Native Zeus assembler example files
-----------------------------------

In this folder you will find the latest version of Simon Brattel and Neil 
Mottershead's Zeus assembler for the ZX Spectrum Next, not to be confused 
with the later one which does not run on real Spectrum (or Next) hardware. 
This Zeus was originally published by Sinclair Research in 1983.

Examples are in Zeus's tokenised binary format, which allows more room 
for assembly programs by storing the Z80 mnemonics (RLCA, LDIR, etc) as 
single-byte tokens, much as ZX BASIC does. Zeus also compresses 
contiguous groups of spaces, for the same reason. For each .god file
there is a corresponding un-numbered plain-text .txt file that can be 
loaded into any assembler that supports ASCII source files.

For updates or feedback please see http://simon.mooli.org.uk/nextech/z80n


EXAMPLE FILES

Example files show how to use Zeus to write a dot command and read the
keyboard from machine language by using the floating point calculator
language built into the ZX ROM. There are also files defining names for
the most commonly-used 'magic numbers' in Next assembly-language source,
so the code written can be more readable and less error-prone.

All of the following files can be loaded into Zeus by loading Zeus.bas
and entering the stem of the name when prompted for a project name. If
you then assemble the code it and the updated source will be saved with
the same name and the extension .god for tokenised source and .bin for
assembled binary.

----------------------------------------------------------------------

ECHO - a minimal DOT command

ECHO.god

This tiny (336 bytes of source) but complete example shows how to read 
the command arguments  and write messages to any channel from a dot 
command assembled to the  required offset by Zeus. Put whatever you 
like in the middle, but read the Next system documentation before 
you make any assumptions about memory paging!

The assembled ECHO command requires just 17 bytes of assembled Z80 
code. Notice that A is 0 at the end and the Z flag is always set on 
return to signal 'no error' - see the docs for how to return an 
error code or message.

ZX BASIC adds PLUS3DOS headers to files it saves, but those stop 
dot commands loading and working as expected. ECHO.bas solves this
problem by taking the CODE saved after assembly and make a raw file 
which can be placed in C:/DOT directory and run by typing its name, 
e.g.

    .ECHO

The key part of this is the loop at the end that writes a binary 
file with no header. You'll need to do this for any dot command 
written on Next itself and saved as CODE from BASIC.

----------------------------------------------------------------------

Searching Z80 memory fast

find.god is a tokenised Zeus source file (corresponding to the text in 
FIND.ASM) which can search memory at hundreds of bytes or records per
second. FIND.BAS is a test and demonstration program which shows how
to search BASIC string and numeric arrays (from lines 2200 and 2620)
or arbitrary simple strings, bytes or records of data in memory. 

The code is Z80n specific (hurrah?!) and not ROMable and not relocatable.
By default it assembles to the top 43 bytes of Z80 RAM. This is convenient 
for storage above RAMTOP and however many UDGs you want today, and also if 
you want to run it via a USR call from inside a BANK, in which case rather 
than POKEing it to the ORG address 65493 you'd BANK b DPOKE 16341 with the 
words, so they appear at the required ORG when BANK b USR 16341 is called,
as BANKs are paged into offset 49152 in the Z80 memory map while active.
To load and run it from anywhere else, adjust the ORG and DPOKEs to suit.

The DEFs are needed to encode Nextra instructions which are not part of the 
1983-vintage Z80 set directly supported by Zeus's tokeniser. Don't try to 
step over those with a standard Z80 debugger like HiSoft's MONS4, or any 
classic Z80 monitor. It'll get confused. Set a breakpoint on the following 
standard Zilog instruction, instead.

HOW TO FIND

The five POKE labels mark (roughly) where parameters should be DPOKEd to tell 
the routine where to look for what, and the structure of the data - raw bytes, 
16-bit words, BASIC array elements, or fixed-sized records with the stuff you 
want to search in a specific field (subset) of each record. For instance if 
your data consists of records of four words and you want to search the first 
of those, set stride to 8 and pattern length to 2.

