The Factor parser follows a simple recursive-descent design. The parser reads successive tokens from the input; if the token identifies a number or an ordinary word, it is added to an accumulator vector. Otherwise if the token identifies a parsing word, the parsing word is executed immediately.
Parsing words are defined using the defining word:
Parsing words have uppercase names by convention. Here is the simplest possible parsing word; it prints a greeting at parse time:
SYNTAX: HELLO "Hello world" print ;
Parsing words must not pop or push items from the stack; however, they are permitted to access the accumulator vector supplied by the parser at the top of the stack. That is, parsing words must have stack effect ( accum -- accum )
, where accum
is the accumulator vector supplied by the parser.
Parsing words can read input, add word definitions to the dictionary, and do anything an ordinary word can.
Because of the stack restriction, parsing words cannot pass data to other words by leaving values on the stack; instead, use suffix!
to add the data to the parse tree so that it can be evaluated later.
Parsing words cannot be called from the same source file where they are defined, because new definitions are only compiled at the end of the source file. An attempt to use a parsing word in its own source file raises an error:
staging-violation ( word -- * )
Tools for implementing parsing words: Reading ahead Nested structure Defining words Parsing raw tokens Reflection support for vocabulary search path