CREATE ... DOES>

This construct is what makes Forth somewhat unique. It allows the compiler to be extended. In fact the assembler is written using this construct to define words that will create others of the same mould. Let us explain by example:

  H: CONSTANT CREATE ,-T DOES> @ ;

The H: tells the Host that this definition is for it and not the Target. All the words between H: and DOES> will be compiled into the Host as a Host definition. All the words after DOES> will be Target words defined in the Target. So what are we doing?

CONSTANT is the new name that we are adding to our compiler. CREATE will create a header in the Host when CONSTANT is run at Target compile time. The word ,-T will save any value on the Host stack into the next available space in the Target dictionary when CONSTANT is executed. DOES> will terminate the Host definition of CONSTANT and enter the compile state for the Target. DOES>starts by compiling into the Target a CALL DODOES. The CFA's of the words following DOES> will then be compiled into the Target dictionary. The address where this compilation takes place is patched into the definition of CONSTANT in the Host.

So when we invoke CONSTANT in our program, the address of the code compiled by DOES> will be compiled into the Target, followed by the value on the Host stack. So when the resulting constant is run in the Target it runs CALL DODOES. This leaves the address of the value that was on the Host stack at compile time on the Target stack. The code compiled after DOES> is then run. This results in the fetching of the compiled value from the code space onto the Target stack.

The word CONSTANT will now create as many more words as we wish, all with the same resultant run-time action, but each with it's own result. Those who know of the Object Oriented Programming style, OOPs, may recognise this construct. Forth has been doing this for nearly 20 years. For more insight into this you may wish to refer to the Appendix.

Note: The example shown here for a constant is not that used by TLM. It is only a simple demonstration of the CREATE...DOES> structure.

Contents