Forthcompiler

From ScienceZero
Jump to: navigation, search

A simple Forth compiler

Definitions

Everything inside ( ) is a comment

When stack content is written on one line, the top of the stack is to the right
  bottom -> 1 2 3 <- top

Stack diagrams are comments that show what is taken from the stack and what is returned ot the stack
( items read from the stack -- items written on the stack )
Examples:
  ( n n -- n )
  This means that two numbers were read from the stack, then one number was written back.
  For example a simple addition reads two numbers and writes back the result.

  ( a b c -- c b a )
  Reading threee values from the stack and write them back in the opposite order.


Compiler stage 1

  1. Tokenize the source by splitting it at whitespace, turning a string into a series of words
  2. Build a dictionary that contains all words and their definitions

Words

Data processing:
  +             ( n n -- n )        ( : +  >r 0 r> - - ; )
  -             ( n n -- n )        ( fundamental )
  *             ( n n -- n )        ( : * 0 do over 1 and if rot dup >r -rot r> + endif rot 1 lsl rot 1 lsr rot over if again endif >r drop -rot drop drop ; ) 
  /             ( n n -- n )        ( ? )
  lsl           ( n n -- n )        ( : lsl for dup + next ; )
  lsr           ( n n -- n )        ( : lsr for 31 for dup 0x80000000 and swap 1 lsl swap if 1 + endif next 0x7fffffff and next ; )
  and           ( n n -- n )        ( fundamental )
  or            ( n n -- n )        ( : or over not and + ; )
  eor           ( n n -- n )        ( : eor over over or -rot and not and ; )
  not           ( n -- n )          ( : not >r -1 r> - ; )

Stack manipulation:
 drop           ( n -- )           ( : drop if endif ; )
 dup            ( n -- n n )       ( fundamental )
 swap           ( a b -- b a )     ( : swap dup >r >r dup r> eor dup >r eor r> r> eor ; )
 over           ( a b -- a b a )   ( : over >r dup r> swap ; ) 
 rot            ( a b c -- b c a ) ( : rot >r swap r> swap ; ) 
 -rot           ( a b c -- c a b ) ( : -rot swap >r swap r> ; )
 >r             ( n -- )           ( fundamental )
 r>             ( -- n )           ( fundamental )