1 /* A sometimes minimal FORTH compiler and tutorial for Linux / i386 systems. -*- asm -*-
2 By Richard W.M. Jones <rich@annexia.org> http://annexia.org/forth
4 gcc -m32 -nostdlib -static -Wl,-Ttext,0 -o jonesforth jonesforth.S
6 INTRODUCTION ----------------------------------------------------------------------
8 FORTH is one of those alien languages which most working programmers regard in the same
9 way as Haskell, LISP, and so on. Something so strange that they'd rather any thoughts
10 of it just go away so they can get on with writing this paying code. But that's wrong
11 and if you care at all about programming then you should at least understand all these
12 languages, even if you will never use them.
14 LISP is the ultimate high-level language, and features from LISP are being added every
15 decade to the more common languages. But FORTH is in some ways the ultimate in low level
16 programming. Out of the box it lacks features like dynamic memory management and even
17 strings. In fact, at its primitive level it lacks even basic concepts like IF-statements
20 Why then would you want to learn FORTH? There are several very good reasons. First
21 and foremost, FORTH is minimal. You really can write a complete FORTH in, say, 2000
22 lines of code. I don't just mean a FORTH program, I mean a complete FORTH operating
23 system, environment and language. You could boot such a FORTH on a bare PC and it would
24 come up with a prompt where you could start doing useful work. The FORTH you have here
25 isn't minimal and uses a Linux process as its 'base PC' (both for the purposes of making
26 it a good tutorial). It's possible to completely understand the system. Who can say they
27 completely understand how Linux works, or gcc?
29 Secondly FORTH has a peculiar bootstrapping property. By that I mean that after writing
30 a little bit of assembly to talk to the hardware and implement a few primitives, all the
31 rest of the language and compiler is written in FORTH itself. Remember I said before
32 that FORTH lacked IF-statements and loops? Well of course it doesn't really because
33 such a lanuage would be useless, but my point was rather that IF-statements and loops are
34 written in FORTH itself.
36 Now of course this is common in other languages as well, and in those languages we call
37 them 'libraries'. For example in C, 'printf' is a library function written in C. But
38 in FORTH this goes way beyond mere libraries. Can you imagine writing C's 'if' in C?
39 And that brings me to my third reason: If you can write 'if' in FORTH, then why restrict
40 yourself to the usual if/while/for/switch constructs? You want a construct that iterates
41 over every other element in a list of numbers? You can add it to the language. What
42 about an operator which pulls in variables directly from a configuration file and makes
43 them available as FORTH variables? Or how about adding Makefile-like dependencies to
44 the language? No problem in FORTH. This concept isn't common in programming languages,
45 but it has a name (in fact two names): "macros" (by which I mean LISP-style macros, not
46 the lame C preprocessor) and "domain specific languages" (DSLs).
48 This tutorial isn't about learning FORTH as the language. I'll point you to some references
49 you should read if you're not familiar with using FORTH. This tutorial is about how to
50 write FORTH. In fact, until you understand how FORTH is written, you'll have only a very
51 superficial understanding of how to use it.
53 So if you're not familiar with FORTH or want to refresh your memory here are some online
56 http://en.wikipedia.org/wiki/Forth_%28programming_language%29
58 http://galileo.phys.virginia.edu/classes/551.jvn.fall01/primer.htm
60 http://wiki.laptop.org/go/Forth_Lessons
62 Here is another "Why FORTH?" essay: http://www.jwdt.com/~paysan/why-forth.html
64 SETTING UP ----------------------------------------------------------------------
66 Let's get a few housekeeping things out of the way. Firstly because I need to draw lots of
67 ASCII-art diagrams to explain concepts, the best way to look at this is using a window which
68 uses a fixed width font and is at least this wide:
70 <------------------------------------------------------------------------------------------------------------------------>
72 Secondly make sure TABS are set to 8 characters. The following should be a vertical
73 line. If not, sort out your tabs.
79 Thirdly I assume that your screen is at least 50 characters high.
81 ASSEMBLING ----------------------------------------------------------------------
83 If you want to actually run this FORTH, rather than just read it, you will need Linux on an
84 i386. Linux because instead of programming directly to the hardware on a bare PC which I
85 could have done, I went for a simpler tutorial by assuming that the 'hardware' is a Linux
86 process with a few basic system calls (read, write and exit and that's about all). i386
87 is needed because I had to write the assembly for a processor, and i386 is by far the most
88 common. (Of course when I say 'i386', any 32- or 64-bit x86 processor will do. I'm compiling
89 this on a 64 bit AMD Opteron).
91 Again, to assemble this you will need gcc and gas (the GNU assembler). The commands to
92 assemble and run the code (save this file as 'jonesforth.S') are:
94 gcc -m32 -nostdlib -static -Wl,-Ttext,0 -o jonesforth jonesforth.S
97 You will see lots of 'Warning: unterminated string; newline inserted' messages from the
98 assembler. That's just because the GNU assembler doesn't have a good syntax for multi-line
99 strings (or rather it used to, but the developers removed it!) so I've abused the syntax
100 slightly to make things readable. Ignore these warnings.
102 ASSEMBLER ----------------------------------------------------------------------
104 (You can just skip to the next section -- you don't need to be able to read assembler to
105 follow this tutorial).
107 However if you do want to read the assembly code here are a few notes about gas (the GNU assembler):
109 (1) Register names are prefixed with '%', so %eax is the 32 bit i386 accumulator. The registers
110 available on i386 are: %eax, %ebx, %ecx, %edx, %esi, %edi, %ebp and %esp, and most of them
111 have special purposes.
113 (2) Add, mov, etc. take arguments in the form SRC,DEST. So mov %eax,%ecx moves %eax -> %ecx
115 (3) Constants are prefixed with '$', and you mustn't forget it! If you forget it then it
116 causes a read from memory instead, so:
117 mov $2,%eax moves number 2 into %eax
118 mov 2,%eax reads the 32 bit word from address 2 into %eax (ie. most likely a mistake)
120 (4) gas has a funky syntax for local labels, where '1f' (etc.) means label '1:' "forwards"
121 and '1b' (etc.) means label '1:' "backwards".
123 (5) 'ja' is "jump if above", 'jb' for "jump if below", 'je' "jump if equal" etc.
125 (6) gas has a reasonably nice .macro syntax, and I use them a lot to make the code shorter and
128 For more help reading the assembler, do "info gas" at the Linux prompt.
130 Now the tutorial starts in earnest.
132 THE DICTIONARY ----------------------------------------------------------------------
134 In FORTH as you will know, functions are called "words", as just as in other languages they
135 have a name and a definition. Here are two FORTH words:
137 : DOUBLE DUP + ; \ name is "DOUBLE", definition is "DUP +"
138 : QUADRUPLE DOUBLE DOUBLE ; \ name is "QUADRUPLE", definition is "DOUBLE DOUBLE"
140 Words, both built-in ones and ones which the programmer defines later, are stored in a dictionary
141 which is just a linked list of dictionary entries.
143 <--- DICTIONARY ENTRY (HEADER) ----------------------->
144 +------------------------+--------+---------- - - - - +----------- - - - -
145 | LINK POINTER | LENGTH/| NAME | DEFINITION
147 +--- (4 bytes) ----------+- byte -+- n bytes - - - - +----------- - - - -
149 I'll come to the definition of the word later. For now just look at the header. The first
150 4 bytes are the link pointer. This points back to the previous word in the dictionary, or, for
151 the first word in the dictionary it is just a NULL pointer. Then comes a length/flags byte.
152 The length of the word can be up to 31 characters (5 bits used) and the top three bits are used
153 for various flags which I'll come to later. This is followed by the name itself, and in this
154 implementation the name is rounded up to a multiple of 4 bytes by padding it with zero bytes.
155 That's just to ensure that the definition starts on a 32 bit boundary.
157 A FORTH variable called LATEST contains a pointer to the most recently defined word, in
158 other words, the head of this linked list.
160 DOUBLE and QUADRUPLE might look like this:
162 pointer to previous word
165 +--|------+---+---+---+---+---+---+---+---+------------- - - - -
166 | LINK | 6 | D | O | U | B | L | E | 0 | (definition ...)
167 +---------+---+---+---+---+---+---+---+---+------------- - - - -
170 +--|------+---+---+---+---+---+---+---+---+---+---+---+---+------------- - - - -
171 | LINK | 9 | Q | U | A | D | R | U | P | L | E | 0 | 0 | (definition ...)
172 +---------+---+---+---+---+---+---+---+---+---+---+---+---+------------- - - - -
178 You shoud be able to see from this how you might implement functions to find a word in
179 the dictionary (just walk along the dictionary entries starting at LATEST and matching
180 the names until you either find a match or hit the NULL pointer at the end of the dictionary),
181 and add a word to the dictionary (create a new definition, set its LINK to LATEST, and set
182 LATEST to point to the new word). We'll see precisely these functions implemented in
183 assembly code later on.
185 One interesting consequence of using a linked list is that you can redefine words, and
186 a newer definition of a word overrides an older one. This is an important concept in
187 FORTH because it means that any word (even "built-in" or "standard" words) can be
188 overridden with a new definition, either to enhance it, to make it faster or even to
189 disable it. However because of the way that FORTH words get compiled, which you'll
190 understand below, words defined using the old definition of a word continue to use
191 the old definition. Only words defined after the new definition use the new definition.
193 DIRECT THREADED CODE ----------------------------------------------------------------------
195 Now we'll get to the really crucial bit in understanding FORTH, so go and get a cup of tea
196 or coffee and settle down. It's fair to say that if you don't understand this section, then you
197 won't "get" how FORTH works, and that would be a failure on my part for not explaining it well.
198 So if after reading this section a few times you don't understand it, please email me
201 Let's talk first about what "threaded code" means. Imagine a peculiar version of C where
202 you are only allowed to call functions without arguments. (Don't worry for now that such a
203 language would be completely useless!) So in our peculiar C, code would look like this:
212 and so on. How would a function, say 'f' above, be compiled by a standard C compiler?
213 Probably into assembly code like this. On the right hand side I've written the actual
217 CALL a E8 08 00 00 00
218 CALL b E8 1C 00 00 00
219 CALL c E8 2C 00 00 00
220 ; ignore the return from the function for now
222 "E8" is the x86 machine code to "CALL" a function. In the first 20 years of computing
223 memory was hideously expensive and we might have worried about the wasted space being used
224 by the repeated "E8" bytes. We can save 20% in code size (and therefore, in expensive memory)
225 by compressing this into just:
227 08 00 00 00 Just the function addresses, without
228 1C 00 00 00 the CALL prefix.
231 Of course this code won't run directly any more. Instead we need to write an interpreter
232 which takes each pair of bytes and calls it.
234 On an i386 machine it turns out that we can write this interpreter rather easily, in just
235 two assembly instructions which turn into just 3 bytes of machine code. Let's store the
236 pointer to the next word to execute in the %esi register:
238 08 00 00 00 <- We're executing this one now. %esi is the _next_ one to execute.
242 The all-important x86 instruction is called LODSL (or in Intel manuals, LODSW). It does
243 two things. Firstly it reads the memory at %esi into the accumulator (%eax). Secondly it
244 increments %esi by 4 bytes. So after LODSL, the situation now looks like this:
246 08 00 00 00 <- We're still executing this one
247 1C 00 00 00 <- %eax now contains this address (0x0000001C)
250 Now we just need to jump to the address in %eax. This is again just a single x86 instruction
251 written JMP *(%eax). And after doing the jump, the situation looks like:
254 1C 00 00 00 <- Now we're executing this subroutine.
257 To make this work, each subroutine is followed by the two instructions 'LODSL; JMP *(%eax)'
258 which literally make the jump to the next subroutine.
260 And that brings us to our first piece of actual code! Well, it's a macro.
269 /* The macro is called NEXT. That's a FORTH-ism. It expands to those two instructions.
271 Every FORTH primitive that we write has to be ended by NEXT. Think of it kind of like
274 The above describes what is known as direct threaded code.
276 To sum up: We compress our function calls down to a list of addresses and use a somewhat
277 magical macro to act as a "jump to next function in the list". We also use one register (%esi)
278 to act as a kind of instruction pointer, pointing to the next function in the list.
280 I'll just give you a hint of what is to come by saying that a FORTH definition such as:
282 : QUADRUPLE DOUBLE DOUBLE ;
284 actually compiles (almost, not precisely but we'll see why in a moment) to a list of
285 function addresses for DOUBLE, DOUBLE and a special function called EXIT to finish off.
287 At this point, REALLY EAGLE-EYED ASSEMBLY EXPERTS are saying "JONES, YOU'VE MADE A MISTAKE!".
289 I lied about JMP *(%eax).
291 INDIRECT THREADED CODE ----------------------------------------------------------------------
293 It turns out that direct threaded code is interesting but only if you want to just execute
294 a list of functions written in assembly language. So QUADRUPLE would work only if DOUBLE
295 was an assembly language function. In the direct threaded code, QUADRUPLE would look like:
298 | addr of DOUBLE --------------------> (assembly code to do the double)
299 +------------------+ NEXT
300 %esi -> | addr of DOUBLE |
303 We can add an extra indirection to allow us to run both words written in assembly language
304 (primitives written for speed) and words written in FORTH themselves as lists of addresses.
306 The extra indirection is the reason for the brackets in JMP *(%eax).
308 Let's have a look at how QUADRUPLE and DOUBLE really look in FORTH:
310 : QUADRUPLE DOUBLE DOUBLE ;
313 | codeword | : DOUBLE DUP + ;
315 | addr of DOUBLE ---------------> +------------------+
316 +------------------+ | codeword |
317 | addr of DOUBLE | +------------------+
318 +------------------+ | addr of DUP --------------> +------------------+
319 | addr of EXIT | +------------------+ | codeword -------+
320 +------------------+ %esi -> | addr of + --------+ +------------------+ |
321 +------------------+ | | assembly to <-----+
322 | addr of EXIT | | | implement DUP |
323 +------------------+ | | .. |
326 | +------------------+
328 +-----> +------------------+
330 +------------------+ |
331 | assembly to <------+
338 This is the part where you may need an extra cup of tea/coffee/favourite caffeinated
339 beverage. What has changed is that I've added an extra pointer to the beginning of
340 the definitions. In FORTH this is sometimes called the "codeword". The codeword is
341 a pointer to the interpreter to run the function. For primitives written in
342 assembly language, the "interpreter" just points to the actual assembly code itself.
344 In words written in FORTH (like QUADRUPLE and DOUBLE), the codeword points to an interpreter
347 I'll show you the interpreter function shortly, but let's recall our indirect
348 JMP *(%eax) with the "extra" brackets. Take the case where we're executing DOUBLE
349 as shown, and DUP has been called. Note that %esi is pointing to the address of +.
351 The assembly code for DUP eventually does a NEXT. That:
353 (1) reads the address of + into %eax %eax points to the codeword of +
354 (2) increments %esi by 4
355 (3) jumps to the indirect %eax jumps to the address in the codeword of +,
356 ie. the assembly code to implement +
364 /* Macros to deal with the return stack. */
366 lea -4(%ebp),%ebp // push reg on to return stack
371 mov (%ebp),\reg // pop top of return stack to reg
375 /* ELF entry point. */
380 mov %esp,var_S0 // Store the initial data stack pointer.
381 mov $return_stack,%ebp // Initialise the return stack.
383 mov $cold_start,%esi // Initialise interpreter.
384 NEXT // Run interpreter!
387 cold_start: // High-level code without a codeword.
390 /* DOCOL - the interpreter! */
394 PUSHRSP %esi // push %esi on to the return stack
395 addl $4,%eax // %eax points to codeword, so make
396 movl %eax,%esi // %esi point to first data word
399 /*----------------------------------------------------------------------
400 * Fixed sized buffers for everything.
404 /* FORTH return stack. */
405 #define RETURN_STACK_SIZE 8192
407 .space RETURN_STACK_SIZE
410 /* Space for user-defined words. */
411 #define USER_DEFS_SIZE 16384
414 .space USER_DEFS_SIZE
421 /*----------------------------------------------------------------------
422 * Built-in words defined the long way.
425 #define F_HIDDEN 0x20
427 // Store the chain of links.
430 .macro defcode name, namelen, flags=0, label
436 .set link,name_\label
437 .byte \flags+\namelen // flags + length byte
438 .ascii "\name" // the name
442 .int code_\label // codeword
446 code_\label : // assembler code follows
449 .macro defword name, namelen, flags=0, label
455 .set link,name_\label
456 .byte \flags+\namelen // flags + length byte
457 .ascii "\name" // the name
461 .int DOCOL // codeword - the interpreter
462 // list of word pointers follow
465 .macro defvar name, namelen, flags=0, label, initial=0
466 defcode \name,\namelen,\flags,\label
475 // Some easy ones, written in assembly for speed
476 defcode "DROP",4,,DROP
477 pop %eax // drop top of stack
481 pop %eax // duplicate top of stack
486 defcode "SWAP",4,,SWAP
487 pop %eax // swap top of stack
493 defcode "OVER",4,,OVER
494 mov 4(%esp),%eax // get the second element of stack
495 push %eax // and push it on top
507 defcode "-ROT",4,,NROT
517 incl (%esp) // increment top of stack
521 decl (%esp) // decrement top of stack
524 defcode "4+",2,,INCR4
525 addl $4,(%esp) // increment top of stack
528 defcode "4-",2,,DECR4
529 subl $4,(%esp) // decrement top of stack
546 push %eax // ignore overflow
554 push %eax // push quotient
562 push %edx // push remainder
565 defcode "=",1,,EQU // top two words are equal?
575 defcode "<>",2,,NEQU // top two words are not equal?
585 defcode "0=",2,,ZEQU // top of stack equals 0?
604 defcode "INVERT",6,,INVERT
608 // COLD must not return (ie. must not call EXIT).
609 defword "COLD",4,,COLD
610 // XXX reinitialisation of the interpreter
611 .int INTERPRETER // call the interpreter loop (never returns)
612 .int LIT,1,SYSEXIT // hmmm, but in case it does, exit(1).
614 defcode "EXIT",4,,EXIT
615 POPRSP %esi // pop return stack into %esi
619 // %esi points to the next command, but in this case it points to the next
620 // literal 32 bit integer. Get that literal into %eax and increment %esi.
621 // On x86, it's a convenient single byte instruction! (cf. NEXT macro)
623 push %eax // push the literal number on to stack
626 defcode "LITSTRING",9,,LITSTRING
627 lodsl // get the length of the string
628 push %eax // push it on the stack
629 push %esi // push the address of the start of the string
630 addl %eax,%esi // skip past the string
631 addl $3,%esi // but round up to next 4 byte boundary
635 defcode "BRANCH",6,,BRANCH
636 add (%esi),%esi // add the offset to the instruction pointer
639 defcode "0BRANCH",7,,ZBRANCH
641 test %eax,%eax // top of stack is zero?
642 jz code_BRANCH // if so, jump back to the branch function above
643 lodsl // otherwise we need to skip the offset
647 pop %ebx // address to store at
648 pop %eax // data to store there
649 mov %eax,(%ebx) // store it
653 pop %ebx // address to fetch
654 mov (%ebx),%eax // fetch it
655 push %eax // push value onto stack
658 defcode "+!",2,,ADDSTORE
660 pop %eax // the amount to add
661 addl %eax,(%ebx) // add it
664 defcode "-!",2,,SUBSTORE
666 pop %eax // the amount to subtract
667 subl %eax,(%ebx) // add it
670 /* ! and @ (STORE and FETCH) store 32-bit words. It's also useful to be able to read and write bytes.
671 * I don't know whether FORTH has these words, so I invented my own, called !b and @b.
672 * Byte-oriented operations only work on architectures which permit them (i386 is one of those).
673 * UPDATE: writing a byte to the dictionary pointer is called C, in FORTH.
675 defcode "!b",2,,STOREBYTE
676 pop %ebx // address to store at
677 pop %eax // data to store there
678 movb %al,(%ebx) // store it
681 defcode "@b",2,,FETCHBYTE
682 pop %ebx // address to fetch
684 movb (%ebx),%al // fetch it
685 push %eax // push value onto stack
688 // The STATE variable is 0 for execute mode, != 0 for compile mode
689 defvar "STATE",5,,STATE
691 // This points to where compiled words go.
692 defvar "HERE",4,,HERE,user_defs_start
694 // This is the last definition in the dictionary.
695 defvar "LATEST",6,,LATEST,name_SYSEXIT // SYSEXIT must be last in built-in dictionary
697 // _X, _Y and _Z are scratch variables used by standard words.
702 // This stores the top of the data stack.
705 // This stores the top of the return stack.
706 defvar "R0",2,,RZ,return_stack
708 defcode "DSP@",4,,DSPFETCH
713 defcode "DSP!",4,,DSPSTORE
718 pop %eax // pop parameter stack into %eax
719 PUSHRSP %eax // push it on to the return stack
722 defcode "R>",2,,FROMR
723 POPRSP %eax // pop return stack on to %eax
724 push %eax // and push on to parameter stack
727 defcode "RSP@",4,,RSPFETCH
731 defcode "RSP!",4,,RSPSTORE
735 defcode "RDROP",5,,RDROP
736 lea 4(%ebp),%ebp // pop return stack and throw away
739 #include <asm-i386/unistd.h>
743 push %eax // push return value on stack
755 1: // out of input; use read(2) to fetch more input from stdin
756 xor %ebx,%ebx // 1st param: stdin
757 mov $buffer,%ecx // 2nd param: buffer
759 mov $buffend-buffer,%edx // 3rd param: max length
760 mov $__NR_read,%eax // syscall: read
762 test %eax,%eax // If %eax <= 0, then exit.
764 addl %eax,%ecx // buffer+%eax = bufftop
768 2: // error or out of input: exit
770 mov $__NR_exit,%eax // syscall: exit
773 defcode "EMIT",4,,EMIT
778 mov $1,%ebx // 1st param: stdout
780 // write needs the address of the byte to write
782 mov $2f,%ecx // 2nd param: address
784 mov $1,%edx // 3rd param: nbytes = 1
786 mov $__NR_write,%eax // write syscall
791 2: .space 1 // scratch used by EMIT
793 defcode "WORD",4,,WORD
795 push %ecx // push length
796 push %edi // push base address
800 /* Search for first non-blank character. Also skip \ comments. */
802 call _KEY // get next key, returned in %eax
803 cmpb $'\\',%al // start of a comment?
804 je 3f // if so, skip the comment
806 jbe 1b // if so, keep looking
808 /* Search for the end of the word, storing chars as we go. */
809 mov $5f,%edi // pointer to return buffer
811 stosb // add character to return buffer
812 call _KEY // get next key, returned in %al
813 cmpb $' ',%al // is blank?
814 ja 2b // if not, keep looping
816 /* Return the word (well, the static buffer) and length. */
818 mov %edi,%ecx // return length of the word
819 mov $5f,%edi // return address of the word
822 /* Code to skip \ comments to end of the current line. */
825 cmpb $'\n',%al // end of line yet?
830 // A static buffer where WORD returns. Subsequent calls
831 // overwrite this buffer. Maximum word length is 32 chars.
834 defcode "EMITSTRING",10,,EMITSTRING
835 mov $1,%ebx // 1st param: stdout
836 pop %ecx // 2nd param: address of string
837 pop %edx // 3rd param: length of string
839 mov $__NR_write,%eax // write syscall
845 pop %eax // Get the number to print into %eax
846 call _DOT // Easier to do this recursively ...
849 mov $10,%ecx // Base 10
853 xor %edx,%edx // %edx:%eax / %ecx -> quotient %eax, remainder %edx
867 // Parse a number from a string on the stack -- almost the opposite of . (DOT)
868 // Note that there is absolutely no error checking. In particular the length of the
869 // string must be >= 1 bytes.
870 defcode "SNUMBER",7,,SNUMBER
880 imull $10,%eax // %eax *= 10
883 subb $'0',%bl // ASCII -> digit
889 defcode "FIND",4,,FIND
890 pop %edi // %edi = address
891 pop %ecx // %ecx = length
897 push %esi // Save %esi so we can use it in string comparison.
899 // Now we start searching backwards through the dictionary for this word.
900 mov var_LATEST,%edx // LATEST points to name header of the latest word in the dictionary
902 test %edx,%edx // NULL pointer? (end of the linked list)
905 // Compare the length expected and the length of the word.
906 // Note that if the F_HIDDEN flag is set on the word, then by a bit of trickery
907 // this won't pick the word (the length will appear to be wrong).
909 movb 4(%edx),%al // %al = flags+length field
910 andb $(F_HIDDEN|0x1f),%al // %al = name length
911 cmpb %cl,%al // Length is the same?
914 // Compare the strings in detail.
915 push %ecx // Save the length
916 push %edi // Save the address (repe cmpsb will move this pointer)
917 lea 5(%edx),%esi // Dictionary string we are checking against.
918 repe cmpsb // Compare the strings.
921 jne 2f // Not the same.
923 // The strings are the same - return the header pointer in %eax
929 mov (%edx),%edx // Move back through the link field to the previous word
930 jmp 1b // .. and loop.
934 xor %eax,%eax // Return zero to indicate not found.
937 defcode ">CFA",4,,TCFA // DEA -> Codeword address
944 add $4,%edi // Skip link pointer.
945 movb (%edi),%al // Load flags+len into %al.
946 inc %edi // Skip flags+len byte.
947 andb $0x1f,%al // Just the length, not the flags.
948 add %eax,%edi // Skip the name.
949 addl $3,%edi // The codeword is 4-byte aligned.
953 defcode "CHAR",4,,CHAR
954 call _WORD // Returns %ecx = length, %edi = pointer to word.
956 movb (%edi),%al // Get the first character of the word.
957 push %eax // Push it onto the stack.
962 // Get the word and create a dictionary entry header for it.
963 call _WORD // Returns %ecx = length, %edi = pointer to word.
964 mov %edi,%ebx // %ebx = address of the word
966 movl var_HERE,%edi // %edi is the address of the header
967 movl var_LATEST,%eax // Get link pointer
968 stosl // and store it in the header.
970 mov %cl,%al // Get the length.
971 orb $F_HIDDEN,%al // Set the HIDDEN flag on this entry.
972 stosb // Store the length/flags byte.
974 mov %ebx,%esi // %esi = word
975 rep movsb // Copy the word
977 addl $3,%edi // Align to next 4 byte boundary.
980 movl $DOCOL,%eax // The codeword for user-created words is always DOCOL (the interpreter)
983 // Header built, so now update LATEST and HERE.
984 // We'll be compiling words and putting them HERE.
989 // And go into compile mode by setting STATE to 1.
994 pop %eax // Code pointer to store.
998 movl var_HERE,%edi // HERE
1000 movl %edi,var_HERE // Update HERE (incremented)
1003 defcode "HIDDEN",6,,HIDDEN
1007 movl var_LATEST,%edi // LATEST word.
1008 addl $4,%edi // Point to name/flags byte.
1009 xorb $F_HIDDEN,(%edi) // Toggle the HIDDEN bit.
1012 defcode "IMMEDIATE",9,F_IMMED,IMMEDIATE
1016 movl var_LATEST,%edi // LATEST word.
1017 addl $4,%edi // Point to name/flags byte.
1018 xorb $F_IMMED,(%edi) // Toggle the IMMED bit.
1021 defcode ";",1,F_IMMED,SEMICOLON
1022 movl $EXIT,%eax // EXIT is the final codeword in compiled words.
1023 call _COMMA // Store it.
1024 call _HIDDEN // Toggle the HIDDEN flag (unhides the new word).
1025 xor %eax,%eax // Set STATE to 0 (back to execute mode).
1029 /* This definiton of ' (TICK) is strictly cheating - it also only works in compiled code. */
1031 lodsl // Get the address of the next word and skip it.
1032 pushl %eax // Push it on the stack.
1035 /* This interpreter is pretty simple, but remember that in FORTH you can always override
1036 * it later with a more powerful one!
1038 defword "INTERPRETER",11,,INTERPRETER
1039 .int INTERPRET,RDROP,INTERPRETER
1041 defcode "INTERPRET",9,,INTERPRET
1042 call _WORD // Returns %ecx = length, %edi = pointer to word.
1044 // Is it in the dictionary?
1046 movl %eax,interpret_is_lit // Not a literal number (not yet anyway ...)
1047 call _FIND // Returns %eax = pointer to header or 0 if not found.
1048 test %eax,%eax // Found?
1051 // In the dictionary. Is it an IMMEDIATE codeword?
1052 mov %eax,%edi // %edi = dictionary entry
1053 movb 4(%edi),%al // Get name+flags.
1054 push %ax // Just save it for now.
1055 call _TCFA // Convert dictionary entry (in %edi) to codeword pointer.
1057 andb $F_IMMED,%al // Is IMMED flag set?
1059 jnz 4f // If IMMED, jump straight to executing.
1063 1: // Not in the dictionary (not a word) so assume it's a literal number.
1064 incl interpret_is_lit
1065 call _SNUMBER // Returns the parsed number in %eax
1067 mov $LIT,%eax // The word is LIT
1069 2: // Are we compiling or executing?
1072 jz 4f // Jump if executing.
1074 // Compiling - just append the word to the current dictionary definition.
1076 mov interpret_is_lit,%ecx // Was it a literal?
1079 mov %ebx,%eax // Yes, so LIT is followed by a number.
1083 4: // Executing - run it!
1084 mov interpret_is_lit,%ecx // Literal?
1085 test %ecx,%ecx // Literal?
1088 // Not a literal, execute it now. This never returns, but the codeword will
1089 // eventually call NEXT which will reenter the loop in INTERPRETER.
1092 5: // Executing a literal, which means push it on the stack.
1099 .int 0 // Flag used to record if reading a literal
1101 // NB: SYSEXIT must be the last entry in the built-in dictionary.
1102 defcode SYSEXIT,7,,SYSEXIT
1107 /*----------------------------------------------------------------------
1108 * Input buffer & initial input.
1113 // XXX gives 'Warning: unterminated string; newline inserted' messages which you can ignore
1115 \\ Define some character constants
1121 \\ CR prints a carriage return
1124 \\ SPACE prints a space
1125 : SPACE 'SPACE' EMIT ;
1127 \\ Primitive . (DOT) function doesn't follow with a blank, so redefine it to behave like FORTH.
1128 \\ Notice how we can trivially redefine existing functions.
1131 \\ DUP, DROP are defined in assembly for speed, but this is how you might define them
1132 \\ in FORTH. Notice use of the scratch variables _X and _Y.
1133 \\ : DUP _X ! _X @ _X @ ;
1136 \\ The 2... versions of the standard operators work on pairs of stack entries. They're not used
1137 \\ very commonly so not really worth writing in assembler. Here is how they are defined in FORTH.
1141 \\ More standard FORTH words.
1145 \\ [ and ] allow you to break into immediate mode while compiling a word.
1146 : [ IMMEDIATE \\ define [ as an immediate word
1147 0 STATE ! \\ go into immediate mode
1151 1 STATE ! \\ go back to compile mode
1154 \\ LITERAL takes whatever is on the stack and compiles LIT <foo>
1156 ' LIT , \\ compile LIT
1157 , \\ compile the literal itself (from the stack)
1160 \\ condition IF true-part THEN rest
1162 \\ condition 0BRANCH OFFSET true-part rest
1163 \\ where OFFSET is the offset of 'rest'
1164 \\ condition IF true-part ELSE false-part THEN
1166 \\ condition 0BRANCH OFFSET true-part BRANCH OFFSET2 false-part rest
1167 \\ where OFFSET if the offset of false-part and OFFSET2 is the offset of rest
1169 \\ IF is an IMMEDIATE word which compiles 0BRANCH followed by a dummy offset, and places
1170 \\ the address of the 0BRANCH on the stack. Later when we see THEN, we pop that address
1171 \\ off the stack, calculate the offset, and back-fill the offset.
1173 ' 0BRANCH , \\ compile 0BRANCH
1174 HERE @ \\ save location of the offset on the stack
1175 0 , \\ compile a dummy offset
1180 HERE @ SWAP - \\ calculate the offset from the address saved on the stack
1181 SWAP ! \\ store the offset in the back-filled location
1185 ' BRANCH , \\ definite branch to just over the false-part
1186 HERE @ \\ save location of the offset on the stack
1187 0 , \\ compile a dummy offset
1188 SWAP \\ now back-fill the original (IF) offset
1189 DUP \\ same as for THEN word above
1194 \\ BEGIN loop-part condition UNTIL
1196 \\ loop-part condition 0BRANCH OFFSET
1197 \\ where OFFSET points back to the loop-part
1198 \\ This is like do { loop-part } while (condition) in the C language
1200 HERE @ \\ save location on the stack
1204 ' 0BRANCH , \\ compile 0BRANCH
1205 HERE @ - \\ calculate the offset from the address saved on the stack
1206 , \\ compile the offset here
1209 \\ BEGIN loop-part AGAIN
1211 \\ loop-part BRANCH OFFSET
1212 \\ where OFFSET points back to the loop-part
1213 \\ In other words, an infinite loop which can only be returned from with EXIT
1215 ' BRANCH , \\ compile BRANCH
1216 HERE @ - \\ calculate the offset back
1217 , \\ compile the offset here
1220 \\ BEGIN condition WHILE loop-part REPEAT
1222 \\ condition 0BRANCH OFFSET2 loop-part BRANCH OFFSET
1223 \\ where OFFSET points back to condition (the beginning) and OFFSET2 points to after the whole piece of code
1224 \\ So this is like a while (condition) { loop-part } loop in the C language
1226 ' 0BRANCH , \\ compile 0BRANCH
1227 HERE @ \\ save location of the offset2 on the stack
1228 0 , \\ compile a dummy offset2
1232 ' BRANCH , \\ compile BRANCH
1233 SWAP \\ get the original offset (from BEGIN)
1234 HERE @ - , \\ and compile it after BRANCH
1236 HERE @ SWAP - \\ calculate the offset2
1237 SWAP ! \\ and back-fill it in the original location
1240 \\ With the looping constructs, we can now write SPACES, which writes n spaces to stdout.
1243 SPACE \\ print a space
1244 1- \\ until we count down to 0
1249 \\ .S prints the contents of the stack. Very useful for debugging.
1251 DSP@ \\ get current stack pointer
1253 DUP @ . \\ print the stack element
1255 DUP S0 @ 4- = \\ stop when we get to the top
1260 \\ DEPTH returns the depth of the stack.
1261 : DEPTH S0 @ DSP@ - ;
1263 \\ .\" is the print string operator in FORTH. Example: .\" Something to print\"
1264 \\ The space after the operator is the ordinary space required between words.
1265 \\ This is tricky to define because it has to do different things depending on whether
1266 \\ we are compiling or in immediate mode. (Thus the word is marked IMMEDIATE so it can
1267 \\ detect this and do different things).
1268 \\ In immediate mode we just keep reading characters and printing them until we get to
1269 \\ the next double quote.
1270 \\ In compile mode we have the problem of where we're going to store the string (remember
1271 \\ that the input buffer where the string comes from may be overwritten by the time we
1272 \\ come round to running the function). We store the string in the compiled function
1274 \\ LITSTRING, string length, string rounded up to 4 bytes, EMITSTRING, ...
1276 STATE @ \\ compiling?
1278 ' LITSTRING , \\ compile LITSTRING
1279 HERE @ \\ save the address of the length word on the stack
1280 0 , \\ dummy length - we don't know what it is yet
1282 KEY \\ get next character of the string
1285 HERE @ !b \\ store the character in the compiled image
1286 1 HERE +! \\ increment HERE pointer by 1 byte
1288 DROP \\ drop the double quote character at the end
1289 DUP \\ get the saved address of the length word
1290 HERE @ SWAP - \\ calculate the length
1291 4- \\ subtract 4 (because we measured from the start of the length word)
1292 SWAP ! \\ and back-fill the length location
1293 HERE @ \\ round up to next multiple of 4 bytes for the remaining code
1297 ' EMITSTRING , \\ compile the final EMITSTRING
1299 \\ In immediate mode, just read characters and print them until we get
1300 \\ to the ending double quote. Much simpler than the above code!
1303 DUP '\"' = IF EXIT THEN
1309 \\ While compiling, [COMPILE] WORD compiles WORD if it would otherwise be IMMEDIATE.
1310 : [COMPILE] IMMEDIATE
1311 WORD \\ get the next word
1312 FIND \\ find it in the dictionary
1313 >CFA \\ get its codeword
1314 , \\ and compile that
1317 \\ RECURSE makes a recursive call to the current word that is being compiled.
1318 \\ Normally while a word is being compiled, it is marked HIDDEN so that references to the
1319 \\ same word within are calls to the previous definition of the word.
1321 LATEST @ >CFA \\ LATEST points to the word being compiled at the moment
1325 \\ ALLOT is used to allocate (static) memory when compiling. It increases HERE by
1326 \\ the amount given on the stack.
1330 \\ Finally print the welcome prompt.