Saturday, May 17, 2014

The Dragon-Free Internals of Forth

In which our protagonist is amazed that the core structure of Forth is so simple even he can understand it.

Forth was not invented by a bunch of eggheads at a university, but by a guy who needed to get real work done. Chuck Moore started programming in the 50's at the Smithsonian Astrophysical Observatory with code that computed ephemerides, orbital elements and satellite station positions. After graduate school at Stanford, he worked as freelance programmer, using a bunch of routines and concepts he had developed on the way over and over again:

Working in Fortran, Algol, Jovial, PL/I and various assemblers, he continued to use his interpreter as much as possible, literally carrying around his card deck and recoding it as necessary.

This "interpreter" would evolve into the language now called Forth. Moore rewrote it for various computers systems, and even later, hardware remained a moving target:

Throughout the 70's, as he implemented Forth on 18 different CPUs (...), he invariably wrote for each his own assembler, his own disk and terminal drivers, even his own multiply and divide subroutines (on machines that required them, as many did).

Keeping stuff simple not only was a philosophy, but a necessity.

So while the internals of boffin languages can be so complex and scary they make people think of dragons, the core of Forth is so simple it seems almost snarky:

The flow chart of a Forth system. From Lost at C? Forth might be the answer by Tom Napier and Eric Krieg.

The only non-trivial concept here are the "immediate" words: As the name says, those are executed right way -- "immediately" -- even if we're in compile mode. LITERAL for instance is a compile-only, immediate word that makes sure the word will later push a number on the stack.

So "compiling" in Forth means adding new words -- what other languages call "functions" -- to the dictionary. In its simplest form, this does not involve math, complex algorithms, or dragons (though of course we have nothing against dragons, because dragons are awesome). In other words, it is something even we can do.

The major question then becomes how to design the dictionary. In the next entry, we'll look at that more closely, because Tali Forth does something weird.