Forth Interpreter

You may work in pairs for this assignment.

In this assignment, you will write an interpreter for a subset of the Forth programming language. A good tutorial can be found here, although your interpreter will not support all of the features discussed in the tutorial.

Here is the lexical specification and grammar for the subset of Forth you are interpreting:

(define the-lexical-spec
  '((whitespace (whitespace) skip)
    (comment ("\\" (arbno (not #\newline))) skip)
    (comment ("(" (arbno (not #\))) ")") skip)
    (number (digit (arbno digit)) number)
    (identifier
      ((or letter "." "!" "@" "$" "%" "^" "&" "*" "+" "-" "=" "/" "?" "<" ">")
       (arbno (or letter digit "." "!" "@" "$" "%" "^" "&" "*" "+" "-" "=" "/" "?" "<" ">")))
      symbol)))

(define the-grammar
  '((program ((arbno statement) "\n") a-program)
    (statement (number) num)
    (statement (identifier) word)
    (statement ("begin" (arbno statement) "while" (arbno statement) "repeat") loop-stmt)
    (statement ("if" (arbno statement) "else" (arbno statement) "then") if-stmt)
    (statement (":" identifier (arbno statement) ";") def)
    (statement ("+") add-prim)
    (statement ("-") sub-prim)
    (statement ("*") mult-prim)
    (statement ("/") div-prim)
    (statement (".") print-prim)
    (statement (">") gt-prim)
    (statement (">=") gte-prim)
    (statement ("cr") cr-prim)
    (statement ("drop") drop-prim)
    (statement ("dup") dup-prim)
    (statement ("over") over-prim)
    (statement ("swap") swap-prim)
    ))
Here is an example of the interpreter at work:
--> 2 3 +
ok
--> .
5 ok
--> 2 3 4 + * .
14 ok
--> 1 if 2 else 3 then .
2 ok
--> : square dup * ;
(square) ok
--> 4 square .
16 ok
--> 10 1 begin over over >= while dup . 1 + repeat
1 2 3 4 5 6 7 8 9 10 ok
--> : fact dup 2 > if dup 1 - fact * else then ;
(fact square) ok
--> 5 fact .
120 ok
Note the following changes from Forth as described in the tutorial: Turn in your completed interpreter, including the lexical specification and grammar above.
Last modified: Thu Apr 8 11:09:45 PDT 2004