mdhender

super secret hq

The Forth Interpreter Loop

In the Forth Programmer’s Handbook, Conklin and Rather outline the basics of the Forth interpreter:

while true
  get next lexeme
  lookup lexeme in dictionary
  if word is found
      execute word
      if there is stack underflow
          display "stack empty"
          reset stacks and intepreter
  elsif lexeme is numeric
      convert to binary
      push result onto stack
  else
      display "unknown word"
      reset stacks and intepreter
end-while

For False Forth, I modified their logic to be script-friendly.

while more input
  get next lexeme
  if lexeme is numeric
      convert to binary
      push result onto stack
  else
      lookup lexeme in dictionary
      if word is found
          execute word
          if there is stack underflow
              display "stack empty"
              exit intepreter
      else
          display "unknown word"
          exit intepreter
end-while

Moving the check for numeric data prevents numbers from being defined as words, which supports the principle of least surprise. Most people don’t expect “2” to do anything other than represent two of something.

Exiting the interpreter on error instead of resetting it supports the principle of “bail early, bail often.” This assumes that the user wants to know about issues as soon as possible so that they can be fixed. Likely true for a script.

Comments