Wednesday, 14 March 2012

Itsy-Forth: the Outer Interpreter of a 1K Tiny Compiler

Itsy Forth is a tiny indirect-threaded compiler for a subset of the Forth programming language. The compiler contains an interactive interpreter which allows the programmer to define new words (subroutines), execute them and even extend the language.

Each word has an entry in the Forth dictionary. New words are defined with : and end with ;. The following example defines a new word inc which calls two words, 1 and +:

: inc 1 + ;

Outer Interpreter

Itsy was developed top-down, first implementing the interpreter. interpret takes the next word from the input buffer and searches for it in the dictionary. If the word isn't found, Itsy attempts to convert it to a number. In compile mode, Itsy will add the word or number to the current definition. Otherwise the word will be executed.

: interpret
begin
    #tib @ >in @ =
    if
        tib 50 accept #tib ! 0 >in !
    then
    32 word find dup
    if
        state @ =
        if
            ,
        else
            execute
        then
    else
        dup rot count >number
        if
            state @
            if
                last @ dup @ last ! dp !
            then
            abort
        then
        drop drop state @
        if
            ['] lit , ,
        then
    then
again
;

The Itsy interpreter uses 23 different words, 5 variables (state, >in, #tib, dp, last) and a constant (tib). Note the variables dp and last are non-standard. dp points to the first free cell in the data area. last points to the last word to be compiled.

Next we'll define the dictionary structure and implement the inner interpreter. In the meantime I'd love to hear any comments on the code so far :-)