Five words should be DPOKEd or assembled into the relevant places to configure 
the search. Since it doesn't write to memory (other than the stack) the lack 
of validation doesn't risk causing a crash. If you set a pattern length of 0 
(interpreted as 64K) or an end address before the start (implying a wrap-around 
from 65535 to 0 and onwards) it's just going to be slow. The only thing you 
should avoid is setting the stride - the interval between records - to zero, 
or failing to set it at all. In that case unless it finds a match at once, or 
DMA comes to the rescue, it'll loop forever.

Here are the five setup parameter words and their offsets within the code, from 
its start address:

target start address     +1
target end address       +4
pattern start address    +9
pattern length in bytes  +12
stride between records   +31

The USR call returns 0 if the pattern cannot be found, or an address between the
target start and target end (inclusive, so a long pattern match might extend 
just past the target end) where the the first match was found. To seek 
the following match, adjust target start to match+stride and call again. 
While your BASIC program runs you only need to DPOKE addresses or lengths that
have changed since the last USR call. Unchanged values can be left as set.

The examples of searching BASIC arrays start with a CLEAR and then dimension
the variables concerned immediately after that. This makes the address of A$
and Z$, or A() and T, predictable by DPEEKing the start of the VARS area
pointed to by the system variable at 23627. The various PRINT and IF .. STOP
lines are sanity-checks which can be omitted for speed if you're sure the
variables are in the expected places. 

The routine changes the AF, BC, DE and HL register values. The result is returned 
in the BC register pair, to suit the ZX BASIC USR function. To return it in HL, 
which may be handy if calling the searcher from another Z80 routine, alter the 
last but one line to zero HL rather than BC, and swap the two POP instructions 
at the label FOUND. You could also skip the first couple of lines if you already
have the target addresses in HL and DE.

One quirk is that the carry flag needs to be clear on entry. The only instruction 
that reads and sets the carry flag is SBC; beyond the first character this is 
sure to be clear because of the JR NC,NEXT1, but before that it will be whatever
 it was on entry. After a USR call we can be sure it will be clear as the 
Spectrum ROM flags an invalid address  by setting carry and only jumps to the 
USR address (in BC) if carry is clear immediately before. Otherwise, OR A first.

Testing find

Peak speed for long targets is 201,000 records/s at 28 MHz, or 194,000 with this 
code if the slower HDMI output is used, and around 230,000 records/s in VGA6.

Find.bas contains 34 regression checks and three performance tests, for byte 
(INSTR), string and numeric array lookups, and example searchers for 16-bit 
integers and 3-character month names. It also contains one line to DPOKE the
routine to the top of main memory or the end of any NextBASIC BANK, and code
to save and list the Z80 code bytes from Zeus above RAMtop or convert it to
DATA as line one of a .BAS file to be merged. 

If you use Zeus.bas, the mini-IDE for Zeus, you'll notice one quirk. In general 
the IDE finds and saves generated code automatically after it's assembled but 
in this extraordinary case where the last byte is assembled to the very end 
of RAM - leaving the program counter $ set to zero afterwards - that confuses 
the line to DPEEK the end-address out of Zeus's RAM since a value of 0 there 
normally means there's no code yet. SAVE the day with CODE 65493,43 ;-)

PROC SetFPS() sets the global variable fps to the number of frame interrupts 
per second at the current video output setting. This is used to convert frame 
counts from %DPEEK 23672 into an elapsed time in seconds regardless of your 
choice of display. Before each test the count is reset to zero.

The speed of searching is proportional to the number of records scanned (the 
byte count from the start of the target to the first match, or the end of the 
target if no match is found, divided by the stride, so doubling the stride 
doubles speed) and the number of characters matched at the start of all the 
records scanned. 

So if the pattern is "test" and the target contains a lot of records that 
don't exactly match but start with "t", "te" or "tes", the search will be
slower than if none of the records to be checked starts with "t". 

----------------------------------------------------------------------

Reading CODE INKEY$ with the Floating Point Calculator

The BASIC command INKEY$ is a useful way to detect when a single
 key is currently pressed, and know which key it is. CODE 
