Forth Macro

Like LispMacros, Forth distinguishes compile-time vs. run-time semantics. Words which are flagged IMMEDIATE run at the time words are compiled, rather than get compiled into the definition themselves. Forth control structures (IF-THEN, BEGIN-WHILE-REPEAT) are IMMEDATE words which compile branch instructions into the definition, using the stack at compile-time to backpatch the branch addresses. One can extend the language with additional control structures in this way.

This is also used by words like create and ." and ['] to parse the input stream for strings and symbols, allowing Forth to use syntaxes other than postfix. This can be handy for creating DomainSpecificLanguages (such as infix mathematical expressions or state diagrams).

One can execute a fragment of a definition at compile-time by temporarily turning off the compiler. For example:
 : slow ( n -- ) prepare  big hairy computation producing another number  compute ;
does the hairy computation each time slow is invoked. It will run faster if written
 : fast ( n -- ) prepare [ big hairy computation producing another number ] literal compute ;
where [ turns the compiler off, executing the hairy computation at compile-time until the matching ]. The resulting number is compiled inline by literal, which at run-time will be passed to compute. This is equivalent to setting a const variable to an expression in C vs. embedding the expression directly into the body of a C function.

On the other hand, one can also write specialized defining words which work like :. One writes the word to be IMMEDIATE, and uses POSTPONE word to compile words into the current definition. An example of this is on DotProductInManyProgrammingLanguages.

Some Forth variants allow a normally compiled colon definition to be flagged to have its body inserted inline when encountered, rather than to compile a call to the word. QuartusForth uses inline after a colon definition, others replace : with macro:.


ForthMacros are RealMacros.


ForthLanguage, ForthVsLisp

EditText of this page (last edited April 22, 2008) or FindPage with title or text search