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