INKEY$ returns the ASCII code of the character, e.g. 65 for 
"A", 49 for "1", etc. But it's difficult to call the 
corresponding Z80 routine in the ROM from assembly language, 
because the subroutine returns not a character code in a 
register but a five-byte entry on the BASIC calculator stack.

As well as BASIC and Z80 machine language, every Spectrum 
(and ZX-81) supports an internal language called Floating 
Point Calculator code, which is embedded in Z80 programs 
between RST 40 instructions and 'end-calc' FPC instructions 
that switch from the stack-based Forth-like FPC language 
to the hardware-level Z80 instruction stream.

FPC code is slower than Z80 assemble language but it can 
manipulate strings and five-byte decimal values accurate 
to nine decimal places, as well as the simple bytes and 
16-bit integers natively supported by the Z80n. It is much 
more concise than Z80 code for this purpose, and extensively 
used in the ZX ROM to plot curves and implement complex 
mathematical functions like ATAN, LN and the ^ operator. 
ZX BASIC would be a lot less capable without it.

This example was written to test out the FPC disassembler 
in my Nextramon utility (shipped  alongside Zeus in Tools/Dev) 
and draws on examples from books by Ian Logan. It demonstrates 
a very general way of calling ROM routines even when they do 
not have a convenient entry point or ideal input and output 
expectations for Z80 programmers. 

code-inkey.bin is the code-inkey binary ready to load with 
LOAD "code-inkey.bin" CODE - it is fully relocatable and 
can run from whatever address you load it to.

code-inkey.god is the corrrsponding source code ready to 
load and assemble with Zeus.

65500 3EA6 LD A,166  ; INKEY$
65502 CD282D CALL 11560  ; Stack-A
65505 EF RST  40  ; FPCALC
65506 2F CHR$       
65507 18 VAL$       
65508 1C CODE       
65509 38 End-calc
65510 C3A22D JP 11682  ; Fp-to-BC

Two ROM routines are used to get integer values into and out 
of the floating point calculator. The routine at address 
11560 is known as 'stack-A' and puts the value in the a 
register onto the 'calculator stack' where it does 
arithmetic. In this case the value of A is 166, the token 
of the INKEY$ function in ZX BASIC. The second ROM routine 
serves the opposite purpose. The routine at address 11682 
reads the last value from the calculator stack and stores 
it as 16 bit integer in the BC register pair. This is 
uncoincidentally where USR expects the value it is to 
return to BASIC, so a USR call to address 65500 returns 
to BASIC the result of the preceding sequence of FPC 
instructions.

The ingenious bit is the four-byte sequence after the 
RST 40 instruction switches the Spectrum into FPC language. 

The CHR$ function, FPC token 47 ($2F) works as in BASIC, 
converting a byte value 0..255 into a single-character 
string. Now we have a string "INKEY$" on the stack, Logan 
showed how the much-maligned and misunderstood VAL$ 
function can be called to evaluate this 'string expression'. 
Token 24 ($18) calls the ROM string expression evaluator, 
which is not otherwise easily accessible, to find the 
string value of VAL$ CHR$ 166.

As in BASIC, VAL$ CHR$ "INKEY$" (where the string contains 
the INKEY$ function token byte 166, rather than the six-
character name) returns the same thing as INKEY$ but by 
a more devious route. In this case the deviation is 
necessary to call the INKEY$ ROM routine in the context 
it expects. The next FPC instruction, byte value 28 
($1C), calls the ROM CODE function. This takes a string 
and converts it into an integer in the same place on the 
FPC stack. Token 56 ($38) stands for 'End-calc' and 
returns from FPC sub-language to Z80 code. The final 
JP to 11682 (Fp-to-BC) gets the stacked value into 
the BC register so it can be returned by USR. As we 
want to return after this, we use JP rather than CALL, 
saving a byte of code and five avoidable memory transfers.

code-inkey.bas

