Indirect threaded code
[jonesforth.git] / jonesforth.S
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
3
4         gcc -m32 -nostdlib -static -Wl,-Ttext,0 -o jonesforth jonesforth.S
5
6         INTRODUCTION ----------------------------------------------------------------------
7
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.
13
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
18         and loops.
19
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?
28
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.
35
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).
47
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.
52
53         So if you're not familiar with FORTH or want to refresh your memory here are some online
54         references to read:
55
56         http://en.wikipedia.org/wiki/Forth_%28programming_language%29
57
58         http://galileo.phys.virginia.edu/classes/551.jvn.fall01/primer.htm
59
60         http://wiki.laptop.org/go/Forth_Lessons
61
62         Here is another "Why FORTH?" essay: http://www.jwdt.com/~paysan/why-forth.html
63
64         SETTING UP ----------------------------------------------------------------------
65
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:
69
70  <------------------------------------------------------------------------------------------------------------------------>
71
72         Secondly make sure TABS are set to 8 characters.  The following should be a vertical
73         line.  If not, sort out your tabs.
74
75         |
76         |
77         |
78
79         Thirdly I assume that your screen is at least 50 characters high.
80
81         ASSEMBLING ----------------------------------------------------------------------
82
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).
90
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:
93
94         gcc -m32 -nostdlib -static -Wl,-Ttext,0 -o jonesforth jonesforth.S
95         ./jonesforth
96
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.
101
102         ASSEMBLER ----------------------------------------------------------------------
103
104         (You can just skip to the next section -- you don't need to be able to read assembler to
105         follow this tutorial).
106
107         However if you do want to read the assembly code here are a few notes about gas (the GNU assembler):
108
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.
112
113         (2) Add, mov, etc. take arguments in the form SRC,DEST.  So mov %eax,%ecx moves %eax -> %ecx
114
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)
119
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".
122
123         (5) 'ja' is "jump if above", 'jb' for "jump if below", 'je' "jump if equal" etc.
124
125         (6) gas has a reasonably nice .macro syntax, and I use them a lot to make the code shorter and
126             less repetitive.
127
128         For more help reading the assembler, do "info gas" at the Linux prompt.
129
130         Now the tutorial starts in earnest.
131
132         THE DICTIONARY ----------------------------------------------------------------------
133
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:
136
137         : DOUBLE DUP + ;                \ name is "DOUBLE", definition is "DUP +"
138         : QUADRUPLE DOUBLE DOUBLE ;     \ name is "QUADRUPLE", definition is "DOUBLE DOUBLE"
139
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.
142
143         <--- DICTIONARY ENTRY (HEADER) ----------------------->
144         +------------------------+--------+---------- - - - - +----------- - - - -
145         | LINK POINTER           | LENGTH/| NAME              | DEFINITION
146         |                        | FLAGS  |                   |
147         +--- (4 bytes) ----------+- byte -+- n bytes  - - - - +----------- - - - -
148
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.
156
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.
159
160         DOUBLE and QUADRUPLE might look like this:
161
162           pointer to previous word
163            ^
164            |
165         +--|------+---+---+---+---+---+---+---+---+------------- - - - -
166         | LINK    | 6 | D | O | U | B | L | E | 0 | (definition ...)
167         +---------+---+---+---+---+---+---+---+---+------------- - - - -
168            ^       len                         padding
169            |
170         +--|------+---+---+---+---+---+---+---+---+---+---+---+---+------------- - - - -
171         | LINK    | 9 | Q | U | A | D | R | U | P | L | E | 0 | 0 | (definition ...)
172         +---------+---+---+---+---+---+---+---+---+---+---+---+---+------------- - - - -
173            ^       len                                     padding
174            |
175            |
176           LATEST
177
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.
184
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.
192
193         DIRECT THREADED CODE ----------------------------------------------------------------------
194
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
199         (rich@annexia.org).
200
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:
204
205         f ()
206         {
207           a ();
208           b ();
209           c ();
210         }
211
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
214         16 bit machine code.
215
216         f:
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
221
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:
226
227         08 00 00 00             Just the function addresses, without
228         1C 00 00 00             the CALL prefix.
229         2C 00 00 00
230
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.
233
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:
237
238                 08 00 00 00     <- We're executing this one now.  %esi is the _next_ one to execute.
239         %esi -> 1C 00 00 00
240                 2C 00 00 00
241
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:
245
246                 08 00 00 00     <- We're still executing this one
247                 1C 00 00 00     <- %eax now contains this address (0x0000001C)
248         %esi -> 2C 00 00 00
249
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:
252
253                 08 00 00 00
254                 1C 00 00 00     <- Now we're executing this subroutine.
255         %esi -> 2C 00 00 00
256
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.
259
260         And that brings us to our first piece of actual code!  Well, it's a macro.
261 */
262
263 /* NEXT macro. */
264         .macro NEXT
265         lodsl
266         jmp *(%eax)
267         .endm
268
269 /*      The macro is called NEXT.  That's a FORTH-ism.  It expands to those two instructions.
270
271         Every FORTH primitive that we write has to be ended by NEXT.  Think of it kind of like
272         a return.
273
274         The above describes what is known as direct threaded code.
275
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.
279
280         I'll just give you a hint of what is to come by saying that a FORTH definition such as:
281
282         : QUADRUPLE DOUBLE DOUBLE ;
283
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.
286
287         At this point, REALLY EAGLE-EYED ASSEMBLY EXPERTS are saying "JONES, YOU'VE MADE A MISTAKE!".
288
289         I lied about JMP *(%eax).  
290
291         INDIRECT THREADED CODE ----------------------------------------------------------------------
292
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:
296
297                 +------------------+
298                 | addr of DOUBLE  --------------------> (assembly code to do the double)
299                 +------------------+                    NEXT
300         %esi -> | addr of DOUBLE   |
301                 +------------------+
302
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.
305
306         The extra indirection is the reason for the brackets in JMP *(%eax).
307
308         Let's have a look at how QUADRUPLE and DOUBLE really look in FORTH:
309
310                 : QUADRUPLE DOUBLE DOUBLE ;
311
312                 +------------------+
313                 | codeword         |               : DOUBLE DUP + ;
314                 +------------------+
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                                                    +------------------+    |       |    ..            |
324                                                                            |       |    ..            |
325                                                                            |       | NEXT             |
326                                                                            |       +------------------+
327                                                                            |
328                                                                            +-----> +------------------+
329                                                                                    | codeword      -------+
330                                                                                    +------------------+   |
331                                                                                    | assembly to   <------+
332                                                                                    | implement +      |
333                                                                                    |    ..            |
334                                                                                    |    ..            |
335                                                                                    | NEXT             |
336                                                                                    +------------------+
337
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.
343
344         In words written in FORTH (like QUADRUPLE and DOUBLE), the codeword points to an interpreter
345         function.
346
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 +.
350
351         The assembly code for DUP eventually does a NEXT.  That:
352
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 +
357
358
359
360
361
362
363
364 /* Macros to deal with the return stack. */
365         .macro PUSHRSP reg
366         lea -4(%ebp),%ebp       // push reg on to return stack
367         movl \reg,(%ebp)
368         .endm
369
370         .macro POPRSP reg
371         mov (%ebp),\reg         // pop top of return stack to reg
372         lea 4(%ebp),%ebp
373         .endm
374
375 /* ELF entry point. */
376         .text
377         .globl _start
378 _start:
379         cld
380         mov %esp,var_S0         // Store the initial data stack pointer.
381         mov $return_stack,%ebp  // Initialise the return stack.
382
383         mov $cold_start,%esi    // Initialise interpreter.
384         NEXT                    // Run interpreter!
385
386         .section .rodata
387 cold_start:                     // High-level code without a codeword.
388         .int COLD
389
390 /* DOCOL - the interpreter! */
391         .text
392         .align 4
393 DOCOL:
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
397         NEXT
398
399 /*----------------------------------------------------------------------
400  * Fixed sized buffers for everything.
401  */
402         .bss
403
404 /* FORTH return stack. */
405 #define RETURN_STACK_SIZE 8192
406         .align 4096
407         .space RETURN_STACK_SIZE
408 return_stack:
409
410 /* Space for user-defined words. */
411 #define USER_DEFS_SIZE 16384
412         .align 4096
413 user_defs_start:
414         .space USER_DEFS_SIZE
415
416
417
418
419
420
421 /*----------------------------------------------------------------------
422  * Built-in words defined the long way.
423  */
424 #define F_IMMED 0x80
425 #define F_HIDDEN 0x20
426
427         // Store the chain of links.
428         .set link,0
429
430         .macro defcode name, namelen, flags=0, label
431         .section .rodata
432         .align 4
433         .globl name_\label
434 name_\label :
435         .int link               // link
436         .set link,name_\label
437         .byte \flags+\namelen   // flags + length byte
438         .ascii "\name"          // the name
439         .align 4
440         .globl \label
441 \label :
442         .int code_\label        // codeword
443         .text
444         .align 4
445         .globl code_\label
446 code_\label :                   // assembler code follows
447         .endm
448
449         .macro defword name, namelen, flags=0, label
450         .section .rodata
451         .align 4
452         .globl name_\label
453 name_\label :
454         .int link               // link
455         .set link,name_\label
456         .byte \flags+\namelen   // flags + length byte
457         .ascii "\name"          // the name
458         .align 4
459         .globl \label
460 \label :
461         .int DOCOL              // codeword - the interpreter
462         // list of word pointers follow
463         .endm
464
465         .macro defvar name, namelen, flags=0, label, initial=0
466         defcode \name,\namelen,\flags,\label
467         push $var_\name
468         NEXT
469         .data
470         .align 4
471 var_\name :
472         .int \initial
473         .endm
474
475         // Some easy ones, written in assembly for speed
476         defcode "DROP",4,,DROP
477         pop %eax                // drop top of stack
478         NEXT
479
480         defcode "DUP",3,,DUP
481         pop %eax                // duplicate top of stack
482         push %eax
483         push %eax
484         NEXT
485
486         defcode "SWAP",4,,SWAP
487         pop %eax                // swap top of stack
488         pop %ebx
489         push %eax
490         push %ebx
491         NEXT
492
493         defcode "OVER",4,,OVER
494         mov 4(%esp),%eax        // get the second element of stack
495         push %eax               // and push it on top
496         NEXT
497
498         defcode "ROT",3,,ROT
499         pop %eax
500         pop %ebx
501         pop %ecx
502         push %eax
503         push %ecx
504         push %ebx
505         NEXT
506
507         defcode "-ROT",4,,NROT
508         pop %eax
509         pop %ebx
510         pop %ecx
511         push %ebx
512         push %eax
513         push %ecx
514         NEXT
515
516         defcode "1+",2,,INCR
517         incl (%esp)             // increment top of stack
518         NEXT
519
520         defcode "1-",2,,DECR
521         decl (%esp)             // decrement top of stack
522         NEXT
523
524         defcode "4+",2,,INCR4
525         addl $4,(%esp)          // increment top of stack
526         NEXT
527
528         defcode "4-",2,,DECR4
529         subl $4,(%esp)          // decrement top of stack
530         NEXT
531
532         defcode "+",1,,ADD
533         pop %eax
534         addl %eax,(%esp)
535         NEXT
536
537         defcode "-",1,,SUB
538         pop %eax
539         subl %eax,(%esp)
540         NEXT
541
542         defcode "*",1,,MUL
543         pop %eax
544         pop %ebx
545         imull %ebx,%eax
546         push %eax               // ignore overflow
547         NEXT
548
549         defcode "/",1,,DIV
550         xor %edx,%edx
551         pop %ebx
552         pop %eax
553         idivl %ebx
554         push %eax               // push quotient
555         NEXT
556
557         defcode "MOD",3,,MOD
558         xor %edx,%edx
559         pop %ebx
560         pop %eax
561         idivl %ebx
562         push %edx               // push remainder
563         NEXT
564
565         defcode "=",1,,EQU      // top two words are equal?
566         pop %eax
567         pop %ebx
568         cmp %ebx,%eax
569         je 1f
570         pushl $0
571         NEXT
572 1:      pushl $1
573         NEXT
574
575         defcode "<>",2,,NEQU    // top two words are not equal?
576         pop %eax
577         pop %ebx
578         cmp %ebx,%eax
579         je 1f
580         pushl $1
581         NEXT
582 1:      pushl $0
583         NEXT
584
585         defcode "0=",2,,ZEQU    // top of stack equals 0?
586         pop %eax
587         test %eax,%eax
588         jz 1f
589         pushl $0
590         NEXT
591 1:      pushl $1
592         NEXT
593
594         defcode "AND",3,,AND
595         pop %eax
596         andl %eax,(%esp)
597         NEXT
598
599         defcode "OR",2,,OR
600         pop %eax
601         orl %eax,(%esp)
602         NEXT
603
604         defcode "INVERT",6,,INVERT
605         notl (%esp)
606         NEXT
607
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).
613
614         defcode "EXIT",4,,EXIT
615         POPRSP %esi             // pop return stack into %esi
616         NEXT
617
618         defcode "LIT",3,,LIT
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)
622         lodsl
623         push %eax               // push the literal number on to stack
624         NEXT
625
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
632         andl $~3,%esi
633         NEXT
634
635         defcode "BRANCH",6,,BRANCH
636         add (%esi),%esi         // add the offset to the instruction pointer
637         NEXT
638
639         defcode "0BRANCH",7,,ZBRANCH
640         pop %eax
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
644         NEXT
645
646         defcode "!",1,,STORE
647         pop %ebx                // address to store at
648         pop %eax                // data to store there
649         mov %eax,(%ebx)         // store it
650         NEXT
651
652         defcode "@",1,,FETCH
653         pop %ebx                // address to fetch
654         mov (%ebx),%eax         // fetch it
655         push %eax               // push value onto stack
656         NEXT
657
658         defcode "+!",2,,ADDSTORE
659         pop %ebx                // address
660         pop %eax                // the amount to add
661         addl %eax,(%ebx)        // add it
662         NEXT
663
664         defcode "-!",2,,SUBSTORE
665         pop %ebx                // address
666         pop %eax                // the amount to subtract
667         subl %eax,(%ebx)        // add it
668         NEXT
669
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.
674  */
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
679         NEXT
680
681         defcode "@b",2,,FETCHBYTE
682         pop %ebx                // address to fetch
683         xor %eax,%eax
684         movb (%ebx),%al         // fetch it
685         push %eax               // push value onto stack
686         NEXT
687
688         // The STATE variable is 0 for execute mode, != 0 for compile mode
689         defvar "STATE",5,,STATE
690
691         // This points to where compiled words go.
692         defvar "HERE",4,,HERE,user_defs_start
693
694         // This is the last definition in the dictionary.
695         defvar "LATEST",6,,LATEST,name_SYSEXIT // SYSEXIT must be last in built-in dictionary
696
697         // _X, _Y and _Z are scratch variables used by standard words.
698         defvar "_X",2,,TX
699         defvar "_Y",2,,TY
700         defvar "_Z",2,,TZ
701
702         // This stores the top of the data stack.
703         defvar "S0",2,,SZ
704
705         // This stores the top of the return stack.
706         defvar "R0",2,,RZ,return_stack
707
708         defcode "DSP@",4,,DSPFETCH
709         mov %esp,%eax
710         push %eax
711         NEXT
712
713         defcode "DSP!",4,,DSPSTORE
714         pop %esp
715         NEXT
716
717         defcode ">R",2,,TOR
718         pop %eax                // pop parameter stack into %eax
719         PUSHRSP %eax            // push it on to the return stack
720         NEXT
721
722         defcode "R>",2,,FROMR
723         POPRSP %eax             // pop return stack on to %eax
724         push %eax               // and push on to parameter stack
725         NEXT
726
727         defcode "RSP@",4,,RSPFETCH
728         push %ebp
729         NEXT
730
731         defcode "RSP!",4,,RSPSTORE
732         pop %ebp
733         NEXT
734
735         defcode "RDROP",5,,RDROP
736         lea 4(%ebp),%ebp        // pop return stack and throw away
737         NEXT
738
739 #include <asm-i386/unistd.h>
740
741         defcode "KEY",3,,KEY
742         call _KEY
743         push %eax               // push return value on stack
744         NEXT
745 _KEY:
746         mov (currkey),%ebx
747         cmp (bufftop),%ebx
748         jge 1f
749         xor %eax,%eax
750         mov (%ebx),%al
751         inc %ebx
752         mov %ebx,(currkey)
753         ret
754
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
758         mov %ecx,currkey
759         mov $buffend-buffer,%edx // 3rd param: max length
760         mov $__NR_read,%eax     // syscall: read
761         int $0x80
762         test %eax,%eax          // If %eax <= 0, then exit.
763         jbe 2f
764         addl %eax,%ecx          // buffer+%eax = bufftop
765         mov %ecx,bufftop
766         jmp _KEY
767
768 2:      // error or out of input: exit
769         xor %ebx,%ebx
770         mov $__NR_exit,%eax     // syscall: exit
771         int $0x80
772
773         defcode "EMIT",4,,EMIT
774         pop %eax
775         call _EMIT
776         NEXT
777 _EMIT:
778         mov $1,%ebx             // 1st param: stdout
779
780         // write needs the address of the byte to write
781         mov %al,(2f)
782         mov $2f,%ecx            // 2nd param: address
783
784         mov $1,%edx             // 3rd param: nbytes = 1
785
786         mov $__NR_write,%eax    // write syscall
787         int $0x80
788         ret
789
790         .bss
791 2:      .space 1                // scratch used by EMIT
792
793         defcode "WORD",4,,WORD
794         call _WORD
795         push %ecx               // push length
796         push %edi               // push base address
797         NEXT
798
799 _WORD:
800         /* Search for first non-blank character.  Also skip \ comments. */
801 1:
802         call _KEY               // get next key, returned in %eax
803         cmpb $'\\',%al          // start of a comment?
804         je 3f                   // if so, skip the comment
805         cmpb $' ',%al
806         jbe 1b                  // if so, keep looking
807
808         /* Search for the end of the word, storing chars as we go. */
809         mov $5f,%edi            // pointer to return buffer
810 2:
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
815
816         /* Return the word (well, the static buffer) and length. */
817         sub $5f,%edi
818         mov %edi,%ecx           // return length of the word
819         mov $5f,%edi            // return address of the word
820         ret
821
822         /* Code to skip \ comments to end of the current line. */
823 3:
824         call _KEY
825         cmpb $'\n',%al          // end of line yet?
826         jne 3b
827         jmp 1b
828
829         .bss
830         // A static buffer where WORD returns.  Subsequent calls
831         // overwrite this buffer.  Maximum word length is 32 chars.
832 5:      .space 32
833
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
838
839         mov $__NR_write,%eax    // write syscall
840         int $0x80
841
842         NEXT
843
844         defcode ".",1,,DOT
845         pop %eax                // Get the number to print into %eax
846         call _DOT               // Easier to do this recursively ...
847         NEXT
848 _DOT:
849         mov $10,%ecx            // Base 10
850 1:
851         cmp %ecx,%eax
852         jb 2f
853         xor %edx,%edx           // %edx:%eax / %ecx -> quotient %eax, remainder %edx
854         idivl %ecx
855         pushl %edx
856         call _DOT
857         popl %eax
858         jmp 1b
859 2:
860         xor %ah,%ah
861         aam $10
862         cwde
863         addl $'0',%eax
864         call _EMIT
865         ret
866
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
871         pop %edi
872         pop %ecx
873         call _SNUMBER
874         push %eax
875         NEXT
876 _SNUMBER:
877         xor %eax,%eax
878         xor %ebx,%ebx
879 1:
880         imull $10,%eax          // %eax *= 10
881         movb (%edi),%bl
882         inc %edi
883         subb $'0',%bl           // ASCII -> digit
884         add %ebx,%eax
885         dec %ecx
886         jnz 1b
887         ret
888
889         defcode "FIND",4,,FIND
890         pop %edi                // %edi = address
891         pop %ecx                // %ecx = length
892         call _FIND
893         push %eax
894         NEXT
895
896 _FIND:
897         push %esi               // Save %esi so we can use it in string comparison.
898
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
901 1:
902         test %edx,%edx          // NULL pointer?  (end of the linked list)
903         je 4f
904
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).
908         xor %eax,%eax
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?
912         jne 2f
913
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.
919         pop %edi
920         pop %ecx
921         jne 2f                  // Not the same.
922
923         // The strings are the same - return the header pointer in %eax
924         pop %esi
925         mov %edx,%eax
926         ret
927
928 2:
929         mov (%edx),%edx         // Move back through the link field to the previous word
930         jmp 1b                  // .. and loop.
931
932 4:      // Not found.
933         pop %esi
934         xor %eax,%eax           // Return zero to indicate not found.
935         ret
936
937         defcode ">CFA",4,,TCFA  // DEA -> Codeword address
938         pop %edi
939         call _TCFA
940         push %edi
941         NEXT
942 _TCFA:
943         xor %eax,%eax
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.
950         andl $~3,%edi
951         ret
952
953         defcode "CHAR",4,,CHAR
954         call _WORD              // Returns %ecx = length, %edi = pointer to word.
955         xor %eax,%eax
956         movb (%edi),%al         // Get the first character of the word.
957         push %eax               // Push it onto the stack.
958         NEXT
959
960         defcode ":",1,,COLON
961
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
965
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.
969
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.
973         push %esi
974         mov %ebx,%esi           // %esi = word
975         rep movsb               // Copy the word
976         pop %esi
977         addl $3,%edi            // Align to next 4 byte boundary.
978         andl $~3,%edi
979
980         movl $DOCOL,%eax        // The codeword for user-created words is always DOCOL (the interpreter)
981         stosl
982
983         // Header built, so now update LATEST and HERE.
984         // We'll be compiling words and putting them HERE.
985         movl var_HERE,%eax
986         movl %eax,var_LATEST
987         movl %edi,var_HERE
988
989         // And go into compile mode by setting STATE to 1.
990         movl $1,var_STATE
991         NEXT
992
993         defcode ",",1,,COMMA
994         pop %eax                // Code pointer to store.
995         call _COMMA
996         NEXT
997 _COMMA:
998         movl var_HERE,%edi      // HERE
999         stosl                   // Store it.
1000         movl %edi,var_HERE      // Update HERE (incremented)
1001         ret
1002
1003         defcode "HIDDEN",6,,HIDDEN
1004         call _HIDDEN
1005         NEXT
1006 _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.
1010         ret
1011
1012         defcode "IMMEDIATE",9,F_IMMED,IMMEDIATE
1013         call _IMMEDIATE
1014         NEXT
1015 _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.
1019         ret
1020
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).
1026         movl %eax,var_STATE
1027         NEXT
1028
1029 /* This definiton of ' (TICK) is strictly cheating - it also only works in compiled code. */
1030         defcode "'",1,,TICK
1031         lodsl                   // Get the address of the next word and skip it.
1032         pushl %eax              // Push it on the stack.
1033         NEXT
1034
1035 /* This interpreter is pretty simple, but remember that in FORTH you can always override
1036  * it later with a more powerful one!
1037  */
1038         defword "INTERPRETER",11,,INTERPRETER
1039         .int INTERPRET,RDROP,INTERPRETER
1040
1041         defcode "INTERPRET",9,,INTERPRET
1042         call _WORD              // Returns %ecx = length, %edi = pointer to word.
1043
1044         // Is it in the dictionary?
1045         xor %eax,%eax
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?
1049         jz 1f
1050
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.
1056         pop %ax
1057         andb $F_IMMED,%al       // Is IMMED flag set?
1058         mov %edi,%eax
1059         jnz 4f                  // If IMMED, jump straight to executing.
1060
1061         jmp 2f
1062
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
1066         mov %eax,%ebx
1067         mov $LIT,%eax           // The word is LIT
1068
1069 2:      // Are we compiling or executing?
1070         movl var_STATE,%edx
1071         test %edx,%edx
1072         jz 4f                   // Jump if executing.
1073
1074         // Compiling - just append the word to the current dictionary definition.
1075         call _COMMA
1076         mov interpret_is_lit,%ecx // Was it a literal?
1077         test %ecx,%ecx
1078         jz 3f
1079         mov %ebx,%eax           // Yes, so LIT is followed by a number.
1080         call _COMMA
1081 3:      NEXT
1082
1083 4:      // Executing - run it!
1084         mov interpret_is_lit,%ecx // Literal?
1085         test %ecx,%ecx          // Literal?
1086         jnz 5f
1087
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.
1090         jmp *(%eax)
1091
1092 5:      // Executing a literal, which means push it on the stack.
1093         push %ebx
1094         NEXT
1095
1096         .data
1097         .align 4
1098 interpret_is_lit:
1099         .int 0                  // Flag used to record if reading a literal
1100
1101         // NB: SYSEXIT must be the last entry in the built-in dictionary.
1102         defcode SYSEXIT,7,,SYSEXIT
1103         pop %ebx
1104         mov $__NR_exit,%eax
1105         int $0x80
1106
1107 /*----------------------------------------------------------------------
1108  * Input buffer & initial input.
1109  */
1110         .data
1111         .align 4096
1112 buffer:
1113         // XXX gives 'Warning: unterminated string; newline inserted' messages which you can ignore
1114         .ascii "\
1115 \\ Define some character constants
1116 : '\\n'   10 ;
1117 : 'SPACE' 32 ;
1118 : '\"'    34 ;
1119 : ':'     58 ;
1120
1121 \\ CR prints a carriage return
1122 : CR '\\n' EMIT ;
1123
1124 \\ SPACE prints a space
1125 : SPACE 'SPACE' EMIT ;
1126
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.
1129 : . . SPACE ;
1130
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 @ ;
1134 \\ : DROP _X ! ;
1135
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.
1138 : 2DUP OVER OVER ;
1139 : 2DROP DROP DROP ;
1140
1141 \\ More standard FORTH words.
1142 : 2* 2 * ;
1143 : 2/ 2 / ;
1144
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
1148         ;
1149
1150 : ]
1151         1 STATE !       \\ go back to compile mode
1152         ;
1153
1154 \\ LITERAL takes whatever is on the stack and compiles LIT <foo>
1155 : LITERAL IMMEDIATE
1156         ' LIT ,         \\ compile LIT
1157         ,               \\ compile the literal itself (from the stack)
1158         ;
1159
1160 \\ condition IF true-part THEN rest
1161 \\   compiles to:
1162 \\ condition 0BRANCH OFFSET true-part rest
1163 \\   where OFFSET is the offset of 'rest'
1164 \\ condition IF true-part ELSE false-part THEN
1165 \\   compiles to:
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
1168
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.
1172 : IF IMMEDIATE
1173         ' 0BRANCH ,     \\ compile 0BRANCH
1174         HERE @          \\ save location of the offset on the stack
1175         0 ,             \\ compile a dummy offset
1176 ;
1177
1178 : THEN IMMEDIATE
1179         DUP
1180         HERE @ SWAP -   \\ calculate the offset from the address saved on the stack
1181         SWAP !          \\ store the offset in the back-filled location
1182 ;
1183
1184 : ELSE IMMEDIATE
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
1190         HERE @ SWAP -
1191         SWAP !
1192 ;
1193
1194 \\ BEGIN loop-part condition UNTIL
1195 \\   compiles to:
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
1199 : BEGIN IMMEDIATE
1200         HERE @          \\ save location on the stack
1201 ;
1202
1203 : UNTIL IMMEDIATE
1204         ' 0BRANCH ,     \\ compile 0BRANCH
1205         HERE @ -        \\ calculate the offset from the address saved on the stack
1206         ,               \\ compile the offset here
1207 ;
1208
1209 \\ BEGIN loop-part AGAIN
1210 \\   compiles to:
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
1214 : AGAIN IMMEDIATE
1215         ' BRANCH ,      \\ compile BRANCH
1216         HERE @ -        \\ calculate the offset back
1217         ,               \\ compile the offset here
1218 ;
1219
1220 \\ BEGIN condition WHILE loop-part REPEAT
1221 \\   compiles to:
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
1225 : WHILE IMMEDIATE
1226         ' 0BRANCH ,     \\ compile 0BRANCH
1227         HERE @          \\ save location of the offset2 on the stack
1228         0 ,             \\ compile a dummy offset2
1229 ;
1230
1231 : REPEAT IMMEDIATE
1232         ' BRANCH ,      \\ compile BRANCH
1233         SWAP            \\ get the original offset (from BEGIN)
1234         HERE @ - ,      \\ and compile it after BRANCH
1235         DUP
1236         HERE @ SWAP -   \\ calculate the offset2
1237         SWAP !          \\ and back-fill it in the original location
1238 ;
1239
1240 \\ With the looping constructs, we can now write SPACES, which writes n spaces to stdout.
1241 : SPACES
1242         BEGIN
1243                 SPACE   \\ print a space
1244                 1-      \\ until we count down to 0
1245                 DUP 0=
1246         UNTIL
1247 ;
1248
1249 \\ .S prints the contents of the stack.  Very useful for debugging.
1250 : .S
1251         DSP@            \\ get current stack pointer
1252         BEGIN
1253                 DUP @ .         \\ print the stack element
1254                 4+              \\ move up
1255                 DUP S0 @ 4- =   \\ stop when we get to the top
1256         UNTIL
1257         DROP
1258 ;
1259
1260 \\ DEPTH returns the depth of the stack.
1261 : DEPTH S0 @ DSP@ - ;
1262
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
1273 \\ like this:
1274 \\   LITSTRING, string length, string rounded up to 4 bytes, EMITSTRING, ...
1275 : .\" IMMEDIATE
1276         STATE @         \\ compiling?
1277         IF
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
1281                 BEGIN
1282                         KEY             \\ get next character of the string
1283                         DUP '\"' <>
1284                 WHILE
1285                         HERE @ !b       \\ store the character in the compiled image
1286                         1 HERE +!       \\ increment HERE pointer by 1 byte
1287                 REPEAT
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
1294                 3 +
1295                 3 INVERT AND
1296                 HERE !
1297                 ' EMITSTRING ,  \\ compile the final EMITSTRING
1298         ELSE
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!
1301                 BEGIN
1302                         KEY
1303                         DUP '\"' = IF EXIT THEN
1304                         EMIT
1305                 AGAIN
1306         THEN
1307 ;
1308
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
1315 ;
1316
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.
1320 : RECURSE IMMEDIATE
1321         LATEST @ >CFA   \\ LATEST points to the word being compiled at the moment
1322         ,               \\ compile it
1323 ;
1324
1325 \\ ALLOT is used to allocate (static) memory when compiling.  It increases HERE by
1326 \\ the amount given on the stack.
1327 : ALLOT HERE +! ;
1328
1329
1330 \\ Finally print the welcome prompt.
1331 .\" OK \"
1332 "
1333
1334 _initbufftop:
1335         .align 4096
1336 buffend:
1337
1338 currkey:
1339         .int buffer
1340 bufftop:
1341         .int _initbufftop