Compiling Programmatically
Semantics
Words can have different behaviour depending on whether we are in compilation mode or interpretation mode. The technical term for "behaviour" is semantics.
- The default interpretation semantics of a word is to run its code section.
- The default compilation semantics of a word is to append its code section to the enclosing new word being defined.
- An immediate word breaks the default compilation semantics. The word's code section is run instead of being compiled into the enclosing word.
- Some words may break both default semantics. Some words have no interpretation semantics.
Compiling
In some situations, you will have to compile code into a new word without expecting it to have the default compilation semantics. There are two words to help you with this.
Word | Action |
---|---|
[COMPILE] |
Takes the following word and compiles the word's code section into the enclosing word, regardless of that word's compilation semantics. |
COMPILE, |
Takes a given XT and compiles its code section into the enclosing word. |
Examples
Example 1: hi "Hi!" . ; : bb [compile] hi "bye!" . ; bb Hi! bye! ok see bb [0] HI [1] Literal(bye!) [2] . okExample 2
: aa [ ' dup compile, ] ; see aa [0] DUP okExample 3
COMPILE,becomes extremely useful when you only have an XT but you want to compile it into your word.
:> "I am just an XT." . ; \ puts an XT on the stack ok : bb ( xt -- ) "What's this?" . [ compile, ] ; ok bb What's this? I am just an XT. ok
Quiz
Question 1
In Example 1, how would it change if you usedPOSTPONEinstead of
[COMPILE]? Explain and check your answer using
SEE.
The word
postponepushes the XT of
HIto the stack and runs
COMPILE,, which takes the
HIXT on the stack and compiles it into the enclosing word. However the program is not running within a word definition, hence there is an error.
Question 2
What are the compilation semantics ofHIin Example 1? Is using
[COMPILE]or
POSTPONEof any value? Explain and check your answer using
SEE.
Since it is not an immediate word, the compilation semantics of the word
HIis to append its code section to the enclosing new word being defined. Hence the word
[compile]is redundant.
Question 3
IfHIwere immediate, what would your answer to Question 2 be? Explain and check your answer with
SEE.
If
HIwere immediate, its code section will be run instead of being compiled into the enclosing word.
[COMPILE]or
POSTPONEshould then be used.
Question 4
What doesAAin Example 2 do? Why did we have to use the switch mode operators?
AAcompiles the code of
DUPinto its definition. It is the same as
: aa dup ;because
DUPis not immediate. The switch mode operators is needed because
COMPILE,is not immediate.
Question 5
Write[COMPILE]in terms of
COMPILE,and other words you know except for
POSTPONEor
`.
: [COMPILE] ' compile, ; immediate