This BASIC example program POKEs the code-inkey routine 
into any specified address and calls it repeatedly in a 
loop until the space key (ASCII code 32) is pressed. 
The PAUSE and BORDER statements in the REPEAT loop 
change the border from blue to red while the USR call 
is being interpreted, showing how long it takes to run. 
It's much slower than using IN to read any single group 
of five keys, but does a lot more work, scanning all 
the keys and converting the result to ASCII as well 
as doing the necessary string and numeric conversions 
required by the ROM routines.

490 POKE 65500,62,166,205,40,45,239,47,24,28,56,195,162,45
495 PAPER 6: CLS 
500 REPEAT 
510 PAUSE 1: BORDER 2:%k=% USR 65500: BORDER 1 
520 REPEAT UNTIL %k=32 
530 STOP 

Just pressing the SHIFT key is enough to alter the timing 
of the routine, moving the border stripes down. Switch 
the CPU speed with RUN AT or the NMI menu to see how 
the border stripes shrink at higher speeds. If the 
border tumbles and flickers this means the loop is 
taking more than one PAUSE frame - around a 50th of 
a second - to complete. At speeds above 3.5 MHz this 
should not be a problem until you put a lot more code
 into the REPEAT loop. You may add this line:

515 PRINT AT 0,0;%k;"  "; : BORDER 0

or similar to see the values being read back - 
and how slow BASIC PRINT commands are. Now the blue 
area of the border shows time spent on line 515 and 
any spare time in the frame appears as a black area.

----------------------------------------------------------------------

MNEMONIC EQUATES

Combining source files

The mnemonic equates are supplied in four separate short .god files 
so you don't need to include more of them in your own program source 
than it requires. The files can easily be merged into a single .god 
file by loading them to successive addresses in memory, over-writing 
the last two bytes of all but the final file with the start of the 
one to follow it in the combined .god file. Then enter Zeus with
GO TO 70, type O to recover the text, and R to renumber the lines 
if you wish, before saving in the usual way. The overlap is needed 
because Zeus puts two $FF bytes to mark the end of source in memory, 
and each saved .god file ends with them. By storing the next file 
over the top of them, a single long file is created:

LOAD "nextras.god" CODE 32768<br>
LOAD "nextreg.god" CODE 32768+952<br>
SAVE "nextset.god" CODE 32768,1566+952<br>

The value 952 is the length of the data in the nextras.god file 
after ignoring the 128 byte header added by NextZXOS and the
 two bytes at the end: 952 = 1082 (from .ls -l) - 128 - 2. 
Likewise 1566 is the length of nextreg.god, without the header 
(so 1694-128) but including the last two bytes. Substitute 
corresponding values to merge any pair of .god files, 
or longer sequences.


sysvars.god

The full set of NextBASIC System Variables documented in the Next manual.
As some of the earlier Sinclair names include underscores Simon N
Goodwin has applied a one-byte patch to Zeus to allow those to be used 
in its assembly source. Earlier versions will not accept such names.


nextreg.god

Symbolic names for the Spectrum Next hardware registers (NextReg). 
The register names are taken from a set worked out by Matt Davies in 
the Spectrum Next Development group on Facebook in September 2020. 
It currently only includes registers accessible to the Copper.


fpcodes.god

ZX floating-point calculator codes. This file includes all the FPC 
instructions documented in Ian Logan's books, and uses similar 
mnemonics to those in his ROM disassembly and output by Nextramon,
the symbolic disassembler I have contributed to the tools/dev folder.

The FPC instruction set is listed in the documentation for Nextramon
on your SD at Guides/Nextramon.gde. This hypertext file includes links 
to the books by Ian Logan which explain how the FPC works and show how 
it can be used. Use the .GUIDE command on the Next itself to read it.

A couple of FPC mnemonics have had to be changed because they have 
the same names as Z80 mnemonics, so OR and NOT must be entered as 
FP_NOT and FP_OR respectively, so the assembled code uses the 
correct binary instruction-set. defb should be used to insert
floating-point constants into the bytecode stream.


nextras.god

