58599e695e2c9d29769c7dd4e23504816fd3da63
[jonesforth.git] / jonesforth.f
1 \ -*- text -*-
2 \       A sometimes minimal FORTH compiler and tutorial for Linux / i386 systems. -*- asm -*-
3 \       By Richard W.M. Jones <rich@annexia.org> http://annexia.org/forth
4 \       This is PUBLIC DOMAIN (see public domain release statement below).
5 \       $Id: jonesforth.f,v 1.16 2007-10-12 01:46:12 rich Exp $
6 \
7 \       The first part of this tutorial is in jonesforth.S.  Get if from http://annexia.org/forth
8 \
9 \       PUBLIC DOMAIN ----------------------------------------------------------------------
10 \
11 \       I, the copyright holder of this work, hereby release it into the public domain. This applies worldwide.
12 \
13 \       In case this is not legally possible, I grant any entity the right to use this work for any purpose,
14 \       without any conditions, unless such conditions are required by law.
15 \
16 \       SETTING UP ----------------------------------------------------------------------
17 \
18 \       Let's get a few housekeeping things out of the way.  Firstly because I need to draw lots of
19 \       ASCII-art diagrams to explain concepts, the best way to look at this is using a window which
20 \       uses a fixed width font and is at least this wide:
21 \
22 \<------------------------------------------------------------------------------------------------------------------------>
23 \
24 \       Secondly make sure TABS are set to 8 characters.  The following should be a vertical
25 \       line.  If not, sort out your tabs.
26 \
27 \               |
28 \               |
29 \               |
30 \
31 \       Thirdly I assume that your screen is at least 50 characters high.
32 \
33 \       START OF FORTH CODE ----------------------------------------------------------------------
34 \
35 \       We've now reached the stage where the FORTH system is running and self-hosting.  All further
36 \       words can be written as FORTH itself, including words like IF, THEN, .", etc which in most
37 \       languages would be considered rather fundamental.
38 \
39 \       Some notes about the code:
40 \
41 \       I use indenting to show structure.  The amount of whitespace has no meaning to FORTH however
42 \       except that you must use at least one whitespace character between words, and words themselves
43 \       cannot contain whitespace.
44 \
45 \       FORTH is case-sensitive.  Use capslock!
46
47 \ The primitive word /MOD (DIVMOD) leaves both the quotient and the remainder on the stack.  (On
48 \ i386, the idivl instruction gives both anyway).  Now we can define the / and MOD in terms of /MOD
49 \ and a few other primitives.
50 : / /MOD SWAP DROP ;
51 : MOD /MOD DROP ;
52
53 \ Define some character constants
54 : '\n' 10 ;
55 : BL   32 ; \ BL (BLank) is a standard FORTH word for space.
56
57 \ CR prints a carriage return
58 : CR '\n' EMIT ;
59
60 \ SPACE prints a space
61 : SPACE BL EMIT ;
62
63 \ NEGATE leaves the negative of a number on the stack.
64 : NEGATE 0 SWAP - ;
65
66 \ Standard words for booleans.
67 : TRUE  1 ;
68 : FALSE 0 ;
69 : NOT   0= ;
70
71 \ LITERAL takes whatever is on the stack and compiles LIT <foo>
72 : LITERAL IMMEDIATE
73         ' LIT ,         \ compile LIT
74         ,               \ compile the literal itself (from the stack)
75         ;
76
77 \ Now we can use [ and ] to insert literals which are calculated at compile time.  (Recall that
78 \ [ and ] are the FORTH words which switch into and out of immediate mode.)
79 \ Within definitions, use [ ... ] LITERAL anywhere that '...' is a constant expression which you
80 \ would rather only compute once (at compile time, rather than calculating it each time your word runs).
81 : ':'
82         [               \ go into immediate mode (temporarily)
83         CHAR :          \ push the number 58 (ASCII code of colon) on the parameter stack
84         ]               \ go back to compile mode
85         LITERAL         \ compile LIT 58 as the definition of ':' word
86 ;
87
88 \ A few more character constants defined the same way as above.
89 : ';' [ CHAR ; ] LITERAL ;
90 : '(' [ CHAR ( ] LITERAL ;
91 : ')' [ CHAR ) ] LITERAL ;
92 : '"' [ CHAR " ] LITERAL ;
93 : 'A' [ CHAR A ] LITERAL ;
94 : '0' [ CHAR 0 ] LITERAL ;
95 : '-' [ CHAR - ] LITERAL ;
96 : '.' [ CHAR . ] LITERAL ;
97
98 \ While compiling, '[COMPILE] word' compiles 'word' if it would otherwise be IMMEDIATE.
99 : [COMPILE] IMMEDIATE
100         WORD            \ get the next word
101         FIND            \ find it in the dictionary
102         >CFA            \ get its codeword
103         ,               \ and compile that
104 ;
105
106 \ RECURSE makes a recursive call to the current word that is being compiled.
107 \
108 \ Normally while a word is being compiled, it is marked HIDDEN so that references to the
109 \ same word within are calls to the previous definition of the word.  However we still have
110 \ access to the word which we are currently compiling through the LATEST pointer so we
111 \ can use that to compile a recursive call.
112 : RECURSE IMMEDIATE
113         LATEST @        \ LATEST points to the word being compiled at the moment
114         >CFA            \ get the codeword
115         ,               \ compile it
116 ;
117
118 \       CONTROL STRUCTURES ----------------------------------------------------------------------
119 \
120 \ So far we have defined only very simple definitions.  Before we can go further, we really need to
121 \ make some control structures, like IF ... THEN and loops.  Luckily we can define arbitrary control
122 \ structures directly in FORTH.
123 \
124 \ Please note that the control structures as I have defined them here will only work inside compiled
125 \ words.  If you try to type in expressions using IF, etc. in immediate mode, then they won't work.
126 \ Making these work in immediate mode is left as an exercise for the reader.
127
128 \ condition IF true-part THEN rest
129 \       -- compiles to: --> condition 0BRANCH OFFSET true-part rest
130 \       where OFFSET is the offset of 'rest'
131 \ condition IF true-part ELSE false-part THEN
132 \       -- compiles to: --> condition 0BRANCH OFFSET true-part BRANCH OFFSET2 false-part rest
133 \       where OFFSET if the offset of false-part and OFFSET2 is the offset of rest
134
135 \ IF is an IMMEDIATE word which compiles 0BRANCH followed by a dummy offset, and places
136 \ the address of the 0BRANCH on the stack.  Later when we see THEN, we pop that address
137 \ off the stack, calculate the offset, and back-fill the offset.
138 : IF IMMEDIATE
139         ' 0BRANCH ,     \ compile 0BRANCH
140         HERE @          \ save location of the offset on the stack
141         0 ,             \ compile a dummy offset
142 ;
143
144 : THEN IMMEDIATE
145         DUP
146         HERE @ SWAP -   \ calculate the offset from the address saved on the stack
147         SWAP !          \ store the offset in the back-filled location
148 ;
149
150 : ELSE IMMEDIATE
151         ' BRANCH ,      \ definite branch to just over the false-part
152         HERE @          \ save location of the offset on the stack
153         0 ,             \ compile a dummy offset
154         SWAP            \ now back-fill the original (IF) offset
155         DUP             \ same as for THEN word above
156         HERE @ SWAP -
157         SWAP !
158 ;
159
160 \ BEGIN loop-part condition UNTIL
161 \       -- compiles to: --> loop-part condition 0BRANCH OFFSET
162 \       where OFFSET points back to the loop-part
163 \ This is like do { loop-part } while (condition) in the C language
164 : BEGIN IMMEDIATE
165         HERE @          \ save location on the stack
166 ;
167
168 : UNTIL IMMEDIATE
169         ' 0BRANCH ,     \ compile 0BRANCH
170         HERE @ -        \ calculate the offset from the address saved on the stack
171         ,               \ compile the offset here
172 ;
173
174 \ BEGIN loop-part AGAIN
175 \       -- compiles to: --> loop-part BRANCH OFFSET
176 \       where OFFSET points back to the loop-part
177 \ In other words, an infinite loop which can only be returned from with EXIT
178 : AGAIN IMMEDIATE
179         ' BRANCH ,      \ compile BRANCH
180         HERE @ -        \ calculate the offset back
181         ,               \ compile the offset here
182 ;
183
184 \ BEGIN condition WHILE loop-part REPEAT
185 \       -- compiles to: --> condition 0BRANCH OFFSET2 loop-part BRANCH OFFSET
186 \       where OFFSET points back to condition (the beginning) and OFFSET2 points to after the whole piece of code
187 \ So this is like a while (condition) { loop-part } loop in the C language
188 : WHILE IMMEDIATE
189         ' 0BRANCH ,     \ compile 0BRANCH
190         HERE @          \ save location of the offset2 on the stack
191         0 ,             \ compile a dummy offset2
192 ;
193
194 : REPEAT IMMEDIATE
195         ' BRANCH ,      \ compile BRANCH
196         SWAP            \ get the original offset (from BEGIN)
197         HERE @ - ,      \ and compile it after BRANCH
198         DUP
199         HERE @ SWAP -   \ calculate the offset2
200         SWAP !          \ and back-fill it in the original location
201 ;
202
203 \ UNLESS is the same as IF but the test is reversed.
204 \
205 \ Note the use of [COMPILE]: Since IF is IMMEDIATE we don't want it to be executed while UNLESS
206 \ is compiling, but while UNLESS is running (which happens to be when whatever word using UNLESS is
207 \ being compiled -- whew!).  So we use [COMPILE] to reverse the effect of marking IF as immediate.
208 \ This trick is generally used when we want to write our own control words without having to
209 \ implement them all in terms of the primitives 0BRANCH and BRANCH, but instead reusing simpler
210 \ control words like (in this instance) IF.
211 : UNLESS IMMEDIATE
212         ' NOT ,         \ compile NOT (to reverse the test)
213         [COMPILE] IF    \ continue by calling the normal IF
214 ;
215
216 \       COMMENTS ----------------------------------------------------------------------
217 \
218 \ FORTH allows ( ... ) as comments within function definitions.  This works by having an IMMEDIATE
219 \ word called ( which just drops input characters until it hits the corresponding ).
220 : ( IMMEDIATE
221         1               \ allowed nested parens by keeping track of depth
222         BEGIN
223                 KEY             \ read next character
224                 DUP '(' = IF    \ open paren?
225                         DROP            \ drop the open paren
226                         1+              \ depth increases
227                 ELSE
228                         ')' = IF        \ close paren?
229                                 1-              \ depth decreases
230                         THEN
231                 THEN
232         DUP 0= UNTIL            \ continue until we reach matching close paren, depth 0
233         DROP            \ drop the depth counter
234 ;
235
236 (
237         From now on we can use ( ... ) for comments.
238
239         STACK NOTATION ----------------------------------------------------------------------
240
241         In FORTH style we can also use ( ... -- ... ) to show the effects that a word has on the
242         parameter stack.  For example:
243
244         ( n -- )        means that the word consumes an integer (n) from the parameter stack.
245         ( b a -- c )    means that the word uses two integers (a and b, where a is at the top of stack)
246                                 and returns a single integer (c).
247         ( -- )          means the word has no effect on the stack
248 )
249
250 ( Some more complicated stack examples, showing the stack notation. )
251 : NIP ( x y -- y ) SWAP DROP ;
252 : TUCK ( x y -- y x y ) DUP ROT ;
253 : PICK ( x_u ... x_1 x_0 u -- x_u ... x_1 x_0 x_u )
254         1+              ( add one because of 'u' on the stack )
255         4 *             ( multiply by the word size )
256         DSP@ +          ( add to the stack pointer )
257         @               ( and fetch )
258 ;
259
260 ( With the looping constructs, we can now write SPACES, which writes n spaces to stdout. )
261 : SPACES        ( n -- )
262         BEGIN
263                 DUP 0>          ( while n > 0 )
264         WHILE
265                 SPACE           ( print a space )
266                 1-              ( until we count down to 0 )
267         REPEAT
268         DROP
269 ;
270
271 ( Standard words for manipulating BASE. )
272 : DECIMAL ( -- ) 10 BASE ! ;
273 : HEX ( -- ) 16 BASE ! ;
274
275 (
276         PRINTING NUMBERS ----------------------------------------------------------------------
277
278         The standard FORTH word . (DOT) is very important.  It takes the number at the top
279         of the stack and prints it out.  However first I'm going to implement some lower-level
280         FORTH words:
281
282         U.R     ( u width -- )  which prints an unsigned number, padded to a certain width
283         U.      ( u -- )        which prints an unsigned number
284         .R      ( n width -- )  which prints a signed number, padded to a certain width.
285
286         For example:
287                 -123 6 .R
288         will print out these characters:
289                 <space> <space> - 1 2 3
290
291         In other words, the number padded left to a certain number of characters.
292
293         The full number is printed even if it is wider than width, and this is what allows us to
294         define the ordinary functions U. and . (we just set width to zero knowing that the full
295         number will be printed anyway).
296
297         Another wrinkle of . and friends is that they obey the current base in the variable BASE.
298         BASE can be anything in the range 2 to 36.
299
300         While we're defining . &c we can also define .S which is a useful debugging tool.  This
301         word prints the current stack (non-destructively) from top to bottom.
302 )
303
304 ( This is the underlying recursive definition of U. )
305 : U.            ( u -- )
306         BASE @ /MOD     ( width rem quot )
307         ?DUP IF                 ( if quotient <> 0 then )
308                 RECURSE         ( print the quotient )
309         THEN
310
311         ( print the remainder )
312         DUP 10 < IF
313                 '0'             ( decimal digits 0..9 )
314         ELSE
315                 10 -            ( hex and beyond digits A..Z )
316                 'A'
317         THEN
318         +
319         EMIT
320 ;
321
322 (
323         FORTH word .S prints the contents of the stack.  It doesn't alter the stack.
324         Very useful for debugging.
325 )
326 : .S            ( -- )
327         DSP@            ( get current stack pointer )
328         BEGIN
329                 DUP S0 @ <
330         WHILE
331                 DUP @ U.        ( print the stack element )
332                 SPACE
333                 4+              ( move up )
334         REPEAT
335         DROP
336 ;
337
338 ( This word returns the width (in characters) of an unsigned number in the current base )
339 : UWIDTH        ( u -- width )
340         BASE @ /        ( rem quot )
341         ?DUP IF         ( if quotient <> 0 then )
342                 RECURSE 1+      ( return 1+recursive call )
343         ELSE
344                 1               ( return 1 )
345         THEN
346 ;
347
348 : U.R           ( u width -- )
349         SWAP            ( width u )
350         DUP             ( width u u )
351         UWIDTH          ( width u uwidth )
352         -ROT            ( u uwidth width )
353         SWAP -          ( u width-uwidth )
354         ( At this point if the requested width is narrower, we'll have a negative number on the stack.
355           Otherwise the number on the stack is the number of spaces to print.  But SPACES won't print
356           a negative number of spaces anyway, so it's now safe to call SPACES ... )
357         SPACES
358         ( ... and then call the underlying implementation of U. )
359         U.
360 ;
361
362 (
363         .R prints a signed number, padded to a certain width.  We can't just print the sign
364         and call U.R because we want the sign to be next to the number ('-123' instead of '-  123').
365 )
366 : .R            ( n width -- )
367         SWAP            ( width n )
368         DUP 0< IF
369                 NEGATE          ( width u )
370                 1               ( save a flag to remember that it was negative | width n 1 )
371                 ROT             ( 1 width u )
372                 SWAP            ( 1 u width )
373                 1-              ( 1 u width-1 )
374         ELSE
375                 0               ( width u 0 )
376                 ROT             ( 0 width u )
377                 SWAP            ( 0 u width )
378         THEN
379         SWAP            ( flag width u )
380         DUP             ( flag width u u )
381         UWIDTH          ( flag width u uwidth )
382         -ROT            ( flag u uwidth width )
383         SWAP -          ( flag u width-uwidth )
384
385         SPACES          ( flag u )
386         SWAP            ( u flag )
387
388         IF                      ( was it negative? print the - character )
389                 '-' EMIT
390         THEN
391
392         U.
393 ;
394
395 ( Finally we can define word . in terms of .R, with a trailing space. )
396 : . 0 .R SPACE ;
397
398 ( The real U., note the trailing space. )
399 : U. U. SPACE ;
400
401 ( ? fetches the integer at an address and prints it. )
402 : ? ( addr -- ) @ . ;
403
404 ( c a b WITHIN returns true if a <= c and c < b )
405 : WITHIN
406         ROT             ( b c a )
407         OVER            ( b c a c )
408         <= IF
409                 > IF            ( b c -- )
410                         TRUE
411                 ELSE
412                         FALSE
413                 THEN
414         ELSE
415                 2DROP           ( b c -- )
416                 FALSE
417         THEN
418 ;
419
420 ( DEPTH returns the depth of the stack. )
421 : DEPTH         ( -- n )
422         S0 @ DSP@ -
423         4-                      ( adjust because S0 was on the stack when we pushed DSP )
424 ;
425
426 (
427         ALIGNED takes an address and rounds it up (aligns it) to the next 4 byte boundary.
428 )
429 : ALIGNED       ( addr -- addr )
430         3 + 3 INVERT AND        ( (addr+3) & ~3 )
431 ;
432
433 (
434         ALIGN aligns the HERE pointer, so the next word appended will be aligned properly.
435 )
436 : ALIGN HERE @ ALIGNED HERE ! ;
437
438 (
439         STRINGS ----------------------------------------------------------------------
440
441         S" string" is used in FORTH to define strings.  It leaves the address of the string and
442         its length on the stack, (length at the top of stack).  The space following S" is the normal
443         space between FORTH words and is not a part of the string.
444
445         This is tricky to define because it has to do different things depending on whether
446         we are compiling or in immediate mode.  (Thus the word is marked IMMEDIATE so it can
447         detect this and do different things).
448
449         In compile mode we append
450                 LITSTRING <string length> <string rounded up 4 bytes>
451         to the current word.  The primitive LITSTRING does the right thing when the current
452         word is executed.
453
454         In immediate mode there isn't a particularly good place to put the string, but in this
455         case we put the string at HERE (but we _don't_ change HERE).  This is meant as a temporary
456         location, likely to be overwritten soon after.
457 )
458 ( C, appends a byte to the current compiled word. )
459 : C,
460         HERE @ C!       ( store the character in the compiled image )
461         1 HERE +!       ( increment HERE pointer by 1 byte )
462 ;
463
464 : S" IMMEDIATE          ( -- addr len )
465         STATE @ IF      ( compiling? )
466                 ' LITSTRING ,   ( compile LITSTRING )
467                 HERE @          ( save the address of the length word on the stack )
468                 0 ,             ( dummy length - we don't know what it is yet )
469                 BEGIN
470                         KEY             ( get next character of the string )
471                         DUP '"' <>
472                 WHILE
473                         C,              ( copy character )
474                 REPEAT
475                 DROP            ( drop the double quote character at the end )
476                 DUP             ( get the saved address of the length word )
477                 HERE @ SWAP -   ( calculate the length )
478                 4-              ( subtract 4 (because we measured from the start of the length word) )
479                 SWAP !          ( and back-fill the length location )
480                 ALIGN           ( round up to next multiple of 4 bytes for the remaining code )
481         ELSE            ( immediate mode )
482                 HERE @          ( get the start address of the temporary space )
483                 BEGIN
484                         KEY
485                         DUP '"' <>
486                 WHILE
487                         OVER C!         ( save next character )
488                         1+              ( increment address )
489                 REPEAT
490                 DROP            ( drop the final " character )
491                 HERE @ -        ( calculate the length )
492                 HERE @          ( push the start address )
493                 SWAP            ( addr len )
494         THEN
495 ;
496
497 (
498         ." is the print string operator in FORTH.  Example: ." Something to print"
499         The space after the operator is the ordinary space required between words and is not
500         a part of what is printed.
501
502         In immediate mode we just keep reading characters and printing them until we get to
503         the next double quote.
504
505         In compile mode we use S" to store the string, then add TELL afterwards:
506                 LITSTRING <string length> <string rounded up to 4 bytes> TELL
507
508         It may be interesting to note the use of [COMPILE] to turn the call to the immediate
509         word S" into compilation of that word.  It compiles it into the definition of .",
510         not into the definition of the word being compiled when this is running (complicated
511         enough for you?)
512 )
513 : ." IMMEDIATE          ( -- )
514         STATE @ IF      ( compiling? )
515                 [COMPILE] S"    ( read the string, and compile LITSTRING, etc. )
516                 ' TELL ,        ( compile the final TELL )
517         ELSE
518                 ( In immediate mode, just read characters and print them until we get
519                   to the ending double quote. )
520                 BEGIN
521                         KEY
522                         DUP '"' = IF
523                                 DROP    ( drop the double quote character )
524                                 EXIT    ( return from this function )
525                         THEN
526                         EMIT
527                 AGAIN
528         THEN
529 ;
530
531 (
532         CONSTANTS AND VARIABLES ----------------------------------------------------------------------
533
534         In FORTH, global constants and variables are defined like this:
535
536         10 CONSTANT TEN         when TEN is executed, it leaves the integer 10 on the stack
537         VARIABLE VAR            when VAR is executed, it leaves the address of VAR on the stack
538
539         Constants can be read but not written, eg:
540
541         TEN . CR                prints 10
542
543         You can read a variable (in this example called VAR) by doing:
544
545         VAR @                   leaves the value of VAR on the stack
546         VAR @ . CR              prints the value of VAR
547         VAR ? CR                same as above, since ? is the same as @ .
548
549         and update the variable by doing:
550
551         20 VAR !                sets VAR to 20
552
553         Note that variables are uninitialised (but see VALUE later on which provides initialised
554         variables with a slightly simpler syntax).
555
556         How can we define the words CONSTANT and VARIABLE?
557
558         The trick is to define a new word for the variable itself (eg. if the variable was called
559         'VAR' then we would define a new word called VAR).  This is easy to do because we exposed
560         dictionary entry creation through the CREATE word (part of the definition of : above).
561         A call to WORD [TEN] CREATE (where [TEN] means that "TEN" is the next word in the input)
562         leaves the dictionary entry:
563
564                                    +--- HERE
565                                    |
566                                    V
567         +---------+---+---+---+---+
568         | LINK    | 3 | T | E | N |
569         +---------+---+---+---+---+
570                    len
571
572         For CONSTANT we can continue by appending DOCOL (the codeword), then LIT followed by
573         the constant itself and then EXIT, forming a little word definition that returns the
574         constant:
575
576         +---------+---+---+---+---+------------+------------+------------+------------+
577         | LINK    | 3 | T | E | N | DOCOL      | LIT        | 10         | EXIT       |
578         +---------+---+---+---+---+------------+------------+------------+------------+
579                    len              codeword
580
581         Notice that this word definition is exactly the same as you would have got if you had
582         written : TEN 10 ;
583
584         Note for people reading the code below: DOCOL is a constant word which we defined in the
585         assembler part which returns the value of the assembler symbol of the same name.
586 )
587 : CONSTANT
588         WORD            ( get the name (the name follows CONSTANT) )
589         CREATE          ( make the dictionary entry )
590         DOCOL ,         ( append DOCOL (the codeword field of this word) )
591         ' LIT ,         ( append the codeword LIT )
592         ,               ( append the value on the top of the stack )
593         ' EXIT ,        ( append the codeword EXIT )
594 ;
595
596 (
597         VARIABLE is a little bit harder because we need somewhere to put the variable.  There is
598         nothing particularly special about the user memory (the area of memory pointed to by HERE
599         where we have previously just stored new word definitions).  We can slice off bits of this
600         memory area to store anything we want, so one possible definition of VARIABLE might create
601         this:
602
603            +--------------------------------------------------------------+
604            |                                                              |
605            V                                                              |
606         +---------+---------+---+---+---+---+------------+------------+---|--------+------------+
607         | <var>   | LINK    | 3 | V | A | R | DOCOL      | LIT        | <addr var> | EXIT       |
608         +---------+---------+---+---+---+---+------------+------------+------------+------------+
609                              len              codeword
610
611         where <var> is the place to store the variable, and <addr var> points back to it.
612
613         To make this more general let's define a couple of words which we can use to allocate
614         arbitrary memory from the user memory.
615
616         First ALLOT, where n ALLOT allocates n bytes of memory.  (Note when calling this that
617         it's a very good idea to make sure that n is a multiple of 4, or at least that next time
618         a word is compiled that HERE has been left as a multiple of 4).
619 )
620 : ALLOT         ( n -- addr )
621         HERE @ SWAP     ( here n )
622         HERE +!         ( adds n to HERE, after this the old value of HERE is still on the stack )
623 ;
624
625 (
626         Second, CELLS.  In FORTH the phrase 'n CELLS ALLOT' means allocate n integers of whatever size
627         is the natural size for integers on this machine architecture.  On this 32 bit machine therefore
628         CELLS just multiplies the top of stack by 4.
629 )
630 : CELLS ( n -- n ) 4 * ;
631
632 (
633         So now we can define VARIABLE easily in much the same way as CONSTANT above.  Refer to the
634         diagram above to see what the word that this creates will look like.
635 )
636 : VARIABLE
637         1 CELLS ALLOT   ( allocate 1 cell of memory, push the pointer to this memory )
638         WORD CREATE     ( make the dictionary entry (the name follows VARIABLE) )
639         DOCOL ,         ( append DOCOL (the codeword field of this word) )
640         ' LIT ,         ( append the codeword LIT )
641         ,               ( append the pointer to the new memory )
642         ' EXIT ,        ( append the codeword EXIT )
643 ;
644
645 (
646         VALUES ----------------------------------------------------------------------
647
648         VALUEs are like VARIABLEs but with a simpler syntax.  You would generally use them when you
649         want a variable which is read often, and written infrequently.
650
651         20 VALUE VAL    creates VAL with initial value 20
652         VAL             pushes the value (20) directly on the stack
653         30 TO VAL       updates VAL, setting it to 30
654         VAL             pushes the value (30) directly on the stack
655
656         Notice that 'VAL' on its own doesn't return the address of the value, but the value itself,
657         making values simpler and more obvious to use than variables (no indirection through '@').
658         The price is a more complicated implementation, although despite the complexity there is no
659         performance penalty at runtime.
660
661         A naive implementation of 'TO' would be quite slow, involving a dictionary search each time.
662         But because this is FORTH we have complete control of the compiler so we can compile TO more
663         efficiently, turning:
664                 TO VAL
665         into:
666                 LIT <addr> !
667         and calculating <addr> (the address of the value) at compile time.
668
669         Now this is the clever bit.  We'll compile our value like this:
670
671         +---------+---+---+---+---+------------+------------+------------+------------+
672         | LINK    | 3 | V | A | L | DOCOL      | LIT        | <value>    | EXIT       |
673         +---------+---+---+---+---+------------+------------+------------+------------+
674                    len              codeword
675
676         where <value> is the actual value itself.  Note that when VAL executes, it will push the
677         value on the stack, which is what we want.
678
679         But what will TO use for the address <addr>?  Why of course a pointer to that <value>:
680
681                 code compiled   - - - - --+------------+------------+------------+-- - - - -
682                 by TO VAL                 | LIT        | <addr>     | !          |
683                                 - - - - --+------------+-----|------+------------+-- - - - -
684                                                              |
685                                                              V
686         +---------+---+---+---+---+------------+------------+------------+------------+
687         | LINK    | 3 | V | A | L | DOCOL      | LIT        | <value>    | EXIT       |
688         +---------+---+---+---+---+------------+------------+------------+------------+
689                    len              codeword
690
691         In other words, this is a kind of self-modifying code.
692
693         (Note to the people who want to modify this FORTH to add inlining: values defined this
694         way cannot be inlined).
695 )
696 : VALUE         ( n -- )
697         WORD CREATE     ( make the dictionary entry (the name follows VALUE) )
698         DOCOL ,         ( append DOCOL )
699         ' LIT ,         ( append the codeword LIT )
700         ,               ( append the initial value )
701         ' EXIT ,        ( append the codeword EXIT )
702 ;
703
704 : TO IMMEDIATE  ( n -- )
705         WORD            ( get the name of the value )
706         FIND            ( look it up in the dictionary )
707         >DFA            ( get a pointer to the first data field (the 'LIT') )
708         4+              ( increment to point at the value )
709         STATE @ IF      ( compiling? )
710                 ' LIT ,         ( compile LIT )
711                 ,               ( compile the address of the value )
712                 ' ! ,           ( compile ! )
713         ELSE            ( immediate mode )
714                 !               ( update it straightaway )
715         THEN
716 ;
717
718 ( x +TO VAL adds x to VAL )
719 : +TO IMMEDIATE
720         WORD            ( get the name of the value )
721         FIND            ( look it up in the dictionary )
722         >DFA            ( get a pointer to the first data field (the 'LIT') )
723         4+              ( increment to point at the value )
724         STATE @ IF      ( compiling? )
725                 ' LIT ,         ( compile LIT )
726                 ,               ( compile the address of the value )
727                 ' +! ,          ( compile +! )
728         ELSE            ( immediate mode )
729                 +!              ( update it straightaway )
730         THEN
731 ;
732
733 (
734         PRINTING THE DICTIONARY ----------------------------------------------------------------------
735
736         ID. takes an address of a dictionary entry and prints the word's name.
737
738         For example: LATEST @ ID. would print the name of the last word that was defined.
739 )
740 : ID.
741         4+              ( skip over the link pointer )
742         DUP C@          ( get the flags/length byte )
743         F_LENMASK AND   ( mask out the flags - just want the length )
744
745         BEGIN
746                 DUP 0>          ( length > 0? )
747         WHILE
748                 SWAP 1+         ( addr len -- len addr+1 )
749                 DUP C@          ( len addr -- len addr char | get the next character)
750                 EMIT            ( len addr char -- len addr | and print it)
751                 SWAP 1-         ( len addr -- addr len-1    | subtract one from length )
752         REPEAT
753         2DROP           ( len addr -- )
754 ;
755
756 (
757         'WORD word FIND ?HIDDEN' returns true if 'word' is flagged as hidden.
758
759         'WORD word FIND ?IMMEDIATE' returns true if 'word' is flagged as immediate.
760 )
761 : ?HIDDEN
762         4+              ( skip over the link pointer )
763         C@              ( get the flags/length byte )
764         F_HIDDEN AND    ( mask the F_HIDDEN flag and return it (as a truth value) )
765 ;
766 : ?IMMEDIATE
767         4+              ( skip over the link pointer )
768         C@              ( get the flags/length byte )
769         F_IMMED AND     ( mask the F_IMMED flag and return it (as a truth value) )
770 ;
771
772 (
773         WORDS prints all the words defined in the dictionary, starting with the word defined most recently.
774         However it doesn't print hidden words.
775
776         The implementation simply iterates backwards from LATEST using the link pointers.
777 )
778 : WORDS
779         LATEST @        ( start at LATEST dictionary entry )
780         BEGIN
781                 ?DUP            ( while link pointer is not null )
782         WHILE
783                 DUP ?HIDDEN NOT IF      ( ignore hidden words )
784                         DUP ID.         ( but if not hidden, print the word )
785                         SPACE
786                 THEN
787                 @               ( dereference the link pointer - go to previous word )
788         REPEAT
789         CR
790 ;
791
792 (
793         FORGET ----------------------------------------------------------------------
794
795         So far we have only allocated words and memory.  FORTH provides a rather primitive method
796         to deallocate.
797
798         'FORGET word' deletes the definition of 'word' from the dictionary and everything defined
799         after it, including any variables and other memory allocated after.
800
801         The implementation is very simple - we look up the word (which returns the dictionary entry
802         address).  Then we set HERE to point to that address, so in effect all future allocations
803         and definitions will overwrite memory starting at the word.  We also need to set LATEST to
804         point to the previous word.
805
806         Note that you cannot FORGET built-in words (well, you can try but it will probably cause
807         a segfault).
808
809         XXX: Because we wrote VARIABLE to store the variable in memory allocated before the word,
810         in the current implementation VARIABLE FOO FORGET FOO will leak 1 cell of memory.
811 )
812 : FORGET
813         WORD FIND       ( find the word, gets the dictionary entry address )
814         DUP @ LATEST !  ( set LATEST to point to the previous word )
815         HERE !          ( and store HERE with the dictionary address )
816 ;
817
818 (
819         DUMP ----------------------------------------------------------------------
820
821         DUMP is used to dump out the contents of memory, in the 'traditional' hexdump format.
822
823         Notice that the parameters to DUMP (address, length) are compatible with string words
824         such as WORD and S".
825
826         You can dump out the raw code for the last word you defined by doing something like:
827
828                 LATEST @ 128 DUMP
829 )
830 : DUMP          ( addr len -- )
831         BASE @ ROT              ( save the current BASE at the bottom of the stack )
832         HEX                     ( and switch to hexadecimal mode )
833
834         BEGIN
835                 ?DUP            ( while len > 0 )
836         WHILE
837                 OVER 8 U.R      ( print the address )
838                 SPACE
839
840                 ( print up to 16 words on this line )
841                 2DUP            ( addr len addr len )
842                 1- 15 AND 1+    ( addr len addr linelen )
843                 BEGIN
844                         ?DUP            ( while linelen > 0 )
845                 WHILE
846                         SWAP            ( addr len linelen addr )
847                         DUP C@          ( addr len linelen addr byte )
848                         2 .R SPACE      ( print the byte )
849                         1+ SWAP 1-      ( addr len linelen addr -- addr len addr+1 linelen-1 )
850                 REPEAT
851                 DROP            ( addr len )
852
853                 ( print the ASCII equivalents )
854                 2DUP 1- 15 AND 1+ ( addr len addr linelen )
855                 BEGIN
856                         ?DUP            ( while linelen > 0)
857                 WHILE
858                         SWAP            ( addr len linelen addr )
859                         DUP C@          ( addr len linelen addr byte )
860                         DUP 32 128 WITHIN IF    ( 32 <= c < 128? )
861                                 EMIT
862                         ELSE
863                                 DROP '.' EMIT
864                         THEN
865                         1+ SWAP 1-      ( addr len linelen addr -- addr len addr+1 linelen-1 )
866                 REPEAT
867                 DROP            ( addr len )
868                 CR
869
870                 DUP 1- 15 AND 1+ ( addr len linelen )
871                 DUP             ( addr len linelen linelen )
872                 ROT             ( addr linelen len linelen )
873                 -               ( addr linelen len-linelen )
874                 ROT             ( len-linelen addr linelen )
875                 +               ( len-linelen addr+linelen )
876                 SWAP            ( addr-linelen len-linelen )
877         REPEAT
878
879         DROP                    ( restore stack )
880         BASE !                  ( restore saved BASE )
881 ;
882
883 (
884         CASE ----------------------------------------------------------------------
885
886         CASE...ENDCASE is how we do switch statements in FORTH.  There is no generally
887         agreed syntax for this, so I've gone for the syntax mandated by the ISO standard
888         FORTH (ANS-FORTH).
889
890                 ( some value on the stack )
891                 CASE
892                 test1 OF ... ENDOF
893                 test2 OF ... ENDOF
894                 testn OF ... ENDOF
895                 ... ( default case )
896                 ENDCASE
897
898         The CASE statement tests the value on the stack by comparing it for equality with
899         test1, test2, ..., testn and executes the matching piece of code within OF ... ENDOF.
900         If none of the test values match then the default case is executed.  Inside the ... of
901         the default case, the value is still at the top of stack (it is implicitly DROP-ed
902         by ENDCASE).  When ENDOF is executed it jumps after ENDCASE (ie. there is no "fall-through"
903         and no need for a break statement like in C).
904
905         The default case may be omitted.  In fact the tests may also be omitted so that you
906         just have a default case, although this is probably not very useful.
907
908         An example (assuming that 'q', etc. are words which push the ASCII value of the letter
909         on the stack):
910
911                 0 VALUE QUIT
912                 0 VALUE SLEEP
913                 KEY CASE
914                         'q' OF 1 TO QUIT ENDOF
915                         's' OF 1 TO SLEEP ENDOF
916                         ( default case: )
917                         ." Sorry, I didn't understand key <" DUP EMIT ." >, try again." CR
918                 ENDCASE
919
920         (In some versions of FORTH, more advanced tests are supported, such as ranges, etc.
921         Other versions of FORTH need you to write OTHERWISE to indicate the default case.
922         As I said above, this FORTH tries to follow the ANS FORTH standard).
923
924         The implementation of CASE...ENDCASE is somewhat non-trivial.  I'm following the
925         implementations from here:
926         http://www.uni-giessen.de/faq/archiv/forthfaq.case_endcase/msg00000.html
927
928         The general plan is to compile the code as a series of IF statements:
929
930         CASE                            (push 0 on the immediate-mode parameter stack)
931         test1 OF ... ENDOF              test1 OVER = IF DROP ... ELSE
932         test2 OF ... ENDOF              test2 OVER = IF DROP ... ELSE
933         testn OF ... ENDOF              testn OVER = IF DROP ... ELSE
934         ... ( default case )            ...
935         ENDCASE                         DROP THEN [THEN [THEN ...]]
936
937         The CASE statement pushes 0 on the immediate-mode parameter stack, and that number
938         is used to count how many THEN statements we need when we get to ENDCASE so that each
939         IF has a matching THEN.  The counting is done implicitly.  If you recall from the
940         implementation above of IF, each IF pushes a code address on the immediate-mode stack,
941         and these addresses are non-zero, so by the time we get to ENDCASE the stack contains
942         some number of non-zeroes, followed by a zero.  The number of non-zeroes is how many
943         times IF has been called, so how many times we need to match it with THEN.
944
945         This code uses [COMPILE] so that we compile calls to IF, ELSE, THEN instead of
946         actually calling them while we're compiling the words below.
947
948         As is the case with all of our control structures, they only work within word
949         definitions, not in immediate mode.
950 )
951 : CASE IMMEDIATE
952         0               ( push 0 to mark the bottom of the stack )
953 ;
954
955 : OF IMMEDIATE
956         ' OVER ,        ( compile OVER )
957         ' = ,           ( compile = )
958         [COMPILE] IF    ( compile IF )
959         ' DROP ,        ( compile DROP )
960 ;
961
962 : ENDOF IMMEDIATE
963         [COMPILE] ELSE  ( ENDOF is the same as ELSE )
964 ;
965
966 : ENDCASE IMMEDIATE
967         ' DROP ,        ( compile DROP )
968
969         ( keep compiling THEN until we get to our zero marker )
970         BEGIN
971                 ?DUP
972         WHILE
973                 [COMPILE] THEN
974         REPEAT
975 ;
976
977 (
978         DECOMPILER ----------------------------------------------------------------------
979
980         CFA> is the opposite of >CFA.  It takes a codeword and tries to find the matching
981         dictionary definition.  (In truth, it works with any pointer into a word, not just
982         the codeword pointer, and this is needed to do stack traces).
983
984         In this FORTH this is not so easy.  In fact we have to search through the dictionary
985         because we don't have a convenient back-pointer (as is often the case in other versions
986         of FORTH).  Because of this search, CFA> should not be used when performance is critical,
987         so it is only used for debugging tools such as the decompiler and printing stack
988         traces.
989
990         This word returns 0 if it doesn't find a match.
991 )
992 : CFA>
993         LATEST @        ( start at LATEST dictionary entry )
994         BEGIN
995                 ?DUP            ( while link pointer is not null )
996         WHILE
997                 2DUP SWAP       ( cfa curr curr cfa )
998                 < IF            ( current dictionary entry < cfa? )
999                         NIP             ( leave curr dictionary entry on the stack )
1000                         EXIT
1001                 THEN
1002                 @               ( follow link pointer back )
1003         REPEAT
1004         DROP            ( restore stack )
1005         0               ( sorry, nothing found )
1006 ;
1007
1008 (
1009         SEE decompiles a FORTH word.
1010
1011         We search for the dictionary entry of the word, then search again for the next
1012         word (effectively, the end of the compiled word).  This results in two pointers:
1013
1014         +---------+---+---+---+---+------------+------------+------------+------------+
1015         | LINK    | 3 | T | E | N | DOCOL      | LIT        | 10         | EXIT       |
1016         +---------+---+---+---+---+------------+------------+------------+------------+
1017          ^                                                                             ^
1018          |                                                                             |
1019         Start of word                                                         End of word
1020
1021         With this information we can have a go at decompiling the word.  We need to
1022         recognise "meta-words" like LIT, LITSTRING, BRANCH, etc. and treat those separately.
1023 )
1024 : SEE
1025         WORD FIND       ( find the dictionary entry to decompile )
1026
1027         ( Now we search again, looking for the next word in the dictionary.  This gives us
1028           the length of the word that we will be decompiling.  (Well, mostly it does). )
1029         HERE @          ( address of the end of the last compiled word )
1030         LATEST @        ( word last curr )
1031         BEGIN
1032                 2 PICK          ( word last curr word )
1033                 OVER            ( word last curr word curr )
1034                 <>              ( word last curr word<>curr? )
1035         WHILE                   ( word last curr )
1036                 NIP             ( word curr )
1037                 DUP @           ( word curr prev (which becomes: word last curr) )
1038         REPEAT
1039
1040         DROP            ( at this point, the stack is: start-of-word end-of-word )
1041         SWAP            ( end-of-word start-of-word )
1042
1043         ( begin the definition with : NAME [IMMEDIATE] )
1044         ':' EMIT SPACE DUP ID. SPACE
1045         DUP ?IMMEDIATE IF ." IMMEDIATE " THEN
1046
1047         >DFA            ( get the data address, ie. points after DOCOL | end-of-word start-of-data )
1048
1049         ( now we start decompiling until we hit the end of the word )
1050         BEGIN           ( end start )
1051                 2DUP >
1052         WHILE
1053                 DUP @           ( end start codeword )
1054
1055                 CASE
1056                 ' LIT OF                ( is it LIT ? )
1057                         4 + DUP @               ( get next word which is the integer constant )
1058                         .                       ( and print it )
1059                 ENDOF
1060                 ' LITSTRING OF          ( is it LITSTRING ? )
1061                         [ CHAR S ] LITERAL EMIT '"' EMIT SPACE ( print S"<space> )
1062                         4 + DUP @               ( get the length word )
1063                         SWAP 4 + SWAP           ( end start+4 length )
1064                         2DUP TELL               ( print the string )
1065                         '"' EMIT SPACE          ( finish the string with a final quote )
1066                         + ALIGNED               ( end start+4+len, aligned )
1067                         4 -                     ( because we're about to add 4 below )
1068                 ENDOF
1069                 ' 0BRANCH OF            ( is it 0BRANCH ? )
1070                         ." 0BRANCH ( "
1071                         4 + DUP @               ( print the offset )
1072                         .
1073                         ." ) "
1074                 ENDOF
1075                 ' BRANCH OF             ( is it BRANCH ? )
1076                         ." BRANCH ( "
1077                         4 + DUP @               ( print the offset )
1078                         .
1079                         ." ) "
1080                 ENDOF
1081                 ' ' OF                  ( is it ' (TICK) ? )
1082                         [ CHAR ' ] LITERAL EMIT SPACE
1083                         4 + DUP @               ( get the next codeword )
1084                         CFA>                    ( and force it to be printed as a dictionary entry )
1085                         ID. SPACE
1086                 ENDOF
1087                 ' EXIT OF               ( is it EXIT? )
1088                         ( We expect the last word to be EXIT, and if it is then we don't print it
1089                           because EXIT is normally implied by ;.  EXIT can also appear in the middle
1090                           of words, and then it needs to be printed. )
1091                         2DUP                    ( end start end start )
1092                         4 +                     ( end start end start+4 )
1093                         <> IF                   ( end start | we're not at the end )
1094                                 ." EXIT "
1095                         THEN
1096                 ENDOF
1097                                         ( default case: )
1098                         DUP                     ( in the default case we always need to DUP before using )
1099                         CFA>                    ( look up the codeword to get the dictionary entry )
1100                         ID. SPACE               ( and print it )
1101                 ENDCASE
1102
1103                 4 +             ( end start+4 )
1104         REPEAT
1105
1106         ';' EMIT CR
1107
1108         2DROP           ( restore stack )
1109 ;
1110
1111 (
1112         EXECUTION TOKENS ----------------------------------------------------------------------
1113
1114         Standard FORTH defines a concept called an 'execution token' (or 'xt') which is very
1115         similar to a function pointer in C.  We map the execution token to a codeword address.
1116
1117                         execution token of DOUBLE is the address of this codeword
1118                                                     |
1119                                                     V
1120         +---------+---+---+---+---+---+---+---+---+------------+------------+------------+------------+
1121         | LINK    | 6 | D | O | U | B | L | E | 0 | DOCOL      | DUP        | +          | EXIT       |
1122         +---------+---+---+---+---+---+---+---+---+------------+------------+------------+------------+
1123                    len                         pad  codeword                                           ^
1124
1125         There is one assembler primitive for execution tokens, EXECUTE ( xt -- ), which runs them.
1126
1127         You can make an execution token for an existing word the long way using >CFA,
1128         ie: WORD [foo] FIND >CFA will push the xt for foo onto the stack where foo is the
1129         next word in input.  So a very slow way to run DOUBLE might be:
1130
1131                 : DOUBLE DUP + ;
1132                 : SLOW WORD FIND >CFA EXECUTE ;
1133                 5 SLOW DOUBLE . CR      \ prints 10
1134
1135         We also offer a simpler and faster way to get the execution token of any word FOO:
1136
1137                 ['] FOO
1138
1139         (Exercises for readers: (1) What is the difference between ['] FOO and ' FOO?
1140         (2) What is the relationship between ', ['] and LIT?)
1141
1142         More useful is to define anonymous words and/or to assign xt's to variables.
1143
1144         To define an anonymous word (and push its xt on the stack) use :NONAME ... ; as in this
1145         example:
1146
1147                 :NONAME ." anon word was called" CR ;   \ pushes xt on the stack
1148                 DUP EXECUTE EXECUTE                     \ executes the anon word twice
1149
1150         Stack parameters work as expected:
1151
1152                 :NONAME ." called with parameter " . CR ;
1153                 DUP
1154                 10 SWAP EXECUTE         \ prints 'called with parameter 10'
1155                 20 SWAP EXECUTE         \ prints 'called with parameter 20'
1156
1157         Notice that the above code has a memory leak: the anonymous word is still compiled
1158         into the data segment, so even if you lose track of the xt, the word continues to
1159         occupy memory.  A good way to keep track of the xt and thus avoid the memory leak is
1160         to assign it to a CONSTANT, VARIABLE or VALUE:
1161
1162                 0 VALUE ANON
1163                 :NONAME ." anon word was called" CR ; TO ANON
1164                 ANON EXECUTE
1165                 ANON EXECUTE
1166
1167         Another use of :NONAME is to create an array of functions which can be called quickly
1168         (think: fast switch statement).  This example is adapted from the ANS FORTH standard:
1169
1170                 10 CELLS ALLOT CONSTANT CMD-TABLE
1171                 : SET-CMD CELLS CMD-TABLE + ! ;
1172                 : CALL-CMD CELLS CMD-TABLE + @ EXECUTE ;
1173
1174                 :NONAME ." alternate 0 was called" CR ;  0 SET-CMD
1175                 :NONAME ." alternate 1 was called" CR ;  1 SET-CMD
1176                         \ etc...
1177                 :NONAME ." alternate 9 was called" CR ;  9 SET-CMD
1178
1179                 0 CALL-CMD
1180                 1 CALL-CMD
1181 )
1182
1183 : :NONAME
1184         0 0 CREATE      ( create a word with no name - we need a dictionary header because ; expects it )
1185         HERE @          ( current HERE value is the address of the codeword, ie. the xt )
1186         DOCOL ,         ( compile DOCOL (the codeword) )
1187         ]               ( go into compile mode )
1188 ;
1189
1190 : ['] IMMEDIATE
1191         ' LIT ,         ( compile LIT )
1192 ;
1193
1194 (
1195         EXCEPTIONS ----------------------------------------------------------------------
1196
1197         Amazingly enough, exceptions can be implemented directly in FORTH, in fact rather easily.
1198
1199         The general usage is as follows:
1200
1201                 : FOO ( n -- ) THROW ;
1202
1203                 : TEST-EXCEPTIONS
1204                         25 ['] FOO CATCH        \ execute 25 FOO, catching any exception
1205                         ?DUP IF
1206                                 ." called FOO and it threw exception number: "
1207                                 . CR
1208                                 DROP            \ we have to drop the argument of FOO (25)
1209                         THEN
1210                 ;
1211                 \ prints: called FOO and it threw exception number: 25
1212
1213         CATCH runs an execution token and detects whether it throws any exception or not.  The
1214         stack signature of CATCH is rather complicated:
1215
1216                 ( a_n-1 ... a_1 a_0 xt -- r_m-1 ... r_1 r_0 0 )         if xt did NOT throw an exception
1217                 ( a_n-1 ... a_1 a_0 xt -- ?_n-1 ... ?_1 ?_0 e )         if xt DID throw exception 'e'
1218
1219         where a_i and r_i are the (arbitrary number of) argument and return stack contents
1220         before and after xt is EXECUTEd.  Notice in particular the case where an exception
1221         is thrown, the stack pointer is restored so that there are n of _something_ on the
1222         stack in the positions where the arguments a_i used to be.  We don't really guarantee
1223         what is on the stack -- perhaps the original arguments, and perhaps other nonsense --
1224         it largely depends on the implementation of the word that was executed.
1225
1226         THROW, ABORT and a few others throw exceptions.
1227
1228         Exception numbers are non-zero integers.  By convention the positive numbers can be used
1229         for app-specific exceptions and the negative numbers have certain meanings defined in
1230         the ANS FORTH standard.  (For example, -1 is the exception thrown by ABORT).
1231
1232         0 THROW does nothing.  This is the stack signature of THROW:
1233
1234                 ( 0 -- )
1235                 ( * e -- ?_n-1 ... ?_1 ?_0 e )  the stack is restored to the state from the corresponding CATCH
1236
1237         The implementation hangs on the definitions of CATCH and THROW and the state shared
1238         between them.
1239
1240         Up to this point, the return stack has consisted merely of a list of return addresses,
1241         with the top of the return stack being the return address where we will resume executing
1242         when the current word EXITs.  However CATCH will push a more complicated 'exception stack
1243         frame' on the return stack.  The exception stack frame records some things about the
1244         state of execution at the time that CATCH was called.
1245
1246         When called, THROW walks up the return stack (the process is called 'unwinding') until
1247         it finds the exception stack frame.  It then uses the data in the exception stack frame
1248         to restore the state allowing execution to continue after the matching CATCH.  (If it
1249         unwinds the stack and doesn't find the exception stack frame then it prints a message
1250         and drops back to the prompt, which is also normal behaviour for so-called 'uncaught
1251         exceptions').
1252
1253         This is what the exception stack frame looks like.  (As is conventional, the return stack
1254         is shown growing downwards from higher to lower memory addresses).
1255
1256                 +------------------------------+
1257                 | return address from CATCH    |   Notice this is already on the
1258                 |                              |   return stack when CATCH is called.
1259                 +------------------------------+
1260                 | original parameter stack     |
1261                 | pointer                      |
1262                 +------------------------------+  ^
1263                 | exception stack marker       |  |
1264                 | (EXCEPTION-MARKER)           |  |   Direction of stack
1265                 +------------------------------+  |   unwinding by THROW.
1266                                                   |
1267                                                   |
1268
1269         The EXCEPTION-MARKER marks the entry as being an exception stack frame rather than an
1270         ordinary return address, and it is this which THROW "notices" as it is unwinding the
1271         stack.  (If you want to implement more advanced exceptions such as TRY...WITH then
1272         you'll need to use a different value of marker if you want the old and new exception stack
1273         frame layouts to coexist).
1274
1275         What happens if the executed word doesn't throw an exception?  It will eventually
1276         return and call EXCEPTION-MARKER, so EXCEPTION-MARKER had better do something sensible
1277         without us needing to modify EXIT.  This nicely gives us a suitable definition of
1278         EXCEPTION-MARKER, namely a function that just drops the stack frame and itself
1279         returns (thus "returning" from the original CATCH).
1280
1281         One thing to take from this is that exceptions are a relatively lightweight mechanism
1282         in FORTH.
1283 )
1284
1285 : EXCEPTION-MARKER
1286         RDROP                   ( drop the original parameter stack pointer )
1287         0                       ( there was no exception, this is the normal return path )
1288 ;
1289
1290 : CATCH         ( xt -- exn? )
1291         DSP@ 4+ >R              ( save parameter stack pointer (+4 because of xt) on the return stack )
1292         ' EXCEPTION-MARKER 4+   ( push the address of the RDROP inside EXCEPTION-MARKER ... )
1293         >R                      ( ... on to the return stack so it acts like a return address )
1294         EXECUTE                 ( execute the nested function )
1295 ;
1296
1297 : THROW         ( n -- )
1298         ?DUP IF                 ( only act if the exception code <> 0 )
1299                 RSP@                    ( get return stack pointer )
1300                 BEGIN
1301                         DUP R0 4- <             ( RSP < R0 )
1302                 WHILE
1303                         DUP @                   ( get the return stack entry )
1304                         ' EXCEPTION-MARKER 4+ = IF      ( found the EXCEPTION-MARKER on the return stack )
1305                                 4+                      ( skip the EXCEPTION-MARKER on the return stack )
1306                                 RSP!                    ( restore the return stack pointer )
1307
1308                                 ( Restore the parameter stack. )
1309                                 DUP DUP DUP             ( reserve some working space so the stack for this word
1310                                                           doesn't coincide with the part of the stack being restored )
1311                                 R>                      ( get the saved parameter stack pointer | n dsp )
1312                                 4-                      ( reserve space on the stack to store n )
1313                                 SWAP OVER               ( dsp n dsp )
1314                                 !                       ( write n on the stack )
1315                                 DSP! EXIT               ( restore the parameter stack pointer, immediately exit )
1316                         THEN
1317                         4+
1318                 REPEAT
1319
1320                 ( No matching catch - print a message and restart the INTERPRETer. )
1321                 DROP
1322
1323                 CASE
1324                 0 1- OF ( ABORT )
1325                         ." ABORTED" CR
1326                 ENDOF
1327                         ( default case )
1328                         ." UNCAUGHT THROW "
1329                         DUP . CR
1330                 ENDCASE
1331                 QUIT
1332         THEN
1333 ;
1334
1335 : ABORT         ( -- )
1336         0 1- THROW
1337 ;
1338
1339 ( Print a stack trace by walking up the return stack. )
1340 : PRINT-STACK-TRACE
1341         RSP@                            ( start at caller of this function )
1342         BEGIN
1343                 DUP R0 4- <             ( RSP < R0 )
1344         WHILE
1345                 DUP @                   ( get the return stack entry )
1346                 CASE
1347                 ' EXCEPTION-MARKER 4+ OF        ( is it the exception stack frame? )
1348                         ." CATCH ( DSP="
1349                         4+ DUP @ U.             ( print saved stack pointer )
1350                         ." ) "
1351                 ENDOF
1352                                                 ( default case )
1353                         DUP
1354                         CFA>                    ( look up the codeword to get the dictionary entry )
1355                         ?DUP IF                 ( and print it )
1356                                 2DUP                    ( dea addr dea )
1357                                 ID.                     ( print word from dictionary entry )
1358                                 [ CHAR + ] LITERAL EMIT
1359                                 SWAP >DFA 4+ - .        ( print offset )
1360                         THEN
1361                 ENDCASE
1362                 4+                      ( move up the stack )
1363         REPEAT
1364         DROP
1365         CR
1366 ;
1367
1368 (
1369         C STRINGS ----------------------------------------------------------------------
1370
1371         FORTH strings are represented by a start address and length kept on the stack or in memory.
1372
1373         Most FORTHs don't handle C strings, but we need them in order to access the process arguments
1374         and environment left on the stack by the Linux kernel, and to make some system calls.
1375
1376         Operation       Input           Output          FORTH word      Notes
1377         ----------------------------------------------------------------------
1378
1379         Create FORTH string             addr len        S" ..."
1380
1381         Create C string                 c-addr          Z" ..."
1382
1383         C -> FORTH      c-addr          addr len        DUP STRLEN
1384
1385         FORTH -> C      addr len        c-addr          CSTRING         Allocated in a temporary buffer, so
1386                                                                         should be consumed / copied immediately.
1387                                                                         FORTH string should not contain NULs.
1388
1389         For example, DUP STRLEN TELL prints a C string.
1390 )
1391
1392 (
1393         Z" .." is like S" ..." except that the string is terminated by an ASCII NUL character.
1394
1395         To make it more like a C string, at runtime Z" just leaves the address of the string
1396         on the stack (not address & length as with S").  To implement this we need to add the
1397         extra NUL to the string and also a DROP instruction afterwards.  Apart from that the
1398         implementation just a modified S".
1399 )
1400 : Z" IMMEDIATE
1401         STATE @ IF      ( compiling? )
1402                 ' LITSTRING ,   ( compile LITSTRING )
1403                 HERE @          ( save the address of the length word on the stack )
1404                 0 ,             ( dummy length - we don't know what it is yet )
1405                 BEGIN
1406                         KEY             ( get next character of the string )
1407                         DUP '"' <>
1408                 WHILE
1409                         HERE @ C!       ( store the character in the compiled image )
1410                         1 HERE +!       ( increment HERE pointer by 1 byte )
1411                 REPEAT
1412                 0 HERE @ C!     ( add the ASCII NUL byte )
1413                 1 HERE +!
1414                 DROP            ( drop the double quote character at the end )
1415                 DUP             ( get the saved address of the length word )
1416                 HERE @ SWAP -   ( calculate the length )
1417                 4-              ( subtract 4 (because we measured from the start of the length word) )
1418                 SWAP !          ( and back-fill the length location )
1419                 ALIGN           ( round up to next multiple of 4 bytes for the remaining code )
1420                 ' DROP ,        ( compile DROP (to drop the length) )
1421         ELSE            ( immediate mode )
1422                 HERE @          ( get the start address of the temporary space )
1423                 BEGIN
1424                         KEY
1425                         DUP '"' <>
1426                 WHILE
1427                         OVER C!         ( save next character )
1428                         1+              ( increment address )
1429                 REPEAT
1430                 DROP            ( drop the final " character )
1431                 0 SWAP C!       ( store final ASCII NUL )
1432                 HERE @          ( push the start address )
1433         THEN
1434 ;
1435
1436 : STRLEN        ( str -- len )
1437         DUP             ( save start address )
1438         BEGIN
1439                 DUP C@ 0<>      ( zero byte found? )
1440         WHILE
1441                 1+
1442         REPEAT
1443
1444         SWAP -          ( calculate the length )
1445 ;
1446
1447 : CSTRING       ( addr len -- c-addr )
1448         SWAP OVER       ( len saddr len )
1449         HERE @ SWAP     ( len saddr daddr len )
1450         CMOVE           ( len )
1451
1452         HERE @ +        ( daddr+len )
1453         0 SWAP C!       ( store terminating NUL char )
1454
1455         HERE @          ( push start address )
1456 ;
1457
1458 (
1459         THE ENVIRONMENT ----------------------------------------------------------------------
1460
1461         Linux makes the process arguments and environment available to us on the stack.
1462
1463         The top of stack pointer is saved by the early assembler code when we start up in the FORTH
1464         variable S0, and starting at this pointer we can read out the command line arguments and the
1465         environment.
1466
1467         Starting at S0, S0 itself points to argc (the number of command line arguments).
1468
1469         S0+4 points to argv[0], S0+8 points to argv[1] etc up to argv[argc-1].
1470
1471         argv[argc] is a NULL pointer.
1472
1473         After that the stack contains environment variables, a set of pointers to strings of the
1474         form NAME=VALUE and on until we get to another NULL pointer.
1475
1476         The first word that we define, ARGC, pushes the number of command line arguments (note that
1477         as with C argc, this includes the name of the command).
1478 )
1479 : ARGC
1480         S0 @ @
1481 ;
1482
1483 (
1484         n ARGV gets the nth command line argument.
1485
1486         For example to print the command name you would do:
1487                 0 ARGV TELL CR
1488 )
1489 : ARGV ( n -- str u )
1490         1+ CELLS S0 @ + ( get the address of argv[n] entry )
1491         @               ( get the address of the string )
1492         DUP STRLEN      ( and get its length / turn it into a FORTH string )
1493 ;
1494
1495 (
1496         ENVIRON returns the address of the first environment string.  The list of strings ends
1497         with a NULL pointer.
1498
1499         For example to print the first string in the environment you could do:
1500                 ENVIRON @ DUP STRLEN TELL
1501 )
1502 : ENVIRON       ( -- addr )
1503         ARGC            ( number of command line parameters on the stack to skip )
1504         2 +             ( skip command line count and NULL pointer after the command line args )
1505         CELLS           ( convert to an offset )
1506         S0 @ +          ( add to base stack address )
1507 ;
1508
1509 (
1510         SYSTEM CALLS AND FILES  ----------------------------------------------------------------------
1511
1512         Miscellaneous words related to system calls, and standard access to files.
1513 )
1514
1515 ( BYE exits by calling the Linux exit(2) syscall. )
1516 : BYE           ( -- )
1517         0               ( return code (0) )
1518         SYS_EXIT        ( system call number )
1519         SYSCALL1
1520 ;
1521
1522 (
1523         UNUSED returns the number of cells remaining in the user memory (data segment).
1524
1525         For our implementation we will use Linux brk(2) system call to find out the end
1526         of the data segment and subtract HERE from it.
1527 )
1528 : GET-BRK       ( -- brkpoint )
1529         0 SYS_BRK SYSCALL1      ( call brk(0) )
1530 ;
1531
1532 : UNUSED        ( -- n )
1533         GET-BRK         ( get end of data segment according to the kernel )
1534         HERE @          ( get current position in data segment )
1535         -
1536         4 /             ( returns number of cells )
1537 ;
1538
1539 (
1540         MORECORE increases the data segment by the specified number of (4 byte) cells.
1541
1542         NB. The number of cells requested should normally be a multiple of 1024.  The
1543         reason is that Linux can't extend the data segment by less than a single page
1544         (4096 bytes or 1024 cells).
1545
1546         This FORTH doesn't automatically increase the size of the data segment "on demand"
1547         (ie. when , (COMMA), ALLOT, CREATE, and so on are used).  Instead the programmer
1548         needs to be aware of how much space a large allocation will take, check UNUSED, and
1549         call MORECORE if necessary.  A simple programming exercise is to change the
1550         implementation of the data segment so that MORECORE is called automatically if
1551         the program needs more memory.
1552 )
1553 : BRK           ( brkpoint -- )
1554         SYS_BRK SYSCALL1
1555 ;
1556
1557 : MORECORE      ( cells -- )
1558         CELLS GET-BRK + BRK
1559 ;
1560
1561 (
1562         Standard FORTH provides some simple file access primitives which we model on
1563         top of Linux syscalls.
1564
1565         The main complication is converting FORTH strings (address & length) into C
1566         strings for the Linux kernel.
1567
1568         Notice there is no buffering in this implementation.
1569 )
1570
1571 : R/O ( -- fam ) O_RDONLY ;
1572 : R/W ( -- fam ) O_RDWR ;
1573
1574 : OPEN-FILE     ( addr u fam -- fd 0 (if successful) | c-addr u fam -- fd errno (if there was an error) )
1575         ROT             ( fam addr u )
1576         CSTRING         ( fam cstring )
1577         SYS_OPEN SYSCALL2 ( open (filename, flags) )
1578         DUP             ( fd fd )
1579         DUP 0< IF       ( errno? )
1580                 NEGATE          ( fd errno )
1581         ELSE
1582                 DROP 0          ( fd 0 )
1583         THEN
1584 ;
1585
1586 : CREATE-FILE   ( addr u fam -- fd 0 (if successful) | c-addr u fam -- fd errno (if there was an error) )
1587         O_CREAT OR
1588         O_TRUNC OR
1589         ROT             ( fam addr u )
1590         CSTRING         ( fam cstring )
1591         420 ROT         ( 0644 fam cstring )
1592         SYS_OPEN SYSCALL3 ( open (filename, flags|O_TRUNC|O_CREAT, 0644) )
1593         DUP             ( fd fd )
1594         DUP 0< IF       ( errno? )
1595                 NEGATE          ( fd errno )
1596         ELSE
1597                 DROP 0          ( fd 0 )
1598         THEN
1599 ;
1600
1601 : CLOSE-FILE    ( fd -- 0 (if successful) | fd -- errno (if there was an error) )
1602         SYS_CLOSE SYSCALL1
1603         NEGATE
1604 ;
1605
1606 : READ-FILE     ( addr u fd -- u2 0 (if successful) | addr u fd -- 0 0 (if EOF) | addr u fd -- u2 errno (if error) )
1607         ROT SWAP -ROT   ( u addr fd )
1608         SYS_READ SYSCALL3
1609
1610         DUP             ( u2 u2 )
1611         DUP 0< IF       ( errno? )
1612                 NEGATE          ( u2 errno )
1613         ELSE
1614                 DROP 0          ( u2 0 )
1615         THEN
1616 ;
1617
1618 (
1619         PERROR prints a message for an errno, similar to C's perror(3) but we don't have the extensive
1620         list of strerror strings available, so all we can do is print the errno.
1621 )
1622 : PERROR        ( errno addr u -- )
1623         TELL
1624         ':' EMIT SPACE
1625         ." ERRNO="
1626         . CR
1627 ;
1628
1629 (
1630         ASSEMBLER CODE ----------------------------------------------------------------------
1631
1632         This is just the outline of a simple assembler, allowing you to write FORTH primitives
1633         in assembly language.
1634
1635         Assembly primitives begin ': NAME' in the normal way, but are ended with ;CODE.  ;CODE
1636         updates the header so that the codeword isn't DOCOL, but points instead to the assembled
1637         code (in the DFA part of the word).
1638
1639         We provide a convenience macro NEXT (you guessed what it does).  However you don't need to
1640         use it because ;CODE will put a NEXT at the end of your word.
1641
1642         The rest consists of some immediate words which expand into machine code appended to the
1643         definition of the word.  Only a very tiny part of the i386 assembly space is covered, just
1644         enough to write a few assembler primitives below.
1645 )
1646
1647 HEX
1648
1649 ( Equivalent to the NEXT macro )
1650 : NEXT IMMEDIATE AD C, FF C, 20 C, ;
1651
1652 : ;CODE IMMEDIATE
1653         [COMPILE] NEXT          ( end the word with NEXT macro )
1654         ALIGN                   ( machine code is assembled in bytes so isn't necessarily aligned at the end )
1655         LATEST @ DUP
1656         HIDDEN                  ( unhide the word )
1657         DUP >DFA SWAP >CFA !    ( change the codeword to point to the data area )
1658         [COMPILE] [             ( go back to immediate mode )
1659 ;
1660
1661 ( The i386 registers )
1662 : EAX IMMEDIATE 0 ;
1663 : ECX IMMEDIATE 1 ;
1664 : EDX IMMEDIATE 2 ;
1665 : EBX IMMEDIATE 3 ;
1666 : ESP IMMEDIATE 4 ;
1667 : EBP IMMEDIATE 5 ;
1668 : ESI IMMEDIATE 6 ;
1669 : EDI IMMEDIATE 7 ;
1670
1671 ( i386 stack instructions )
1672 : PUSH IMMEDIATE 50 + C, ;
1673 : POP IMMEDIATE 58 + C, ;
1674
1675 ( RDTSC instruction )
1676 : RDTSC IMMEDIATE 0F C, 31 C, ;
1677
1678 DECIMAL
1679
1680 (
1681         RDTSC is an assembler primitive which reads the Pentium timestamp counter (a very fine-
1682         grained counter which counts processor clock cycles).  Because the TSC is 64 bits wide
1683         we have to push it onto the stack in two slots.
1684 )
1685 : RDTSC         ( -- lsb msb )
1686         RDTSC           ( writes the result in %edx:%eax )
1687         EAX PUSH        ( push lsb )
1688         EDX PUSH        ( push msb )
1689 ;CODE
1690
1691 (
1692         INLINE can be used to inline an assembler primitive into the current (assembler)
1693         word.
1694
1695         For example:
1696
1697                 : 2DROP INLINE DROP INLINE DROP ;CODE
1698
1699         will build an efficient assembler word 2DROP which contains the inline assembly code
1700         for DROP followed by DROP (eg. two 'pop %eax' instructions in this case).
1701
1702         Another example.  Consider this ordinary FORTH definition:
1703
1704                 : C@++ ( addr -- addr+1 byte ) DUP 1+ SWAP C@ ;
1705
1706         (it is equivalent to the C operation '*p++' where p is a pointer to char).  If we
1707         notice that all of the words used to define C@++ are in fact assembler primitives,
1708         then we can write a faster (but equivalent) definition like this:
1709
1710                 : C@++ INLINE DUP INLINE 1+ INLINE SWAP INLINE C@ ;CODE
1711
1712         There are several conditions that must be met for INLINE to be used successfully:
1713
1714         (1) You must be currently defining an assembler word (ie. : ... ;CODE).
1715
1716         (2) The word that you are inlining must be known to be an assembler word.  If you try
1717         to inline a FORTH word, you'll get an error message.
1718
1719         (3) The assembler primitive must be position-independent code and must end with a
1720         single NEXT macro.
1721
1722         Exercises for the reader: (a) Generalise INLINE so that it can inline FORTH words when
1723         building FORTH words. (b) Further generalise INLINE so that it does something sensible
1724         when you try to inline FORTH into assembler and vice versa.
1725
1726         The implementation of INLINE is pretty simple.  We find the word in the dictionary,
1727         check it's an assembler word, then copy it into the current definition, byte by byte,
1728         until we reach the NEXT macro (which is not copied).
1729 )
1730 HEX
1731 : =NEXT         ( addr -- next? )
1732            DUP C@ AD <> IF DROP FALSE EXIT THEN
1733         1+ DUP C@ FF <> IF DROP FALSE EXIT THEN
1734         1+     C@ 20 <> IF      FALSE EXIT THEN
1735         TRUE
1736 ;
1737 DECIMAL
1738
1739 ( (INLINE) is the lowlevel inline function. )
1740 : (INLINE)      ( cfa -- )
1741         @                       ( codeword points to the code, remember )
1742         BEGIN                   ( copy bytes until we hit NEXT macro )
1743                 DUP =NEXT NOT
1744         WHILE
1745                 DUP C@ C,
1746                 1+
1747         REPEAT
1748         DROP
1749 ;
1750
1751 : INLINE IMMEDIATE
1752         WORD FIND               ( find the word in the dictionary )
1753         >CFA                    ( codeword )
1754
1755         DUP @ DOCOL = IF        ( check codeword <> DOCOL (ie. not a FORTH word) )
1756                 ." Cannot INLINE FORTH words" CR ABORT
1757         THEN
1758
1759         (INLINE)
1760 ;
1761
1762 HIDE =NEXT
1763
1764 (
1765         NOTES ----------------------------------------------------------------------
1766
1767         DOES> isn't possible to implement with this FORTH because we don't have a separate
1768         data pointer.
1769 )
1770
1771 (
1772         WELCOME MESSAGE ----------------------------------------------------------------------
1773
1774         Print the version and OK prompt.
1775 )
1776
1777 : WELCOME
1778         S" TEST-MODE" FIND NOT IF
1779                 ." JONESFORTH VERSION " VERSION . CR
1780                 UNUSED . ." CELLS REMAINING" CR
1781                 ." OK "
1782         THEN
1783 ;
1784
1785 WELCOME
1786 HIDE WELCOME