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.10 2007-09-29 16:06:27 rich Exp $
7 \ The first part of this tutorial is in jonesforth.S. Get if from http://annexia.org/forth
9 \ PUBLIC DOMAIN ----------------------------------------------------------------------
11 \ I, the copyright holder of this work, hereby release it into the public domain. This applies worldwide.
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.
16 \ SETTING UP ----------------------------------------------------------------------
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:
22 \<------------------------------------------------------------------------------------------------------------------------>
24 \ Secondly make sure TABS are set to 8 characters. The following should be a vertical
25 \ line. If not, sort out your tabs.
31 \ Thirdly I assume that your screen is at least 50 characters high.
33 \ START OF FORTH CODE ----------------------------------------------------------------------
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.
39 \ Some notes about the code:
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.
45 \ FORTH is case-sensitive. Use capslock!
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.
53 \ Define some character constants
57 \ CR prints a carriage return
60 \ SPACE prints a space
61 : SPACE 'SPACE' EMIT ;
63 \ DUP, DROP are defined in assembly for speed, but this is how you might define them
64 \ in FORTH. Notice use of the scratch variables _X and _Y.
65 \ : DUP _X ! _X @ _X @ ;
68 \ The 2... versions of the standard operators work on pairs of stack entries. They're not used
69 \ very commonly so not really worth writing in assembler. Here is how they are defined in FORTH.
73 \ More standard FORTH words.
77 \ NEGATE leaves the negative of a number on the stack.
80 \ Standard words for booleans.
85 \ LITERAL takes whatever is on the stack and compiles LIT <foo>
88 , \ compile the literal itself (from the stack)
91 \ Now we can use [ and ] to insert literals which are calculated at compile time. (Recall that
92 \ [ and ] are the FORTH words which switch into and out of immediate mode.)
93 \ Within definitions, use [ ... ] LITERAL anywhere that '...' is a constant expression which you
94 \ would rather only compute once (at compile time, rather than calculating it each time your word runs).
96 [ \ go into immediate mode (temporarily)
97 CHAR : \ push the number 58 (ASCII code of colon) on the parameter stack
98 ] \ go back to compile mode
99 LITERAL \ compile LIT 58 as the definition of ':' word
102 \ A few more character constants defined the same way as above.
103 : ';' [ CHAR ; ] LITERAL ;
104 : '(' [ CHAR ( ] LITERAL ;
105 : ')' [ CHAR ) ] LITERAL ;
106 : '"' [ CHAR " ] LITERAL ;
107 : 'A' [ CHAR A ] LITERAL ;
108 : '0' [ CHAR 0 ] LITERAL ;
109 : '-' [ CHAR - ] LITERAL ;
110 : '.' [ CHAR . ] LITERAL ;
112 \ While compiling, '[COMPILE] word' compiles 'word' if it would otherwise be IMMEDIATE.
113 : [COMPILE] IMMEDIATE
114 WORD \ get the next word
115 FIND \ find it in the dictionary
116 >CFA \ get its codeword
120 \ RECURSE makes a recursive call to the current word that is being compiled.
122 \ Normally while a word is being compiled, it is marked HIDDEN so that references to the
123 \ same word within are calls to the previous definition of the word. However we still have
124 \ access to the word which we are currently compiling through the LATEST pointer so we
125 \ can use that to compile a recursive call.
127 LATEST @ \ LATEST points to the word being compiled at the moment
128 >CFA \ get the codeword
132 \ CONTROL STRUCTURES ----------------------------------------------------------------------
134 \ So far we have defined only very simple definitions. Before we can go further, we really need to
135 \ make some control structures, like IF ... THEN and loops. Luckily we can define arbitrary control
136 \ structures directly in FORTH.
138 \ Please note that the control structures as I have defined them here will only work inside compiled
139 \ words. If you try to type in expressions using IF, etc. in immediate mode, then they won't work.
140 \ Making these work in immediate mode is left as an exercise for the reader.
142 \ condition IF true-part THEN rest
143 \ -- compiles to: --> condition 0BRANCH OFFSET true-part rest
144 \ where OFFSET is the offset of 'rest'
145 \ condition IF true-part ELSE false-part THEN
146 \ -- compiles to: --> condition 0BRANCH OFFSET true-part BRANCH OFFSET2 false-part rest
147 \ where OFFSET if the offset of false-part and OFFSET2 is the offset of rest
149 \ IF is an IMMEDIATE word which compiles 0BRANCH followed by a dummy offset, and places
150 \ the address of the 0BRANCH on the stack. Later when we see THEN, we pop that address
151 \ off the stack, calculate the offset, and back-fill the offset.
153 ' 0BRANCH , \ compile 0BRANCH
154 HERE @ \ save location of the offset on the stack
155 0 , \ compile a dummy offset
160 HERE @ SWAP - \ calculate the offset from the address saved on the stack
161 SWAP ! \ store the offset in the back-filled location
165 ' BRANCH , \ definite branch to just over the false-part
166 HERE @ \ save location of the offset on the stack
167 0 , \ compile a dummy offset
168 SWAP \ now back-fill the original (IF) offset
169 DUP \ same as for THEN word above
174 \ BEGIN loop-part condition UNTIL
175 \ -- compiles to: --> loop-part condition 0BRANCH OFFSET
176 \ where OFFSET points back to the loop-part
177 \ This is like do { loop-part } while (condition) in the C language
179 HERE @ \ save location on the stack
183 ' 0BRANCH , \ compile 0BRANCH
184 HERE @ - \ calculate the offset from the address saved on the stack
185 , \ compile the offset here
188 \ BEGIN loop-part AGAIN
189 \ -- compiles to: --> loop-part BRANCH OFFSET
190 \ where OFFSET points back to the loop-part
191 \ In other words, an infinite loop which can only be returned from with EXIT
193 ' BRANCH , \ compile BRANCH
194 HERE @ - \ calculate the offset back
195 , \ compile the offset here
198 \ BEGIN condition WHILE loop-part REPEAT
199 \ -- compiles to: --> condition 0BRANCH OFFSET2 loop-part BRANCH OFFSET
200 \ where OFFSET points back to condition (the beginning) and OFFSET2 points to after the whole piece of code
201 \ So this is like a while (condition) { loop-part } loop in the C language
203 ' 0BRANCH , \ compile 0BRANCH
204 HERE @ \ save location of the offset2 on the stack
205 0 , \ compile a dummy offset2
209 ' BRANCH , \ compile BRANCH
210 SWAP \ get the original offset (from BEGIN)
211 HERE @ - , \ and compile it after BRANCH
213 HERE @ SWAP - \ calculate the offset2
214 SWAP ! \ and back-fill it in the original location
217 \ COMMENTS ----------------------------------------------------------------------
219 \ FORTH allows ( ... ) as comments within function definitions. This works by having an IMMEDIATE
220 \ word called ( which just drops input characters until it hits the corresponding ).
222 1 \ allowed nested parens by keeping track of depth
224 KEY \ read next character
225 DUP '(' = IF \ open paren?
226 DROP \ drop the open paren
229 ')' = IF \ close paren?
233 DUP 0= UNTIL \ continue until we reach matching close paren, depth 0
234 DROP \ drop the depth counter
238 From now on we can use ( ... ) for comments.
240 STACK NOTATION ----------------------------------------------------------------------
242 In FORTH style we can also use ( ... -- ... ) to show the effects that a word has on the
243 parameter stack. For example:
245 ( n -- ) means that the word consumes an integer (n) from the parameter stack.
246 ( b a -- c ) means that the word uses two integers (a and b, where a is at the top of stack)
247 and returns a single integer (c).
248 ( -- ) means the word has no effect on the stack
251 ( Some more complicated stack examples, showing the stack notation. )
252 : NIP ( x y -- y ) SWAP DROP ;
253 : TUCK ( x y -- y x y ) DUP ROT ;
254 : PICK ( x_u ... x_1 x_0 u -- x_u ... x_1 x_0 x_u )
255 1+ ( add one because of 'u' on the stack )
256 4 * ( multiply by the word size )
257 DSP@ + ( add to the stack pointer )
261 ( With the looping constructs, we can now write SPACES, which writes n spaces to stdout. )
264 DUP 0> ( while n > 0 )
266 SPACE ( print a space )
267 1- ( until we count down to 0 )
272 ( Standard words for manipulating BASE. )
273 : DECIMAL ( -- ) 10 BASE ! ;
274 : HEX ( -- ) 16 BASE ! ;
277 PRINTING NUMBERS ----------------------------------------------------------------------
279 The standard FORTH word . (DOT) is very important. It takes the number at the top
280 of the stack and prints it out. However first I'm going to implement some lower-level
283 U.R ( u width -- ) which prints an unsigned number, padded to a certain width
284 U. ( u -- ) which prints an unsigned number
285 .R ( n width -- ) which prints a signed number, padded to a certain width.
289 will print out these characters:
290 <space> <space> - 1 2 3
292 In other words, the number padded left to a certain number of characters.
294 The full number is printed even if it is wider than width, and this is what allows us to
295 define the ordinary functions U. and . (we just set width to zero knowing that the full
296 number will be printed anyway).
298 Another wrinkle of . and friends is that they obey the current base in the variable BASE.
299 BASE can be anything in the range 2 to 36.
301 While we're defining . &c we can also define .S which is a useful debugging tool. This
302 word prints the current stack (non-destructively) from top to bottom.
305 ( This is the underlying recursive definition of U. )
307 BASE @ /MOD ( width rem quot )
308 DUP 0<> IF ( if quotient <> 0 then )
309 RECURSE ( print the quotient )
311 DROP ( drop the zero quotient )
314 ( print the remainder )
316 '0' ( decimal digits 0..9 )
318 10 - ( hex and beyond digits A..Z )
326 FORTH word .S prints the contents of the stack. It doesn't alter the stack.
327 Very useful for debugging.
330 DSP@ ( get current stack pointer )
334 DUP @ U. ( print the stack element )
341 ( This word returns the width (in characters) of an unsigned number in the current base )
342 : UWIDTH ( u -- width )
343 BASE @ / ( rem quot )
344 DUP 0<> IF ( if quotient <> 0 then )
345 RECURSE 1+ ( return 1+recursive call )
347 DROP ( drop the zero quotient )
355 UWIDTH ( width u uwidth )
356 -ROT ( u uwidth width )
357 SWAP - ( u width-uwidth )
358 ( At this point if the requested width is narrower, we'll have a negative number on the stack.
359 Otherwise the number on the stack is the number of spaces to print. But SPACES won't print
360 a negative number of spaces anyway, so it's now safe to call SPACES ... )
362 ( ... and then call the underlying implementation of U. )
367 .R prints a signed number, padded to a certain width. We can't just print the sign
368 and call U.R because we want the sign to be next to the number ('-123' instead of '- 123').
374 1 ( save a flag to remember that it was negative | width n 1 )
383 SWAP ( flag width u )
384 DUP ( flag width u u )
385 UWIDTH ( flag width u uwidth )
386 -ROT ( flag u uwidth width )
387 SWAP - ( flag u width-uwidth )
392 IF ( was it negative? print the - character )
399 ( Finally we can define word . in terms of .R, with a trailing space. )
402 ( The real U., note the trailing space. )
405 ( ? fetches the integer at an address and prints it. )
406 : ? ( addr -- ) @ . ;
408 ( c a b WITHIN returns true if a <= c and c < b )
424 ( DEPTH returns the depth of the stack. )
427 4- ( adjust because S0 was on the stack when we pushed DSP )
431 ALIGNED takes an address and rounds it up (aligns it) to the next 4 byte boundary.
433 : ALIGNED ( addr -- addr )
434 3 + 3 INVERT AND ( (addr+3) & ~3 )
438 ALIGN aligns the HERE pointer, so the next word appended will be aligned properly.
440 : ALIGN HERE @ ALIGNED HERE ! ;
443 STRINGS ----------------------------------------------------------------------
445 S" string" is used in FORTH to define strings. It leaves the address of the string and
446 its length on the stack, (length at the top of stack). The space following S" is the normal
447 space between FORTH words and is not a part of the string.
449 This is tricky to define because it has to do different things depending on whether
450 we are compiling or in immediate mode. (Thus the word is marked IMMEDIATE so it can
451 detect this and do different things).
453 In compile mode we append
454 LITSTRING <string length> <string rounded up 4 bytes>
455 to the current word. The primitive LITSTRING does the right thing when the current
458 In immediate mode there isn't a particularly good place to put the string, but in this
459 case we put the string at HERE (but we _don't_ change HERE). This is meant as a temporary
460 location, likely to be overwritten soon after.
462 : S" IMMEDIATE ( -- addr len )
463 STATE @ IF ( compiling? )
464 ' LITSTRING , ( compile LITSTRING )
465 HERE @ ( save the address of the length word on the stack )
466 0 , ( dummy length - we don't know what it is yet )
468 KEY ( get next character of the string )
471 HERE @ C! ( store the character in the compiled image )
472 1 HERE +! ( increment HERE pointer by 1 byte )
474 DROP ( drop the double quote character at the end )
475 DUP ( get the saved address of the length word )
476 HERE @ SWAP - ( calculate the length )
477 4- ( subtract 4 (because we measured from the start of the length word) )
478 SWAP ! ( and back-fill the length location )
479 ALIGN ( round up to next multiple of 4 bytes for the remaining code )
480 ELSE ( immediate mode )
481 HERE @ ( get the start address of the temporary space )
486 OVER C! ( save next character )
487 1+ ( increment address )
489 DROP ( drop the final " character )
490 HERE @ - ( calculate the length )
491 HERE @ ( push the start address )
497 ." is the print string operator in FORTH. Example: ." Something to print"
498 The space after the operator is the ordinary space required between words and is not
499 a part of what is printed.
501 In immediate mode we just keep reading characters and printing them until we get to
502 the next double quote.
504 In compile mode we use S" to store the string, then add TELL afterwards:
505 LITSTRING <string length> <string rounded up to 4 bytes> TELL
507 It may be interesting to note the use of [COMPILE] to turn the call to the immediate
508 word S" into compilation of that word. It compiles it into the definition of .",
509 not into the definition of the word being compiled when this is running (complicated
512 : ." IMMEDIATE ( -- )
513 STATE @ IF ( compiling? )
514 [COMPILE] S" ( read the string, and compile LITSTRING, etc. )
515 ' TELL , ( compile the final TELL )
517 ( In immediate mode, just read characters and print them until we get
518 to the ending double quote. )
522 DROP ( drop the double quote character )
523 EXIT ( return from this function )
531 CONSTANTS AND VARIABLES ----------------------------------------------------------------------
533 In FORTH, global constants and variables are defined like this:
535 10 CONSTANT TEN when TEN is executed, it leaves the integer 10 on the stack
536 VARIABLE VAR when VAR is executed, it leaves the address of VAR on the stack
538 Constants can be read but not written, eg:
542 You can read a variable (in this example called VAR) by doing:
544 VAR @ leaves the value of VAR on the stack
545 VAR @ . CR prints the value of VAR
546 VAR ? CR same as above, since ? is the same as @ .
548 and update the variable by doing:
550 20 VAR ! sets VAR to 20
552 Note that variables are uninitialised (but see VALUE later on which provides initialised
553 variables with a slightly simpler syntax).
555 How can we define the words CONSTANT and VARIABLE?
557 The trick is to define a new word for the variable itself (eg. if the variable was called
558 'VAR' then we would define a new word called VAR). This is easy to do because we exposed
559 dictionary entry creation through the CREATE word (part of the definition of : above).
560 A call to CREATE TEN leaves the dictionary entry:
565 +---------+---+---+---+---+
566 | LINK | 3 | T | E | N |
567 +---------+---+---+---+---+
570 For CONSTANT we can continue by appending DOCOL (the codeword), then LIT followed by
571 the constant itself and then EXIT, forming a little word definition that returns the
574 +---------+---+---+---+---+------------+------------+------------+------------+
575 | LINK | 3 | T | E | N | DOCOL | LIT | 10 | EXIT |
576 +---------+---+---+---+---+------------+------------+------------+------------+
579 Notice that this word definition is exactly the same as you would have got if you had
582 Note for people reading the code below: DOCOL is a constant word which we defined in the
583 assembler part which returns the value of the assembler symbol of the same name.
586 CREATE ( make the dictionary entry (the name follows CONSTANT) )
587 DOCOL , ( append DOCOL (the codeword field of this word) )
588 ' LIT , ( append the codeword LIT )
589 , ( append the value on the top of the stack )
590 ' EXIT , ( append the codeword EXIT )
594 VARIABLE is a little bit harder because we need somewhere to put the variable. There is
595 nothing particularly special about the 'user definitions area' (the area of memory pointed
596 to by HERE where we have previously just stored new word definitions). We can slice off
597 bits of this memory area to store anything we want, so one possible definition of
598 VARIABLE might create this:
600 +--------------------------------------------------------------+
603 +---------+---------+---+---+---+---+------------+------------+---|--------+------------+
604 | <var> | LINK | 3 | V | A | R | DOCOL | LIT | <addr var> | EXIT |
605 +---------+---------+---+---+---+---+------------+------------+------------+------------+
608 where <var> is the place to store the variable, and <addr var> points back to it.
610 To make this more general let's define a couple of words which we can use to allocate
611 arbitrary memory from the user definitions area.
613 First ALLOT, where n ALLOT allocates n bytes of memory. (Note when calling this that
614 it's a very good idea to make sure that n is a multiple of 4, or at least that next time
615 a word is compiled that HERE has been left as a multiple of 4).
617 : ALLOT ( n -- addr )
618 HERE @ SWAP ( here n )
619 HERE +! ( adds n to HERE, after this the old value of HERE is still on the stack )
623 Second, CELLS. In FORTH the phrase 'n CELLS ALLOT' means allocate n integers of whatever size
624 is the natural size for integers on this machine architecture. On this 32 bit machine therefore
625 CELLS just multiplies the top of stack by 4.
627 : CELLS ( n -- n ) 4 * ;
630 So now we can define VARIABLE easily in much the same way as CONSTANT above. Refer to the
631 diagram above to see what the word that this creates will look like.
634 1 CELLS ALLOT ( allocate 1 cell of memory, push the pointer to this memory )
635 CREATE ( make the dictionary entry (the name follows VARIABLE) )
636 DOCOL , ( append DOCOL (the codeword field of this word) )
637 ' LIT , ( append the codeword LIT )
638 , ( append the pointer to the new memory )
639 ' EXIT , ( append the codeword EXIT )
643 VALUES ----------------------------------------------------------------------
645 VALUEs are like VARIABLEs but with a simpler syntax. You would generally use them when you
646 want a variable which is read often, and written infrequently.
648 20 VALUE VAL creates VAL with initial value 20
649 VAL pushes the value directly on the stack
650 30 TO VAL updates VAL, setting it to 30
652 Notice that 'VAL' on its own doesn't return the address of the value, but the value itself,
653 making values simpler and more obvious to use than variables (no indirection through '@').
654 The price is a more complicated implementation, although despite the complexity there is no
655 performance penalty at runtime.
657 A naive implementation of 'TO' would be quite slow, involving a dictionary search each time.
658 But because this is FORTH we have complete control of the compiler so we can compile TO more
659 efficiently, turning:
663 and calculating <addr> (the address of the value) at compile time.
665 Now this is the clever bit. We'll compile our value like this:
667 +---------+---+---+---+---+------------+------------+------------+------------+
668 | LINK | 3 | V | A | L | DOCOL | LIT | <value> | EXIT |
669 +---------+---+---+---+---+------------+------------+------------+------------+
672 where <value> is the actual value itself. Note that when VAL executes, it will push the
673 value on the stack, which is what we want.
675 But what will TO use for the address <addr>? Why of course a pointer to that <value>:
677 code compiled - - - - --+------------+------------+------------+-- - - - -
678 by TO VAL | LIT | <addr> | ! |
679 - - - - --+------------+-----|------+------------+-- - - - -
682 +---------+---+---+---+---+------------+------------+------------+------------+
683 | LINK | 3 | V | A | L | DOCOL | LIT | <value> | EXIT |
684 +---------+---+---+---+---+------------+------------+------------+------------+
687 In other words, this is a kind of self-modifying code.
689 (Note to the people who want to modify this FORTH to add inlining: values defined this
690 way cannot be inlined).
693 CREATE ( make the dictionary entry (the name follows VALUE) )
694 DOCOL , ( append DOCOL )
695 ' LIT , ( append the codeword LIT )
696 , ( append the initial value )
697 ' EXIT , ( append the codeword EXIT )
700 : TO IMMEDIATE ( n -- )
701 WORD ( get the name of the value )
702 FIND ( look it up in the dictionary )
703 >DFA ( get a pointer to the first data field (the 'LIT') )
704 4+ ( increment to point at the value )
705 STATE @ IF ( compiling? )
706 ' LIT , ( compile LIT )
707 , ( compile the address of the value )
709 ELSE ( immediate mode )
710 ! ( update it straightaway )
714 ( x +TO VAL adds x to VAL )
716 WORD ( get the name of the value )
717 FIND ( look it up in the dictionary )
718 >DFA ( get a pointer to the first data field (the 'LIT') )
719 4+ ( increment to point at the value )
720 STATE @ IF ( compiling? )
721 ' LIT , ( compile LIT )
722 , ( compile the address of the value )
723 ' +! , ( compile +! )
724 ELSE ( immediate mode )
725 +! ( update it straightaway )
730 PRINTING THE DICTIONARY ----------------------------------------------------------------------
732 ID. takes an address of a dictionary entry and prints the word's name.
734 For example: LATEST @ ID. would print the name of the last word that was defined.
737 4+ ( skip over the link pointer )
738 DUP C@ ( get the flags/length byte )
739 F_LENMASK AND ( mask out the flags - just want the length )
742 DUP 0> ( length > 0? )
744 SWAP 1+ ( addr len -- len addr+1 )
745 DUP C@ ( len addr -- len addr char | get the next character)
746 EMIT ( len addr char -- len addr | and print it)
747 SWAP 1- ( len addr -- addr len-1 | subtract one from length )
749 2DROP ( len addr -- )
753 'WORD word FIND ?HIDDEN' returns true if 'word' is flagged as hidden.
755 'WORD word FIND ?IMMEDIATE' returns true if 'word' is flagged as immediate.
758 4+ ( skip over the link pointer )
759 C@ ( get the flags/length byte )
760 F_HIDDEN AND ( mask the F_HIDDEN flag and return it (as a truth value) )
763 4+ ( skip over the link pointer )
764 C@ ( get the flags/length byte )
765 F_IMMED AND ( mask the F_IMMED flag and return it (as a truth value) )
769 WORDS prints all the words defined in the dictionary, starting with the word defined most recently.
770 However it doesn't print hidden words.
772 The implementation simply iterates backwards from LATEST using the link pointers.
775 LATEST @ ( start at LATEST dictionary entry )
777 DUP 0<> ( while link pointer is not null )
779 DUP ?HIDDEN NOT IF ( ignore hidden words )
780 DUP ID. ( but if not hidden, print the word )
783 @ ( dereference the link pointer - go to previous word )
790 FORGET ----------------------------------------------------------------------
792 So far we have only allocated words and memory. FORTH provides a rather primitive method
795 'FORGET word' deletes the definition of 'word' from the dictionary and everything defined
796 after it, including any variables and other memory allocated after.
798 The implementation is very simple - we look up the word (which returns the dictionary entry
799 address). Then we set HERE to point to that address, so in effect all future allocations
800 and definitions will overwrite memory starting at the word. We also need to set LATEST to
801 point to the previous word.
803 Note that you cannot FORGET built-in words (well, you can try but it will probably cause
806 XXX: Because we wrote VARIABLE to store the variable in memory allocated before the word,
807 in the current implementation VARIABLE FOO FORGET FOO will leak 1 cell of memory.
810 WORD FIND ( find the word, gets the dictionary entry address )
811 DUP @ LATEST ! ( set LATEST to point to the previous word )
812 HERE ! ( and store HERE with the dictionary address )
816 DUMP ----------------------------------------------------------------------
818 DUMP is used to dump out the contents of memory, in the 'traditional' hexdump format.
820 Notice that the parameters to DUMP (address, length) are compatible with string words
823 : DUMP ( addr len -- )
824 BASE @ ROT ( save the current BASE at the bottom of the stack )
825 HEX ( and switch the hexadecimal mode )
828 DUP 0> ( while len > 0 )
830 OVER 8 U.R ( print the address )
833 ( print up to 16 words on this line )
834 2DUP ( addr len addr len )
835 1- 15 AND 1+ ( addr len addr linelen )
837 DUP 0> ( while linelen > 0 )
839 SWAP ( addr len linelen addr )
840 DUP C@ ( addr len linelen addr byte )
841 2 .R SPACE ( print the byte )
842 1+ SWAP 1- ( addr len linelen addr -- addr len addr+1 linelen-1 )
846 ( print the ASCII equivalents )
847 2DUP 1- 15 AND 1+ ( addr len addr linelen )
849 DUP 0> ( while linelen > 0)
851 SWAP ( addr len linelen addr )
852 DUP C@ ( addr len linelen addr byte )
853 DUP 32 128 WITHIN IF ( 32 <= c < 128? )
858 1+ SWAP 1- ( addr len linelen addr -- addr len addr+1 linelen-1 )
863 DUP 1- 15 AND 1+ ( addr len linelen )
864 DUP ( addr len linelen linelen )
865 ROT ( addr linelen len linelen )
866 - ( addr linelen len-linelen )
867 ROT ( len-linelen addr linelen )
868 + ( len-linelen addr+linelen )
869 SWAP ( addr-linelen len-linelen )
872 2DROP ( restore stack )
873 BASE ! ( restore saved BASE )
877 CASE ----------------------------------------------------------------------
879 CASE...ENDCASE is how we do switch statements in FORTH. There is no generally
880 agreed syntax for this, so I've gone for the syntax mandated by the ISO standard
883 ( some value on the stack )
891 The CASE statement tests the value on the stack by comparing it for equality with
892 test1, test2, ..., testn and executes the matching piece of code within OF ... ENDOF.
893 If none of the test values match then the default case is executed. Inside the ... of
894 the default case, the value is still at the top of stack (it is implicitly DROP-ed
895 by ENDCASE). When ENDOF is executed it jumps after ENDCASE (ie. there is no "fall-through"
896 and no need for a break statement like in C).
898 The default case may be omitted. In fact the tests may also be omitted so that you
899 just have a default case, although this is probably not very useful.
901 An example (assuming that 'q', etc. are words which push the ASCII value of the letter
907 'q' OF 1 TO QUIT ENDOF
908 's' OF 1 TO SLEEP ENDOF
910 ." Sorry, I didn't understand key <" DUP EMIT ." >, try again." CR
913 (In some versions of FORTH, more advanced tests are supported, such as ranges, etc.
914 Other versions of FORTH need you to write OTHERWISE to indicate the default case.
915 As I said above, this FORTH tries to follow the ANS FORTH standard).
917 The implementation of CASE...ENDCASE is somewhat non-trivial. I'm following the
918 implementations from here:
919 http://www.uni-giessen.de/faq/archiv/forthfaq.case_endcase/msg00000.html
921 The general plan is to compile the code as a series of IF statements:
923 CASE (push 0 on the immediate-mode parameter stack)
924 test1 OF ... ENDOF test1 OVER = IF DROP ... ELSE
925 test2 OF ... ENDOF test2 OVER = IF DROP ... ELSE
926 testn OF ... ENDOF testn OVER = IF DROP ... ELSE
927 ... ( default case ) ...
928 ENDCASE DROP THEN [THEN [THEN ...]]
930 The CASE statement pushes 0 on the immediate-mode parameter stack, and that number
931 is used to count how many THEN statements we need when we get to ENDCASE so that each
932 IF has a matching THEN. The counting is done implicitly. If you recall from the
933 implementation above of IF, each IF pushes a code address on the immediate-mode stack,
934 and these addresses are non-zero, so by the time we get to ENDCASE the stack contains
935 some number of non-zeroes, followed by a zero. The number of non-zeroes is how many
936 times IF has been called, so how many times we need to match it with THEN.
938 This code uses [COMPILE] so that we compile calls to IF, ELSE, THEN instead of
939 actually calling them while we're compiling the words below.
941 As is the case with all of our control structures, they only work within word
942 definitions, not in immediate mode.
945 0 ( push 0 to mark the bottom of the stack )
949 ' OVER , ( compile OVER )
951 [COMPILE] IF ( compile IF )
952 ' DROP , ( compile DROP )
956 [COMPILE] ELSE ( ENDOF is the same as ELSE )
960 ' DROP , ( compile DROP )
962 ( keep compiling THEN until we get to our zero marker )
971 DECOMPILER ----------------------------------------------------------------------
973 CFA> is the opposite of >CFA. It takes a codeword and tries to find the matching
974 dictionary definition.
976 In this FORTH this is not so easy. In fact we have to search through the dictionary
977 because we don't have a convenient back-pointer (as is often the case in other versions
980 This word returns 0 if it doesn't find a match.
983 LATEST @ ( start at LATEST dictionary entry )
985 DUP 0<> ( while link pointer is not null )
987 DUP >CFA ( cfa curr curr-cfa )
988 2 PICK ( cfa curr curr-cfa cfa )
989 = IF ( found a match? )
990 NIP ( leave curr dictionary entry on the stack )
991 EXIT ( and return from the function )
993 @ ( follow link pointer back )
995 2DROP ( restore stack )
996 0 ( sorry, nothing found )
1000 SEE decompiles a FORTH word.
1002 We search for the dictionary entry of the word, then search again for the next
1003 word (effectively, the end of the compiled word). This results in two pointers:
1005 +---------+---+---+---+---+------------+------------+------------+------------+
1006 | LINK | 3 | T | E | N | DOCOL | LIT | 10 | EXIT |
1007 +---------+---+---+---+---+------------+------------+------------+------------+
1010 Start of word End of word
1012 With this information we can have a go at decompiling the word. We need to
1013 recognise "meta-words" like LIT, LITSTRING, BRANCH, etc. and treat those separately.
1016 WORD FIND ( find the dictionary entry to decompile )
1018 ( Now we search again, looking for the next word in the dictionary. This gives us
1019 the length of the word that we will be decompiling. (Well, mostly it does). )
1020 HERE @ ( address of the end of the last compiled word )
1021 LATEST @ ( word last curr )
1023 2 PICK ( word last curr word )
1024 OVER ( word last curr word curr )
1025 <> ( word last curr word<>curr? )
1026 WHILE ( word last curr )
1028 DUP @ ( word curr prev (which becomes: word last curr) )
1031 DROP ( at this point, the stack is: start-of-word end-of-word )
1032 SWAP ( end-of-word start-of-word )
1034 ( begin the definition with : NAME [IMMEDIATE] )
1035 ':' EMIT SPACE DUP ID. SPACE
1036 DUP ?IMMEDIATE IF ." IMMEDIATE " THEN
1038 >DFA ( get the data address, ie. points after DOCOL | end-of-word start-of-data )
1040 ( now we start decompiling until we hit the end of the word )
1044 DUP @ ( end start codeword )
1047 ' LIT OF ( is it LIT ? )
1048 4 + DUP @ ( get next word which is the integer constant )
1051 ' LITSTRING OF ( is it LITSTRING ? )
1052 [ CHAR S ] LITERAL EMIT '"' EMIT SPACE ( print S"<space> )
1053 4 + DUP @ ( get the length word )
1054 SWAP 4 + SWAP ( end start+4 length )
1055 2DUP TELL ( print the string )
1056 '"' EMIT SPACE ( finish the string with a final quote )
1057 + ALIGNED ( end start+4+len, aligned )
1058 4 - ( because we're about to add 4 below )
1060 ' 0BRANCH OF ( is it 0BRANCH ? )
1062 4 + DUP @ ( print the offset )
1066 ' BRANCH OF ( is it BRANCH ? )
1068 4 + DUP @ ( print the offset )
1072 ' ' OF ( is it ' (TICK) ? )
1073 [ CHAR ' ] LITERAL EMIT SPACE
1074 4 + DUP @ ( get the next codeword )
1075 CFA> ( and force it to be printed as a dictionary entry )
1078 ' EXIT OF ( is it EXIT? )
1079 ( We expect the last word to be EXIT, and if it is then we don't print it
1080 because EXIT is normally implied by ;. EXIT can also appear in the middle
1081 of words, and then it needs to be printed. )
1082 2DUP ( end start end start )
1083 4 + ( end start end start+4 )
1084 <> IF ( end start | we're not at the end )
1089 DUP ( in the default case we always need to DUP before using )
1090 CFA> ( look up the codeword to get the dictionary entry )
1091 ID. SPACE ( and print it )
1099 2DROP ( restore stack )
1103 DOES> ----------------------------------------------------------------------
1105 CREATE ... DOES> is a tricky construct allowing you to create words which create other words.
1106 For example CONSTANT (defined above) is a word which creates words, and it could have been
1109 : CONSTANT CREATE DOCOL , , DOES> @ ;
1111 Even explaining what DOES> is supposed to do is tricky. It's possible that the implementation
1112 is easier to understand than the explanation.
1114 If we look at the definition of CONSTANT here, and remember that when it is called the value
1115 of the constant is on the stack and the name follows. So first CREATE makes the header of a
1116 new word with the name. Secondly the codeword is set to DOCOL. Thirdly , (COMMA) takes the
1117 value off the stack and adds it to the definition. At this point (just before executing DOES>)
1118 the word looks like this:
1120 ________ CREATE _______ _ DOCOL ,_ ____ , ___
1122 +---------+---+---+---+---+------------+------------+
1123 | LINK | 3 | T | E | N | DOCOL | 10 |
1124 +---------+---+---+---+---+------------+------------+
1140 C STRINGS ----------------------------------------------------------------------
1142 FORTH strings are represented by a start address and length kept on the stack or in memory.
1144 Most FORTHs don't handle C strings, but we need them in order to access the process arguments
1145 and environment left on the stack by the Linux kernel.
1147 The main function we need is STRLEN which works out the length of a C string. DUP STRLEN is
1148 a common idiom which 'converts' a C string into a FORTH string. (For example, DUP STRLEN TELL
1152 ( STRLEN returns the length of a C string )
1153 : STRLEN ( str -- len )
1154 DUP ( save start address )
1156 DUP C@ 0<> ( zero byte found? )
1161 SWAP - ( calculate the length )
1165 STRNCMP compares two strings up to a length. As with C's strncmp it returns 0 if they
1166 are equal, or a number > 0 or < 0 indicating their order.
1168 : STRNCMP ( str1 str2 len -- eq? )
1172 ROT ( len str1 str2 )
1173 DUP C@ ( len str1 str2 char2 )
1174 2 PICK C@ ( len str1 str2 char2 char1 )
1175 OVER ( len str1 str2 char2 char1 char2 )
1176 - ( len str1 str2 char2 char1-char2 )
1178 ?DUP IF ( strings not the same at this position? )
1179 NIP ( len str1 str2 diff )
1180 ROT ( len diff str1 str2 )
1181 DROP DROP ( len diff )
1186 0= IF ( characters are equal, but is this the end of the C string? )
1192 1+ ( len str1 str2+1 )
1193 ROT ( str2+1 len str1 )
1194 1+ ROT ( str1+1 str2+1 len )
1195 1- ( str1+1 str2+1 len-1 )
1198 2DROP ( restore stack )
1203 THE ENVIRONMENT ----------------------------------------------------------------------
1205 Linux makes the process arguments and environment available to us on the stack.
1207 The top of stack pointer is saved by the early assembler code when we start up in the FORTH
1208 variable S0, and starting at this pointer we can read out the command line arguments and the
1211 Starting at S0, S0 itself points to argc (the number of command line arguments).
1213 S0+4 points to argv[0], S0+8 points to argv[1] etc up to argv[argc-1].
1215 argv[argc] is a NULL pointer.
1217 After that the stack contains environment variables, a set of pointers to strings of the
1218 form NAME=VALUE and on until we get to another NULL pointer.
1220 The first word that we define, ARGC, pushes the number of command line arguments (note that
1221 as with C argc, this includes the name of the command).
1228 n ARGV gets the nth command line argument.
1230 For example to print the command name you would do:
1233 : ARGV ( n -- str u )
1234 1+ CELLS S0 @ + ( get the address of argv[n] entry )
1235 @ ( get the address of the string )
1236 DUP STRLEN ( and get its length / turn it into a FORTH string )
1240 ENVIRON returns the address of the first environment string. The list of strings ends
1241 with a NULL pointer.
1243 For example to print the first string in the environment you could do:
1244 ENVIRON @ DUP STRLEN TELL
1246 : ENVIRON ( -- addr )
1247 ARGC ( number of command line parameters on the stack to skip )
1248 2 + ( skip command line count and NULL pointer after the command line args )
1249 CELLS ( convert to an offset )
1250 S0 @ + ( add to base stack address )
1254 ANS FORTH ----------------------------------------------------------------------
1256 From this point we're trying to fill in the missing parts of the ISO standard, commonly
1257 referred to as ANS FORTH.
1259 http://www.taygeta.com/forth/dpans.html
1260 http://www.taygeta.com/forth/dpansf.htm (list of words)
1262 ( BL pushes the ASCII character code of space on the stack. )
1265 ( C, writes a byte at the HERE pointer. )
1266 : C, HERE @ C! 1 HERE +! ;
1270 ( Finally print the welcome prompt. )
1271 ." JONESFORTH VERSION " VERSION . CR