Shadow words
Posted: Mon Jul 07, 2025 9:20 pm
Here is a way to create temporary, or shadow, words in Forth. The temporary words can not be used in normal Forth words. They can be used to help build normal Forth words and data structures and removed when no longer needed because they are defined higher up in memory.
A helper word to exchange memory contents is needed.
Code: Select all
: EXCHANGE ( ADR1 ADR2 -- )
2DUP @ >R @ SWAP! R> SWAP! ;
A variable to hold an alternate DP is needed as well as a new VOCABULARY .
Code: Select all
FORTH DEFINITIONS
VARIABLE SHADOWLANDS
FREE 2/ PAD + SHADOWLANDS !
VOCABULARY TEMPORARY
The word to start temporary definitions is written so it will only execute once before it is reset.
Code: Select all
: (TEMPS) ( -- )
['] EXIT (IS) RECURSE
DP SHADOWLANDS EXCHANGE ;
The word to stop creating temporary definitions is written so it will only execute if the word to start temporary definitions has been executed.
Code: Select all
: (NORMAL) ( -- )
['] (TEMPS) >BODY @ ['] EXIT =
0EXIT
DP SHADOWLANDS EXCHANGE
['] LIT (IS) (TEMPS) ;
And finally the two wrapper words to make sure the temporary definitions are defined in the TEMPORARY vocabulary.
Code: Select all
: TEMPS ( -- )
(TEMPS) TEMPORARY DEFINITIONS ;
: NORMAL ( -- )
(NORMAL) FORTH DEFINITIONS ;
In case anyone was wondering, the functionality of (TEMPS) and (NORMAL) were factored out for use in something else I'm working on.
Here is a trivial example of using a temporary definition:
Code: Select all
// TEST RUN
TEMPS
: RAMP
256 0
DO
255 I - C,
LOOP ;
NORMAL
CREATE DESCEND
TEMPORARY // INCLUDE TEMPORARY
// IN SEARCH ORDER
RAMP
: NOTHING ;
FORGET NOTHING
A nothing word is created at the end. When NOTHING is forgotten, all the words in the TEMPORARY vocabulary will be forgotten, without forgetting DESCEND , because they are all above HERE .