This file provides support for extra Z80n instructions unique
to the Spectrum Next and not in any other Zilog-compatible CPU.
Zeus supports the full set of Zilog Z80 machine-code mnemonics, 
but the tokenising scheme does not allow for the 20 extra 
opcodes, all preceded by the $ED prefix, which are unique 
to Next's Z80n processor. It's easy to use those, in unusual 
cases where they're needed, in Zeus or any standard assembler 
by entering the corresponding byte codes e.g. DEFB 237,48 
for MUL D,E, but easier and less error-prone to use symbolic 
names for the new opcodes, e.g.

    DEFB NEXTX,MUL

The token NEXTX is equated to 237, for greater clarity. All
these magic numbers are defined in the nextras.god source file.

This technique does not accommodate the extra register names 
shown in examples of the Z80n instruction set, as it does not 
need to, e.g. MUL D,E is written simply MUL, MIRROR A is MIRROR 
and the BRLC DE,B opcode can be unambiguously written 

    DEFB NEXTX,BRLC

The suffixes serve no semantic purpose as those instructions 
all have unique mnemonics and are hard-wired to work on 
specific registers - there is no BRLC HL,A for example, 
and all the barrel shifter instructions shift DE according 
to a count in register B. The Next opcode jp (c) only uses 
register C but JP_C could too easily be confused with JP C
so nextras.god uses the symbol JP_BC:

    DEFB NEXTX,JP_BC

To add the 8-bit accumulator value to a 16-bit register pair, 
use ADDHL_A or similar.

Four of the Nextras expect to be followed by 16-bit constant 
operands, written NN in Appendix A of the Next manual, e.g. 
ADD HL,NN. Since ADD HL already prefixes several instructions, 
the symbols for Zeus on Next are single words with _W to show
there needs to be a 16-bit constant after the opcode, 
e.g. ADDHL_W, ADDDE_W and ADDBC_W. 

To add 48K to (or equivalently subtract 16K from) HL, enter:

    DEFB NEXTX,ADDHL_W
    DEFW 49152

Similarly, PUSH_W pushes the following 16 bit-word onto the 
stack without using intermediate registers. In fact the Z80n 
does this in a way so alien to the original chip that the 
bytes are the opposite way round from every other 16-bit 
value. This shocking wart does make the FPGA simpler, and 
the Copper co-processor also includes operands backwards 
from the Intel and Zilog convention.

To push the 16-bit hexadecimal value #ABCD onto the stack, 
write:

    DEFB NEXTX,PUSH_W
    DEFB #AB,#CD

Notice how the most significant byte is placed first, the 
opposite of the Intel convention. This is easier to see when 
the values are written in hexadecimal.

TEST n is the new instruction to test the accumulator by
masking its bits with the following operand byte. This is 
similar to AND n except that it does not alter A; it's a 
counterpart instruction, much as CP n is to SUB n. Unlike 
those, TEST is a three byte instruction. This is because 
of the need for a NEXTX prefix byte to sift out the Next 
extension - and many original Zilog opcodes too, as Zilog 
used the same prefix to add many of the Z80 instructions 
the 8080 lacked. This time any byte mask (BIN 01111110 or 
126 here) can follow to complete the instruction on the 
same line:

    DEFB NEXTX,TEST,126

Finally consider the pair of Z80n opcodes to write Next 
registers, documented as NEXTREG r,N to set register 
number r to byte value N, and NEXTREG r,a which sets 
register number r (not to be confused with register R, 
or any CPU register!) to the value in the accumulator. 

To use those in Zeus, the equates are NEXTREG and 
NEXTREGA; append the register number after the 
NEXTREGA with DEFB, or both the register and byte 
value for NEXTREG, e.g.

    DEFB NEXTX,NEXTREG,REG_CPU_SPEED,3
    XOR A
    DEFB NEXTX,NEXTREGA,REG_CPU_SPEED

The first instruction sets the CPU speed to 28 MHz.
The last one sets it to 3.5 MHz, as XOR A clears 
the value in the accumulator.

----------------------------------------------------------------------


Enjoy! Simon N Goodwin, 29th April 2023

Further information: http://simon.mooli.org.uk/nextech
