This is gforth.info, produced by makeinfo version 7.2 from gforth.texi.

This manual is for Gforth (version 0.7.9_20260223, February 23, 2026), a
fast and portable implementation of the Standard Forth language.  It
serves as reference manual, but it also contains an introduction to
Forth and a Forth tutorial.

   Authors: Bernd Paysan, Anton Ertl, Gerald Wodni, Neal Crook, David
Kuehling, Jens Wilke Copyright © 1995, 1996, 1997, 1998, 2000, 2003,
2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024,2025 Free Software
Foundation, Inc.

     Permission is granted to copy, distribute and/or modify this
     document under the terms of the GNU Free Documentation License,
     Version 1.1 or any later version published by the Free Software
     Foundation; with no Invariant Sections, with the Front-Cover texts
     being "A GNU Manual," and with the Back-Cover Texts as in (a)
     below.  A copy of the license is included in the section entitled
     "GNU Free Documentation License."

     (a) The FSF's Back-Cover Text is: "You have freedom to copy and
     modify this GNU Manual, like GNU software.  Copies published by the
     Free Software Foundation raise funds for GNU development."
INFO-DIR-SECTION Software development
START-INFO-DIR-ENTRY
* Gforth: (gforth).             A fast interpreter for the Forth language.
END-INFO-DIR-ENTRY


File: gforth.info,  Node: Arbitrary control structures,  Next: Calls and returns,  Prev: General control structures with CASE,  Up: Control Structures

6.10.6 Arbitrary control structures
-----------------------------------

Standard Forth permits and supports using control structures in a
non-nested way.  Information about incomplete control structures is
stored on the control-flow stack.  This stack may be implemented on the
Forth data stack, and this is what we have done in Gforth.

   An orig entry represents an unresolved forward branch, a dest entry
represents a backward branch target.  A few words are the basis for
building any control structure possible (except control structures that
need storage, like calls, coroutines, and backtracking).

‘IF’ ( compilation - orig ; run-time f -  ) core
   At run-time, if f=0, execution continues after the ‘THEN’ (or ‘ELSE’)
that consumes the orig, otherwise right after the ‘IF’ (*note
Selection::).

‘AHEAD’ ( compilation - orig ; run-time -  ) tools-ext
   At run-time, execution continues after the ‘THEN’ that consumes the
orig.

‘THEN’ ( compilation orig - ; run-time -  ) core
   The ‘IF’, ‘AHEAD’, ‘ELSE’ or ‘WHILE’ that pushed orig jumps right
after the ‘THEN’ (*note Selection::).

‘BEGIN’ ( compilation - dest ; run-time -  ) core
   The ‘UNTIL’, ‘AGAIN’ or ‘REPEAT’ that consumes the dest jumps right
behind the ‘BEGIN’ (*note General Loops::).

‘UNTIL’ ( compilation dest - ; run-time f -  ) core
   At run-time, if f=0, execution continues after the ‘BEGIN’ that
produced dest, otherwise right after the ‘UNTIL’ (*note General
Loops::).

‘AGAIN’ ( compilation dest - ; run-time -  ) core-ext
   At run-time, execution continues after the ‘BEGIN’ that produced the
dest (*note General Loops::).

‘CS-PICK’ ( dest0/orig0 dest1/orig1 ... destu/origu u - ... dest0/orig0  ) tools-ext "c-s-pick"

‘CS-ROLL’ ( destu/origu .. dest0/orig0 u - .. dest0/orig0 destu/origu  ) tools-ext "c-s-roll"

‘CS-DROP’ ( dest/orig -  ) gforth-1.0

   The Standard words ‘cs-pick’ and ‘cs-roll’ allow you to manipulate
the control-flow stack in a portable way.  Without them, you would need
to know how many stack items are occupied by a control-flow entry (Many
systems use one cell.  In Gforth they currently take four cells, but
this may change in the future).

   When using ‘cs-pick’ and ‘cs-drop’ on an orig, you need to use one
‘cs-drop’ for every ‘cs-pick’ (and vice versa) of a given orig, because
the orig must be resolved by ‘then’ exactly once.

   Some standard control structure words are built from these words:

‘ELSE’ ( compilation orig1 - orig2 ; run-time -  ) core
   At run-time, execution continues after the ‘THEN’ that consumes the
orig; the ‘IF’, ‘AHEAD’, ‘ELSE’ or ‘WHILE’ that pushed orig1 jumps right
after the ‘ELSE’.  (*note Selection::).

‘WHILE’ ( compilation dest - orig dest ; run-time f -  ) core
   At run-time, if f=0, execution continues after the ‘REPEAT’ (or
‘THEN’ or ‘ELSE’) that consumes the orig, otherwise right after the
‘WHILE’ (*note General Loops::).

‘REPEAT’ ( compilation orig dest - ; run-time -  ) core
   At run-time, execution continues after the ‘BEGIN’ that produced the
dest; the ‘WHILE’, ‘IF’, ‘AHEAD’ or ‘ELSE’ that pushed orig jumps right
after the ‘REPEAT’.  (*note General Loops::).

Gforth adds some more control-structure words:

‘ENDIF’ ( compilation orig - ; run-time -  ) gforth-0.2
   Same as ‘THEN’.

‘?dup-IF’ ( compilation - orig ; run-time n - n|  ) gforth-0.2 "question-dupe-if"
   This is the preferred alternative to the idiom "‘?DUP IF’", since it
can be better handled by tools like stack checkers.  Besides, it's
faster.

‘?DUP-0=-IF’ ( compilation - orig ; run-time n - n|  ) gforth-0.2 "question-dupe-zero-equals-if"


File: gforth.info,  Node: Calls and returns,  Next: Exception Handling,  Prev: Arbitrary control structures,  Up: Control Structures

6.10.7 Calls and returns
------------------------

A definition can be called simply be writing the name of the definition
to be called.  Normally a definition is invisible during its own
definition.  If you want to write a directly recursive definition, you
can use ‘recursive’ to make the current definition visible, or ‘recurse’
to call the current definition directly.

‘recursive’ ( compilation - ; run-time -  ) gforth-0.2
   Make the current definition visible, enabling it to call itself
recursively.

‘recurse’ ( ... - ...  ) core
   Alias to the current definition.

For examples of using these words, *Note Recursion Tutorial::.

   Programming style note:

   I prefer using ‘recursive’ to ‘recurse’, because calling the
definition by name is more descriptive (if the name is well-chosen) than
the somewhat cryptic ‘recurse’.  E.g., in a quicksort implementation, it
is much better to read (and think) "now sort the partitions" than to
read "now do a recursive call".

   For mutual recursion, Gforth offers the defining word ‘forward’.  You
can use it to create a forward reference which is resolved
automatically, and does not incur additional costs like the indirection
of ‘Defer’.  However, these forward definitions only work for colon
definitions.  Here's a usage example:

     forward foo

     : bar ( ... -- ... )
      ... foo ... ;

     : foo ( ... -- ... ) \ resolves the forward definition
      ... bar ... ;

   The words used for forward definitions are:

‘forward’ ( "name" -  ) gforth-1.0
   Defines a forward reference to a colon definition.  Defining a colon
definition with the same name in the same wordlist resolves the forward
references.  Use ‘.unresolved’ to check whether any forwards are
unresolved.

‘.unresolved’ ( -  ) gforth-1.0 "dot-unresolved"
   print all unresolved forward references

   In Standard Forth, you use ‘Defer’red words for mutual recursion,
like this:

     Defer foo

     : bar ( ... -- ... )
      ... foo ... ;

     :noname ( ... -- ... )
      ... bar ... ;
     IS foo

   Deferred words are discussed in more detail in *note Deferred
Words::.

   The current definition returns control to the calling definition when
the end of the definition is reached or ‘EXIT’ is encountered.

‘EXIT’ ( compilation - ; run-time nest-sys -  ) core
   Return to the calling definition; usually used as a way of forcing an
early return from a definition.  Before ‘EXIT’ing you must clean up the
return stack and ‘UNLOOP’ any outstanding ‘?DO’...‘LOOP’s.

‘?EXIT’ ( -  ) gforth-0.2 "question-exit"
   Return to the calling definition if f is true.


File: gforth.info,  Node: Exception Handling,  Prev: Calls and returns,  Up: Control Structures

6.10.8 Exception Handling
-------------------------

If a word detects an error condition that it cannot handle, it can
‘throw’ an exception.  In the simplest case, this will terminate your
program, and report an appropriate error.

‘throw’ ( y1 .. ym nerror - y1 .. ym / z1 .. zn nerror  ) exception
   If nerror is 0, drop it and continue.  Otherwise, transfer control to
the next dynamically enclosing exception handler, reset the stacks
accordingly, and push nerror.

‘fast-throw’ ( ... nerror - ... nerror ) gforth-experimental "fast-throw"
   Lightweight ‘throw’ variant: only for non-zero nerrors, and does not
store a backtrace or deal with missing ‘catch’.

   ‘Throw’ consumes a cell-sized error number on the stack.  There are
some predefined error numbers in Standard Forth (see ‘errors.fs’).  In
Gforth (and most other systems) you can use the iors produced by various
words as error numbers (e.g., a typical use of ‘allocate’ is ‘allocate
throw’).  Gforth also provides the word ‘exception’ to define your own
error numbers (with decent error reporting); a Standard Forth version of
this word (but without the error messages) is available in
‘compat/except.fs’.  And finally, you can use your own error numbers
(anything outside the range -4095..0), but won't get nice error
messages, only numbers.  For example, try:

     -10 throw                    \ Standard defined
     -267 throw                   \ system defined
     s" my error" exception throw \ user defined
     7 throw                      \ arbitrary number

‘exception’ ( addr u - n  ) gforth-0.2
   N is a previously unused ‘throw’ value in the range (-4095...-256).
Consecutive calls to ‘exception’ return consecutive decreasing numbers.
Gforth uses the string ADDR U as an error message.

   There are also cases where you have a word (typically modeled after
POSIX' ‘strerror’) for converting an error number into a string.  You
can use the following word to get these strings into Gforth's error
handling:

‘exceptions’ ( xt n1 - n2  ) gforth-1.0
   Xt ‘( +n -- c-addr u )’ converts an error number in the range 0<=n<n1
into an error message.  ‘Exceptions’ reserves n1 error codes in the
range n2-n1<n3<=n2.  When (at some later point in time) the Gforth error
code n3 in that range is thrown, it pushes n2-n3 and then executes xt to
produce the error message.

   As an example, if the ‘errno’ errors (and the conversion using
‘strerror’) was not already directly supported by Gforth, you could tie
‘strerror’ in as follows:

     ' strerror 1536 exceptions constant errno-base
     : errno-ior ( -- n )
     \ n is the Gforth ior corresponding to the value in errno, so
     \ we have to convert between the ranges here.
     \ ERRNO is not a Gforth word, so you  would have to use the
     \ C interface to access it.
       errno errno-base over - swap 0<> and ;

   When you call a C function that can set ‘errno’ (with the C
interface, *note C Interface::), you can use one of the following words
for converting that error into a ‘throw’:

‘?errno-throw’ ( f -  ) gforth-1.0 "question-errno-throw"
   If f<>0, throws an error code based on the value of ‘errno’.

‘?ior’ ( x -  ) gforth-1.0 "question-i-o-r"
   If f=-1, throws an error code based on the value of ‘errno’.

   Which of these you should use depends on how the C function indicates
that an error has happened.  When the system then catches a throw
performed by one of these words, it produces the proper error message
(such as "Permission denied").

   Note that the errno numbers are not directly used as throw codes
(because the Forth standard specifies that positive throw codes must not
be system-defined), but maps them into a different number range.

   A common idiom to ‘THROW’ a specific err# if a flag is true is this:

     ( flag ) 0<> err# and throw

   Your program can provide exception handlers to catch exceptions.  An
exception handler can be used to correct the problem, or to clean up
some data structures and just throw the exception to the next exception
handler.  Note that ‘throw’ jumps to the dynamically innermost exception
handler.  The system's exception handler is outermost, and just prints
an error and restarts command-line interpretation (or, in batch mode
(i.e., while processing the shell command line), leaves Gforth).

   The Standard Forth way to catch exceptions is ‘catch’:

‘catch’ ( x1 .. xn xt - y1 .. ym 0 / z1 .. zn error  ) exception
   ‘Executes’ xt.  If execution returns normally, ‘catch’ pushes 0 on
the stack.  If execution returns through ‘throw’, all the stacks are
reset to the depth on entry to ‘catch’, and the TOS (the xt position) is
replaced with the throw code.

‘catch-nobt’ ( x1 .. xn xt - y1 .. ym 0 / z1 .. zn error  ) gforth-experimental
   perform a catch that does not record backtraces on errors

‘nothrow’ ( -  ) gforth-0.7
   Use this (or the standard sequence ‘['] false catch 2drop’) after a
‘catch’ or ‘endtry’ that does not rethrow; this ensures that the next
‘throw’ will record a backtrace.

   The most common use of exception handlers is to clean up the state
when an error happens.  E.g.,

     base @ >r hex \ actually the HEX should be inside foo to protect
                   \ against exceptions between HEX and CATCH
     ['] foo catch ( nerror|0 )
     r> base !
     ( nerror|0 ) throw \ pass it on

   A use of ‘catch’ for handling the error ‘myerror’ might look like
this:

     ['] foo catch
     CASE
       myerror OF ... ( do something about it ) nothrow ENDOF
       dup throw \ default: pass other errors on, do nothing on non-errors
     ENDCASE

   Having to wrap the code into a separate word is often cumbersome,
therefore Gforth provides an alternative syntax:

     TRY
       code1
       IFERROR
         code2
       THEN
       code3
     ENDTRY

   This performs code1.  If code1 completes normally, execution
continues with code3.  If there is an exception in code1 or before
‘endtry’, the stacks are reset to the depth during ‘try’, the throw
value is pushed on the data stack, and execution continues at code2, and
finally falls through to code3.

‘try’ ( compilation  - orig ; run-time  - R:sys1  ) gforth-0.5
   Start an exception-catching region.

‘endtry’ ( compilation  - ; run-time  R:sys1 -  ) gforth-0.5
   End an exception-catching region.

‘iferror’ ( compilation  orig1 - orig2 ; run-time  -  ) gforth-0.7
   Starts the exception handling code (executed if there is an exception
between ‘try’ and ‘endtry’).  This part has to be finished with ‘then’.

   If you don't need code2, you can write ‘restore’ instead of ‘iferror
then’:

     TRY
       code1
     RESTORE
       code3
     ENDTRY

   The cleanup example from above in this syntax:

     base @ { oldbase }
     TRY
       hex foo \ now the hex is placed correctly
       0       \ value for throw
     RESTORE
       oldbase base !
     ENDTRY
     throw

   An additional advantage of this variant is that an exception between
‘restore’ and ‘endtry’ (e.g., from the user pressing ‘Ctrl-C’) restarts
the execution of the code after ‘restore’, so the base will be restored
under all circumstances.

   However, you have to ensure that this code does not cause an
exception itself, otherwise the ‘iferror’/‘restore’ code will loop.
Moreover, you should also make sure that the stack contents needed by
the ‘iferror’/‘restore’ code exist everywhere between ‘try’ and
‘endtry’; in our example this is achieved by putting the data in a local
before the ‘try’ (you cannot use the return stack because the exception
frame (sys1) is in the way there).

   This kind of usage corresponds to Lisp's ‘unwind-protect’.

   If you do not want this exception-restarting behaviour, you achieve
this as follows:

     TRY
       code1
     ENDTRY-IFERROR
       code2
     THEN

   If there is an exception in code1, then code2 is executed, otherwise
execution continues behind the ‘then’ (or in a possible ‘else’ branch).
This corresponds to the construct

     TRY
       code1
     RECOVER
       code2
     ENDTRY

   in Gforth before version 0.7.  So you can directly replace
‘recover’-using code; however, we recommend that you check if it would
not be better to use one of the other ‘try’ variants while you are at
it.

   To ease the transition, Gforth provides two compatibility files:
‘endtry-iferror.fs’ provides the ‘try ... endtry-iferror ... then’
syntax (but not ‘iferror’ or ‘restore’) for old systems;
‘recover-endtry.fs’ provides the ‘try ... recover ... endtry’ syntax on
new systems, so you can use that file as a stopgap to run old programs.
Both files work on any Gforth (they just do nothing if the system
already has the syntax it implements), so you can unconditionally
‘require’ one of these files, even if you use a mix old and new Gforths.

‘restore’ ( compilation  orig1 - ; run-time  -  ) gforth-0.7
   Starts restoring code, that is executed if there is an exception, and
if there is no exception.

‘endtry-iferror’ ( compilation  orig1 - orig2 ; run-time  R:sys1 -  ) gforth-0.7
   End an exception-catching region while starting exception-handling
code outside that region (executed if there is an exception between
‘try’ and ‘endtry-iferror’).  This part has to be finished with ‘then’
(or ‘else’...‘then’).

   Here's the error handling example:

     TRY
       foo
     ENDTRY-IFERROR
       CASE
         myerror OF ... ( do something about it ) nothrow ENDOF
         throw \ pass other errors on
       ENDCASE
     THEN

   Programming style note:

   As usual, you should ensure that the stack depth is statically known
at the end: either after the ‘throw’ for passing on errors, or after the
‘ENDTRY’ (or, if you use ‘catch’, after the end of the selection
construct for handling the error).

   There are two alternatives to ‘throw’: ‘Abort"’ is conditional and
you can provide an error message.  ‘Abort’ just produces an "Aborted"
error.

   The problem with these words is that exception handlers cannot
differentiate between different ‘abort"’s; they just look like ‘-2
throw’ to them (the error message cannot be accessed by standard
programs).  Similarly, ‘abort’ looks like ‘-1 throw’ to exception
handlers.

‘ABORT"’ ( compilation 'ccc"' - ; run-time ... f -  ) core,exception-ext "abort-quote"
   If any bit of f is non-zero, perform the function of ‘-2 throw’,
displaying the string ccc if there is no exception frame on the
exception stack.

‘abort’ ( ?? - ??  ) core,exception-ext
   ‘-1 throw’.

   For problems that are not that awful that you need to abort
execution, you can just display a warning.  The variable ‘warnings’
allows to tune how many warnings you see.

‘WARNING"’ ( compilation 'ccc"' - ; run-time f -  ) gforth-1.0 "warning-quote"
   if f is non-zero, display the string ccc as warning message.

‘warnings’ ( - addr  ) gforth-0.2
   Set warnings level to
‘0’
     turns warnings off
‘-1’
     turns normal warnings on
‘-2’
     turns beginner warnings on
‘-3’
     turns pedantic warnings on
‘-4’
     turns warnings into errors (including beginner warnings)


File: gforth.info,  Node: Defining Words,  Next: Structures,  Prev: Control Structures,  Up: Words

6.11 Defining Words
===================

Defining words are used to extend Forth by creating new entries in the
dictionary.

* Menu:

* CREATE::
* Variables::                   Variables and user variables
* Constants::
* Values::                      Initialised variables
* Colon Definitions::
* Inline Definitions::
* Anonymous Definitions::       Definitions without names
* Quotations::
* Supplying names::             Passing definition names as strings
* User-defined Defining Words::
* Deferred Words::              Allow forward references
* Synonyms::


File: gforth.info,  Node: CREATE,  Next: Variables,  Prev: Defining Words,  Up: Defining Words

6.11.1 ‘CREATE’
---------------

The simplest defining word is ‘CREATE’, used like this:

     CREATE new-word1

   ‘CREATE’ is a parsing word, i.e., it takes an argument from the input
stream (‘new-word1’ in our example).  It generates a dictionary entry
for ‘new-word1’.  When ‘new-word1’ is executed, all that it does is
leave an address on the stack.  The address represents the value of the
dictionary pointer (‘HERE’) at the time that ‘new-word1’ was defined.
Therefore, ‘CREATE’ is a way of associating a name with the address of a
region of memory.

‘Create’ ( "name" -  ) core

   Note that Standard Forth guarantees only for ‘create’ that its body
is contiguous with the following dictionary allocations (e.g., ‘allot’,
*note Dictionary allocation::).  Also, in Standard Forth only ‘create’d
words can be modified with ‘does>’ (*note User-defined Defining
Words::).  And in Standard Forth ‘>body’ can only be applied to
‘create’d words.

   By extending this example to reserve some memory in data space, we
end up with something like a variable.  Here are two different ways to
do it:

     CREATE new-word2 1 cells allot  \ reserve 1 cell without initializing it
     CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)

   The variable can be examined and modified using ‘@’ ("fetch") and ‘!’
("store") like this:

     new-word2 @ .      \ get address, fetch from it and display
     1234 new-word2 !   \ new value, get address, store to it

   A similar mechanism can be used to create arrays.  For example, an
80-character text buffer:

     CREATE text-buf 80 allot \ uninitialized

     text-buf 0 + c@ \ the 1st character (offset 0)
     text-buf 3 + c@ \ the 4th character (offset 3)

   You can build arbitrarily complex data structures by allocating
appropriate areas of memory.  For further discussions of this, and to
learn about some Gforth tools that make it easier, *Note Structures::.


File: gforth.info,  Node: Variables,  Next: Constants,  Prev: CREATE,  Up: Defining Words

6.11.2 Variables
----------------

The previous section showed how a sequence of commands could be used to
generate a variable.  As a final refinement, the whole code sequence can
be wrapped up in a defining word, making it easier to create new
variables:

     : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
     : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;

     myvariableX foo \ variable foo starts off with an unknown value
     myvariable0 joe \ whilst joe is initialised to 0

     45 3 * foo !   \ set foo to 135
     1234 joe !     \ set joe to 1234
     3 joe +!       \ increment joe by 3.. to 1237

   Not surprisingly, there is no need to define ‘myvariableX’, since
Forth already has a definition ‘Variable’.  Standard Forth does not
guarantee that a ‘Variable’ is initialised when it is created (i.e., it
may behave like ‘myvariableX’).  In contrast, Gforth's ‘Variable’
initialises the variable to 0 (i.e., it behaves exactly like
‘myvariable0’).  Forth also provides ‘2Variable’ and ‘fvariable’ for
double and floating-point variables, respectively - they are initialised
to #0.  and 0e in Gforth.  If you use a ‘Variable’ to store a boolean,
you can use ‘on’ and ‘off’ to toggle its state (*note Boolean Flags::).

‘Variable’ ( "name" -  ) core
   Define name and reserve a cell at addr.
name execution: ‘( -- addr )’.

‘AVariable’ ( "name" -  ) gforth-0.2
   Works like ‘variable’, but (when used in cross-compiled code) tells
the cross-compiler that the cell stored in the variable is an address.

‘2Variable’ ( "name" -  ) double "two-variable"
   Define name and reserve two cells starting at addr.
name execution: ‘( -- addr )’.

‘fvariable’ ( "name" -  ) floating "f-variable"
   Define name and reserve a float at f-addr.
name execution: ‘( -- f-addr )’.

   Finally, for buffers of arbitrary length there is

‘buffer:’ ( u "name" -  ) core-ext "buffer-colon"
   Define name and reserve u bytes starting at addr.  Gforth initializes
the reserved bytes to 0, but the standard does not guarantee this.
name execution: ‘( -- addr )’.


File: gforth.info,  Node: Constants,  Next: Values,  Prev: Variables,  Up: Defining Words

6.11.3 Constants
----------------

‘Constant’ allows you to declare a fixed value and refer to it by name.
For example:

     12 Constant INCHES-PER-FOOT \ is integer appropriate
     2.54e fconstant CM-PER-INCH

   A ‘Variable’ can be both read and written, so its run-time behaviour
is to supply an address through which its current value can be
manipulated.  In contrast, the value of a ‘Constant’ cannot be changed
once it has been declared(1) so it's not necessary to supply the address
- it is more efficient to return the value of the constant directly.
That's exactly what happens; the run-time effect of a constant is to put
its value on the top of the stack (You can find one way of implementing
‘Constant’ in *note User-defined Defining Words::).

   Forth also provides ‘2Constant’ and ‘fconstant’ for defining double
and floating-point constants, respectively.

‘Constant’ ( w "name" -  ) core
   Define name.
name execution: ( - w )

‘AConstant’ ( addr "name" -  ) gforth-0.2
   Like ‘constant’, but defines a constant for an address (this only
makes a difference in the cross-compiler).

‘2Constant’ ( w1 w2 "name" -  ) double "two-constant"
   Define name.
name execution: ( - w1 w2 )

‘fconstant’ ( r "name" -  ) floating "f-constant"
   Define name.
name execution: ( - r )

   ---------- Footnotes ----------

   (1) Well, often it can be - but not in a Standard, portable way.
It's safer to use a ‘Value’ (read on).


File: gforth.info,  Node: Values,  Next: Colon Definitions,  Prev: Constants,  Up: Defining Words

6.11.4 Values
-------------

A ‘Value’ behaves like a ‘Constant’, but it can be changed.  ‘TO’ and
‘+TO’ are parsing words that change a value.  Alternatively, you can
change a value ‘v’ by writing ‘->v’ (equivalent to ‘TO v’) or ‘+>v’
(equivalent to ‘+TO v’).

   Here are some examples:

     12 value apples \ Define APPLES with an initial value of 12
     34 to apples    \ Change the value of APPLES. TO is a parsing word
     34 ->apples     \ Change the value of APPLES. Non-standard usage
     1  +to apples   \ Increment APPLES.  Non-standard usage.
     1  +>apples     \ Increment APPLES.  Non-standard usage.
     apples          \ puts 36 on the top of the stack.

‘Value’ ( w "name" -  ) core-ext
   Define name with the initial value w
name execution: ( - w2 ) push the current value of name.
‘to name’ run-time: ( w3 - ) change the value of name to w3.
‘+to name’ run-time: ( n|u - ) increment the value of name by n|u

‘AValue’ ( w "name" -  ) gforth-0.6
   Like ‘value’, but defines a value for an address (this only makes a
difference in the cross-compiler).

‘2Value’ ( w1 w2 "name" -  ) double-ext "two-value"
   Define name with the initial value w
name execution: ( - w3 w4 ) push the current value of name.
‘to name’ run-time: ( w5 w6 - ) change the value of name to w5 w6.
‘+to name’ run-time: ( d|ud - ) increment the value of name by d|ud

‘fvalue’ ( r "name" -  ) floating-ext "f-value"
   Define name with the initial value r
name execution: ( - r2 ) push the current value of name.
‘to name’ run-time: ( r3 - ) change the value of name to r3.
‘+to name’ run-time: ( r4 - ) increment the value of name by r4

‘TO’ ( value ... "name" -  ) core-ext
   Name is a value-flavoured word, ...  is optional additional
addressing information, e.g., for a value-flavoured field.  At run-time,
perform the to name semantics: change name (with the same additional
addressing information) to push value.  The type of value depends on the
type of name (see the defining word for name for the actual type).  An
alternative syntax is to write ‘->name’.

‘+TO’ ( value ... "name" -  ) gforth-1.0 "plus-TO"
   Name is a value-flavoured word, ...  is optional additional
addressing information, e.g., for a value-flavoured field.  At run-time,
perform the +to name semantics: if name (with the same additional
addressing information) pushed value1 before, change it to push value2,
the sum of the value1 and value.  The type of value depends on the type
of name (see the defining word for name for the actual type).  An
alternative syntax is to write ‘+>name’.

   Words that produce their value on execution and that can be changed
with ‘to’ or ‘+to’ are called value-flavoured (in contrast to the
variable-flavoured words that produce their address on execution).  They
are defined be some of the words listed above, but also by some locals
definitions words (*note Locals definition words::) and some field
definition words (*note Value-Flavoured and Defer-Flavoured Fields::).

   Sometimes you want to take the address of a value-flavoured word.
Because this has some potential performance disadvantages, Gforth asks
you to be explicit about it, and define the word as addressable.  Once
you have done that, you can get the address with ‘addr’.  The following
example is equivalent to the one above:

     12 addressable: value apples
     34 addr apples ! \ Change the value of APPLES.  ADDR is a parsing word
     1 +to apples     \ Increment APPLES
     addr apples @    \ puts 35 on the top of the stack.

‘addressable:’ ( -  ) gforth-experimental "addressable-colon"
   ‘Addressable:’ should be used in front of a defining word for a
value-flavoured word (e.g., ‘value’).  It allows to use ‘addr’ on the
word defined by that defining word.

‘addr’ ( interpretation "name" ... - addr; compilation "name" - ; run-time ... - addr  ) gforth-1.0
   Name is an ‘addressable:’ value-flavoured word, ...  is optional
additional addressing information, e.g., for a value-flavoured field.
Addr is the address where the value of name (taking the additional
address information into account) is stored.

   For now using ‘addr’ on a non-‘addressable:’ value results in a
warning.  In the future, when we change the code generation in a way
that results in potentially faster code for non-‘addressable:’ values,
but where the use of ‘addr’ on such values could produce unexpected
results, such usage will result in an error.


File: gforth.info,  Node: Colon Definitions,  Next: Inline Definitions,  Prev: Values,  Up: Defining Words

6.11.5 Colon Definitions
------------------------

     : name ( ... -- ... )
         word1 word2 word3 ;

Creates a word called ‘name’ that, upon execution, executes ‘word1 word2
word3’.  ‘name’ is a “(colon) definition”.

   The explanation above is somewhat superficial.  For simple examples
of colon definitions see *note Your first definition::.  For an in-depth
discussion of some of the issues involved, *Note Interpretation and
Compilation Semantics::.

‘:’ ( "name" - colon-sys  ) core "colon"

‘;’ ( compilation colon-sys - ; run-time nest-sys -  ) core "semicolon"


File: gforth.info,  Node: Inline Definitions,  Next: Anonymous Definitions,  Prev: Colon Definitions,  Up: Defining Words

6.11.6 Inline Definitions
-------------------------

We plan to to perform automatic inlining eventually, but for now you can
perform inlining with

‘inline:’ ( "name" - inline:-sys  ) gforth-experimental "inline-colon"
   Start inline colon definition.  The code between ‘inline:’ and
‘;inline’ has to compile (not perform) the code to be inlined, but the
resulting definition name is a colon definition that performs the
inlined code.  Note that the compiling code must have the stack effect
‘( -- )’, otherwise you will get an error when Gforth tries to create
the colon definition for name.

‘;inline’ ( inline:-sys -  ) gforth-experimental "semi-inline"
   end inline definition started with ‘inline:’

   As an example, you can define an inlined word and use it with

     inline: my2dup ( a b -- a b a b )
         ]] over over [[ ;inline

     #1. my2dup d. d.
     : foo my2dup ;
     #1. foo d. d.
     see foo

   Inline words are related to macros (*note Macros::); the difference
is that a macro has immediate compilation semantics while an
‘inline:’-defined word has default compilation semantics; this means
that you normally use a macro only inside a colon definition, while you
can use an ‘inline:’ word also interpretively.  But that also means that
you can do some things with macros that you cannot do as an ‘inline:’
word.  E.g.,

     \ Doesn't work:
     \   inline: endif ]] then [[ ;inline
     \ Instead, write a macro:
     : endif ]] then [[ ; immediate

   Conversely, for words that would be fine as non-immediate colon
definitions, define them as non-immediate colon definitions or (if
utmost performance is required) as ‘inline:’ words; don't define them as
macros, because then you cannot properly use them interpretively:

     : another2dup ]] over over [[ ; immediate
     \ Doesn't work:
     \   #1. another2dup d. d.

   You may wonder why you have to write compiling code between ‘inline:’
and ‘;inline’.  That's because the implementation of an inline word like
‘my2dup’ above works similar to:

     : compile-my2dup ( xt -- )
         drop ]] over over [[ ;

     : my2dup [ 0 compile-my2dup ] ;
     ' compile-my2dup set-optimizer

   The ‘DROP’ and ‘0’ are there because ‘compile-my2dup’ is the
implementation of ‘compile,’ for ‘my2dup’, and ‘compile,’ expects an xt
(*note User-defined compile-comma::).


File: gforth.info,  Node: Anonymous Definitions,  Next: Quotations,  Prev: Inline Definitions,  Up: Defining Words

6.11.7 Anonymous Definitions
----------------------------

Sometimes you want to define an “anonymous word”; a word without a name.
You can do this with:

‘:noname’ ( - xt colon-sys  ) core-ext "colon-no-name"

   This leaves the execution token for the word on the stack after the
closing ‘;’.  Here's an example in which a deferred word is initialised
with an ‘xt’ from an anonymous colon definition:

     Defer deferred
     :noname ( ... -- ... )
       ... ;
     IS deferred

Gforth provides an alternative way of doing this, using two separate
words:

‘noname’ ( -  ) gforth-0.2
   The next defined word will be anonymous.  The defining word will
leave the input stream alone.  The xt of the defined word will be given
by ‘latestxt’, its nt by ‘latestnt’ (*note Name token::).

‘latestxt’ ( - xt  ) gforth-0.6
   xt is the execution token of the most recent word defined in the
current section.

The previous example can be rewritten using ‘noname’ and ‘latestxt’:

     Defer deferred
     noname : ( ... -- ... )
       ... ;
     latestxt IS deferred

‘noname’ works with any defining word, not just ‘:’.

   ‘latestxt’ also works when the last word was not defined as ‘noname’.
It also has the useful property that it is valid as soon as the header
for a definition has been built.  Thus:

     latestxt . : foo [ latestxt . ] ; ' foo .

prints 3 numbers; the last two are the same.


File: gforth.info,  Node: Quotations,  Next: Supplying names,  Prev: Anonymous Definitions,  Up: Defining Words

6.11.8 Quotations
-----------------

A quotation is an anonymous colon definition inside another colon
definition.  Quotations are useful when dealing with words that consume
an execution token, like ‘catch’ or ‘outfile-execute’.  E.g.  consider
the following example of using ‘outfile-execute’ (*note Redirection::):

     : some-warning ( n -- )
         cr ." warning# " . ;

     : print-some-warning ( n -- )
         ['] some-warning stderr outfile-execute ;

   Here we defined ‘some-warning’ as a helper word whose xt we could
pass to outfile-execute.  Instead, we can use a quotation to define such
a word anonymously inside ‘print-some-warning’:

     : print-some-warning ( n -- )
       [: cr ." warning# " . ;] stderr outfile-execute ;

   The quotation is bounded by ‘[:’ and ‘;]’.  It produces an execution
token at run-time.

‘[:’ ( compile-time: - quotation-sys flag colon-sys  ) gforth-1.0 "bracket-colon"
   Starts a quotation in the next section.

‘;]’ ( compile-time: quotation-sys - ; run-time: - xt  ) gforth-1.0 "semi-bracket"
   Ends a quotation (represented by xt) and switch to the previous
section.  ‘Latestxt’ and ‘latestnt’ refer to the last word in the
current section, i.e., not to the quotation.


File: gforth.info,  Node: Supplying names,  Next: User-defined Defining Words,  Prev: Quotations,  Up: Defining Words

6.11.9 Supplying the name of a defined word
-------------------------------------------

By default, a defining word takes the name for the defined word from the
input stream.  Sometimes you want to supply the name from a string.  You
can do this with:

‘nextname’ ( c-addr u -  ) gforth-0.2
   The next defined word will have the name C-ADDR U; the defining word
will leave the input stream alone.

   For example:

     s" foo" nextname create

is equivalent to:

     create foo

‘nextname’ works with any defining word.


File: gforth.info,  Node: User-defined Defining Words,  Next: Deferred Words,  Prev: Supplying names,  Up: Defining Words

6.11.10 User-defined Defining Words
-----------------------------------

You can define new defining words in terms of any existing defining
word, but ‘:’ and ‘create’...‘does>’/‘set-does>’ are particularly
flexible, whereas the children of, e.g., ‘constant’ are all just
constants.

* Menu:

* User-defined defining words with colon definitions::
* User-defined defining words using CREATE::
* CREATE..DOES> applications::
* CREATE..DOES> details::
* Advanced does> usage example::
* Words with user-defined TO etc.::
* User-defined compile-comma::
* Creating from a prototype::
* Making a word current::
* Const-does>::


File: gforth.info,  Node: User-defined defining words with colon definitions,  Next: User-defined defining words using CREATE,  Prev: User-defined Defining Words,  Up: User-defined Defining Words

6.11.10.1 User-defined defining words with colon definitions
............................................................

Colon definitions are very flexible, so you can write a defining word
that defines a new colon definition at its run-time.  Here is an
example:

     : myconstant {: w -- :}
       : w postpone literal postpone ; ;

   When defining ‘5 myconstant five’, ‘myconstant’ first stashes w in a
local (for reasons explained later), then calls ‘:’, which starts the
definition of ‘five’.  Then it uses ‘postpone literal’ (*note Compiling
words::) to compile w (i.e., 5) into this colon definition, and then
‘postpone ;’ to end it.  You can look at the result with ‘see five’:

     : five  #5 ;

   Can't we just leave w on the data stack for consumption by ‘postpone
literal’?  No: ‘:’ pushes a colon-sys on the data stack, so we have to
first move w elsewhere so we can later access it.  In this example, we
used a local variable, but moving w on the return stack and back would
also have been an option.

   A more convenient, but Gforth-specific way to write ‘myconstant’ is:

     : myconstant {: w -- :}
       : ]] w ; [[ ;

   The features used in this code are explained elsewhere (*note
Macros::).

   A disadvantage of this approach is that it consumes more memory than
the approach of the next section: E.g, here are the memory costs of
defining ‘five’ with the various implementations:

     builtin  : does> set-does> opt
        48   64   48     48      48  bytes header+threaded code
         0   23    0      0       0  bytes native code
        16   16   32     16      16  compiled threaded code
         4   23   34      7       4  compiled native code

   Builtin refers to using ‘constant’, : to using ‘myconstant’ (defined
above), does> to using ‘myconstant2’, set-does> to using ‘myconstant3’
(both from *note User-defined defining words using CREATE::), and opt to
using ‘myconstant4’ (*note User-defined compile-comma::).

   The lines where the label starts with "bytes" report the space
consumption of defining the word ‘five’ itself; the native code is for
gforth-fast on AMD64 (native code for the gforth engine is larger).

   The lines where the label starts with "compiled" report the space
consumption (also in bytes) for the invocation of ‘five’ in the word ‘:
foo five * ;’.  The native code can be bigger or smaller in other
contexts.


File: gforth.info,  Node: User-defined defining words using CREATE,  Next: CREATE..DOES> applications,  Prev: User-defined defining words with colon definitions,  Up: User-defined Defining Words

6.11.10.2 User-defined defining words using ‘create’
....................................................

If you want the words defined with your defining words to behave
differently from words defined with standard defining words, you can
write your defining word like this:

     : def-word ( "name" -- )
         CREATE code1
     DOES> ( ... -- ... )
         code2 ;

     def-word name

   This fragment defines a “defining word” ‘def-word’ and then executes
it.  When ‘def-word’ executes, it ‘CREATE’s a new word name, and
executes the code code1.  The code code2 is not executed at this time.
The word name is sometimes called a “child” of ‘def-word’.

   When you execute name, the address of the body of name is pushed on
the data stack and code2 is executed.  The address of the body of name
is the address ‘HERE’ returns immediately after the ‘CREATE’, i.e., the
address a ‘create’d word returns by default).

   You can understand the behaviour of ‘def-word’ and ‘name’ by
considering the following definitions:
     : def-word1 ( "name" -- )
         CREATE code1 ;

     : action1 ( ... -- ... )
         code2 ;

     def-word1 name1

Using ‘name1 action1’ is equivalent to using ‘name’.

   You can use ‘def-word’ to define a set of child words that behave
similarly; they all have a common run-time behaviour determined by
code2.  Typically, the code1 sequence builds a data area in the body of
the child word.  The structure of the data is common to all children of
‘def-word’, but the data values are specific - and private - to each
child word.

   As an example, here's how you can define ‘myconstant2’ with ‘does>’:

     : myconstant2 ( w "name" -- )
         create ,
     does> ( -- w )
         @ ;

   Here ‘create’ defines a word name, then ‘,’ stores w in name's data
area, then the ‘does>’ changes name's behaviour and returns to the
caller of ‘myconstant2’: When name is invoked, the new behaviour first
pushes the address of the data area (as before), but then also performs
the code after the ‘does>’.  In the present case, this code fetches the
value of the constant from the data area.

   The stack effect besides the ‘does’ reflects the stack effect of name
execution, not the stack effect of the code after the ‘does>’ (this is
not common practice yet but we still recommend it).

   ‘Does>’ splits the definition into two subdefinitions and has a
number of disadvantages.  Alternatively, Gforth allows you to provide
the second part as an execution token by using ‘set-does>’.  So the
general scheme is:

     : def-word ( "name" -- ; name execution: ... -- ... )
         create code1
         xt-code2 set-does>
         code3 ;

   The difference from the definition using ‘does>’ is that on name
execution, after pushing the data address, xt-code2 is ‘execute’d,
rather than calling the code after the ‘does>’.  This also allows
putting code3 in def-word; this is particularly relevant when you want
to also use ‘set-optimizer’ (*note User-defined compile-comma::) on the
defined word, because ‘does>’/‘set-does>’ calls ‘set-optimizer’ itself,
so using ‘set-optimizer’ before ‘does>’/‘set-does>’ has no effect.

   Here xt-code2 could be the xt of an existing word, or it could be
provided through a quotation (*note Quotations::).

   Another advantage of ‘set-does>’ is that the result is a little more
efficient if the execution token passed to it is that of a primitive.
This advantages comes to fruition in:

     : myconstant3 ( w "name" -- ; name execution: -- w )
         create ,
         ['] @ set-does> ;

   During name execution, after pushing the body address of name, ‘@’ is
executed.

   The efficiency advantage shows up in the comparisons of compiled code
size (*note User-defined defining words with colon definitions::); the
execution time also benefits.


File: gforth.info,  Node: CREATE..DOES> applications,  Next: CREATE..DOES> details,  Prev: User-defined defining words using CREATE,  Up: User-defined Defining Words

6.11.10.3 Applications of ‘CREATE..DOES>’
.........................................

You may wonder how to use this feature.  Here are some usage patterns:

   When you see a sequence of code occurring several times, and you can
identify a meaning, you will factor it out as a colon definition.  When
you see similar colon definitions, you can factor them using
‘CREATE..DOES>’.  E.g., an assembler usually defines several words that
look very similar:
     : ori, ( reg-target reg-source n -- )
         0 asm-reg-reg-imm ;
     : andi, ( reg-target reg-source n -- )
         1 asm-reg-reg-imm ;

This could be factored with:
     : reg-reg-imm ( op-code -- )
         CREATE ,
     DOES> ( reg-target reg-source n -- )
         @ asm-reg-reg-imm ;

     0 reg-reg-imm ori,
     1 reg-reg-imm andi,

   Another view of ‘CREATE..DOES>’ is to consider it as a crude way to
supply a part of the parameters for a word (known as “currying” in the
functional language community).  E.g., ‘+’ needs two parameters.
Creating versions of ‘+’ with one parameter fixed can be done like this:

     : curry+ ( n1 "name" -- )
         CREATE ,
     DOES> ( n2 -- n1+n2 )
         @ + ;

      3 curry+ 3+
     -2 curry+ 2-


File: gforth.info,  Node: CREATE..DOES> details,  Next: Advanced does> usage example,  Prev: CREATE..DOES> applications,  Up: User-defined Defining Words

6.11.10.4 The gory details of ‘CREATE..DOES>’
.............................................

‘DOES>’ ( compilation colon-sys1 - colon-sys2  ) core "does"
   Changes the current word such that it pushes its body address and
then calls the code behind the ‘does>’.  Also changes the ‘compile,’
implementation accordingly.  Call ‘set-optimizer’ afterwards if you want
a more efficient implementation.

   You can put the ‘does>’-part in a different definition than the
‘create’ part.  This allows us to, e.g., select among different
‘DOES>’-parts:
     : does1
     DOES> ( ... -- ... )
         code1 ;

     : does2
     DOES> ( ... -- ... )
         code2 ;

     : def-word ( ... -- ... )
         create ...
         IF
            does1
         ELSE
            does2
         THEN ;

   In this example, the selection of whether to use ‘does1’ or ‘does2’
is made at definition-time, i.e., at the time when the child word is
‘CREATE’d.

   Note that the property of ‘does>’ to end the definition makes it
necessary to introduce extra definitions ‘does1’ and ‘does2’.  You can
avoid that with ‘set-does>’:

     : def-word ( ... -- ... )
         create ...
         IF
            [: code1 ;] set-does>
         ELSE
            [: code2 ;] set-does>
         THEN ;

‘set-does>’ ( xt -  ) gforth-1.0 "set-does-to"
   Changes the current word such that it pushes its body address and
then executes xt.  Also changes the ‘compile,’ implementation
accordingly.  Call ‘set-optimizer’ afterwards if you want a more
efficient implementation.

   In a standard program you can apply a ‘DOES>’-part only if the last
word was defined with ‘CREATE’.  In Gforth, the ‘DOES>’-part will
override the behaviour of the last word defined in any case.  In a
standard program, you can use ‘DOES>’ only in a colon definition.  In
Gforth, you can also use it in interpretation state, in a kind of
one-shot mode; for example:
     CREATE name ( ... -- ... )
       initialization
     DOES>
       code ;

is equivalent to the standard:
     :noname
     DOES>
         code ;
     CREATE name EXECUTE ( ... -- ... )
         initialization

   Gforth also supports quotations in interpreted code, and quotations
save and restore the current definition, so you can also write the
example above also as:

     CREATE name ( ... -- ... )
       initialization
     [: code ;] set-does>

‘>body’ ( xt - a-addr  ) core "to-body"
   a-addr is the address of the body (aka parameter field or data field)
of the word represented by xt

   You can access the data area of a ‘create’d word with ‘>body’,
including words where the behaviour has been changed with
‘does>’/‘set-does>’.  So if you know that ‘five’ has been defined with,
e.g., ‘myconstant3’ (*note User-defined defining words using CREATE::),
you can change its value with

     7 ' five >body !

   and performing ‘five’ will then push 7.  By contrast, for words
defined with ‘myconstant’ (defined using ‘:’, *note User-defined
defining words with colon definitions::) you cannot change the value in
this way.

   However, if a word uses ‘set-optimizer’ (*note User-defined
compile-comma::) for a more efficient implementation of the compiled
code for a word, in many cases the compiled code does not read data from
the body of this word, and in that case changing the data by using
‘>body’ will not have the desired effect.  So looking at the source code
of a defining word and seeing ‘create’ is not enough to conclude that
you can change the data and it will affect all existing uses.  An
example of that is ‘myconstant4’ (*note User-defined compile-comma::).

   So it's a good idea to document whether the intention behind a
defining word using ‘create’ is that it's data should be changeable
through ‘>body’.


File: gforth.info,  Node: Advanced does> usage example,  Next: Words with user-defined TO etc.,  Prev: CREATE..DOES> details,  Up: User-defined Defining Words

6.11.10.5 Advanced does> usage example
......................................

The MIPS disassembler (‘arch/mips/disasm.fs’) contains many words for
disassembling instructions, that follow a very repetitive scheme:

     :noname DISASM-OPERANDS s" INST-NAME" type ;
     ENTRY-NUM cells TABLE + !

   Of course, this inspires the idea to factor out the commonalities to
allow a definition like

     DISASM-OPERANDS ENTRY-NUM TABLE define-inst INST-NAME

   The parameters DISASM-OPERANDS and TABLE are usually correlated.
Moreover, before I wrote the disassembler, there already existed code
that defines instructions like this:

     ENTRY-NUM INST-FORMAT INST-NAME

   This code comes from the assembler and resides in
‘arch/mips/insts.fs’.

   So I had to define the INST-FORMAT words that performed the scheme
above when executed.  At first I chose to use run-time code-generation:

     : INST-FORMAT ( entry-num "name" -- ; compiled code: addr w -- )
       :noname Postpone DISASM-OPERANDS
       name Postpone sliteral Postpone type Postpone ;
       swap cells TABLE + ! ;

   Note that this supplies the other two parameters of the scheme above.

   An alternative would have been to write this using ‘create’/‘does>’:

     : INST-FORMAT ( entry-num "name" -- )
       here name string, ( entry-num c-addr ) \ parse and save "name"
       noname create , ( entry-num )
       latestxt swap cells TABLE + !
     does> ( addr w -- )
       \ disassemble instruction w at addr
       @ >r
       DISASM-OPERANDS
       r> count type ;

   Somehow the first solution is simpler, mainly because it's simpler to
shift a string from definition-time to use-time with ‘sliteral’ than
with ‘string,’ and friends.

   I wrote a lot of words following this scheme and soon thought about
factoring out the commonalities among them.  Note that this uses a
two-level defining word, i.e., a word that defines ordinary defining
words.

   This time a solution involving ‘postpone’ and friends seemed more
difficult (try it as an exercise), so I decided to use a
‘create’/‘does>’ word; since I was already at it, I also used
‘create’/‘does>’ for the lower level (try using ‘postpone’ etc.  as an
exercise), resulting in the following definition:

     : define-format ( disasm-xt table-xt -- )
         \ define an instruction format that uses disasm-xt for
         \ disassembling and enters the defined instructions into table
         \ table-xt
         create 2,
     does> ( u "inst" -- )
         \ defines an anonymous word for disassembling instruction inst,
         \ and enters it as u-th entry into table-xt
         2@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
         noname create 2,      \ define anonymous word
         execute latestxt swap ! \ enter xt of defined word into table-xt
     does> ( addr w -- )
         \ disassemble instruction w at addr
         2@ >r ( addr w disasm-xt R: c-addr )
         execute ( R: c-addr ) \ disassemble operands
         r> count type ; \ print name

   Note that the tables here (in contrast to above) do the ‘cells +’ by
themselves (that's why you have to pass an xt).  This word is used in
the following way:

     ' DISASM-OPERANDS ' TABLE define-format INST-FORMAT

   As shown above, the defined instruction format is then used like
this:

     ENTRY-NUM INST-FORMAT INST-NAME

   In terms of currying, this kind of two-level defining word provides
the parameters in three stages: first DISASM-OPERANDS and TABLE, then
ENTRY-NUM and INST-NAME, finally ‘addr w’, i.e., the instruction to be
disassembled.

   Of course this did not quite fit all the instruction format names
used in ‘insts.fs’, so I had to define a few wrappers that conditioned
the parameters into the right form.

   If you have trouble following this section, don't worry.  First, this
is involved and takes time (and probably some playing around) to
understand; second, this is the first two-level ‘create’/‘does>’ word I
have written in seventeen years of Forth; and if I did not have
‘insts.fs’ to start with, I may well have elected to use just a
one-level defining word (with some repeating of parameters when using
the defining word).  So it is not necessary to understand this, but it
may improve your understanding of Forth.


File: gforth.info,  Node: Words with user-defined TO etc.,  Next: User-defined compile-comma,  Prev: Advanced does> usage example,  Up: User-defined Defining Words

6.11.10.6 Words with user-defined ‘to’ etc.
...........................................

When you define a word _x_, you can set its execution semantics with
‘set-does>’ (*note User-defined defining words using CREATE::) or
‘set-execute’ (*note Header methods::).  But you can also change the
semantics of

     to _x_        \ aka ->_x_
     +to _x_       \ aka +>_x_
     action-of _x_ \ aka `_x_ defer@
     is _x_        \ aka `_x_ defer!
     addr _x_

   This is all achieved through a common mechanism described in this
section.  As an example, let's define ‘dvalue’ (it behaves in Gforth
exactly like ‘2value’, *note Values::).  The code is as follows,
explained below:

     : d+! ( d addr -- )
       dup >r 2@ d+ r> 2! ;

     \                  to +to action-of is  addr
     to-table: d!-table 2! d+!    n/a    n/a [noop]

     ' >body d!-table to-class: dvalue-to

     : dvalue ( d "name" -- )
       create 2,
       ['] 2@ set-does>
       ['] dvalue-to set-to ;

     #5. dvalue x
     #2. +to x
     x d. \ prints 7

   First, we define the support word ‘d+!’.

   Next, we define ‘d!-table’, a table of the various ‘to’-like actions.

   For actions that are not supported, we put ‘n/a’ in the table, and
when you try to use, e.g., ‘is x’, exception -21 (unsupported operation)
is thrown.

   For the ‘to’ and ‘+to’ actions, we have to provide words with the
stack effect ‘( d addr -- )’, where addr is the address where the data
of the value-flavoured word is stored.  For ‘addr’ (only supported for
‘addressable:’ words), we have to provide a word with the stack effect
‘( addr1 -- addr2 )’; in the usual case, both addresses are the same,
and we can just provide ‘[noop]’.  For the general case, see the
description of ‘to-table:’ below.

   Next, the defining word ‘to-class:’ combines the ‘d!-table’ with the
address-computation word ‘>body’, resulting in the definition of
‘dvalue-to’.(1)  The address-computation word has the stack effect ‘(
... xt -- addr )’.  When invoking ‘+to x’, the xt of ‘x’ is pushed and
then the address-computation word (‘>body’) is called; the result is the
address that is then passed on to ‘d+!’ (from ‘d!-table’).

   For ‘dvalue’ that's all, but in other cases, e.g., value-flavoured
fields (*note Value-Flavoured and Defer-Flavoured Fields::), additional
stack items can be consumed by the address-computation word, and those
have to be provided by the user as stack-top values when invoking, e.g.,
‘to field’.

   Next, we have the definition of ‘dvalue’, which is a straightforward
‘create’...‘set-does>’ word that also tells name with ‘set-to’ how it
should behave for ‘to’ etc.

   Finally, we use ‘dvalue’ to define ‘x’ and use it.  The line using
‘+to’ exercises the ‘set-to’ mechanism:

     #2. +to x

   performs

     #2. ' x >body d+!

   The ‘>body’ is the address-computation word given in the definition
of ‘dvalue-to’, and the ‘d+!’ is the ‘+to’ entry in ‘d!-table’.

   These are the words mentioned above:

‘to-table:’ ( "name" "to-word" "+to-word" "addr-word" "action-of-word" "is-word" -  ) gforth-experimental "to-table-colon"
   Create a table name with entries for ‘TO’, ‘+TO’, ‘ACTION-OF’, ‘IS’,
and ‘ADDR’.  The words for these entries are called with xt on the
stack, where xt belongs to the word behind ‘to’ (or ‘+to’ etc.).  Use
‘n/a’ to mark unsupported operations.  Default entries operations can be
left away at the end of the line; the default is for the ‘addr’ entry is
‘[noop]’ while the default for the other entries is ‘n/a’.

   The stack effects of the actions are:

   • For the ‘to’ and ‘+to’ action: ‘( value addr -- )’, where value has
     the appropriate type (e.g., a double-cell in our ‘dvalue’ example).

   • For the ‘action-of’ action: ‘( addr -- xt )’

   • For the ‘is’ action: ‘( xt addr -- )’

   • For the ‘addr’ action: ‘( addr1 -- addr2 )’

   The addr input parameter in all these cases is the address of the
memory where the value of the xt is stored.

   The default mechanism means that ‘d!-table’ could instead have been
defined as follows:

     \                  to +to action-of is  addr
     to-table: d!-table 2! d+!

‘n/a’ ( -  ) gforth-experimental "not-available"
   This word can be ticked, but throws an "Operation not supported"
exception on interpretation and compilation.  Use this for methods etc.
that aren't supported.

‘to-class:’ ( xt table "name" -  ) gforth-experimental "to-class-colon"
   Create a to-class implementation name, where XT ‘( ... xt -- addr )’
computes the address to access the data, and TABLE (created with
‘to-table:’) contains the words for accessing it.

‘>uvalue’ ( xt - addr  ) gforth-internal "to-uvalue"
   Xt is the xt of a word x defined with ‘uvalue’; addr is the address
of the data of x in the current task.  This word is useful for building,
e.g., ‘uvalue’.  Do not use it to circumvent that you cannot get the
address of a uvalue with ‘addr’; in the future Gforth may perform
optimizations that assume that uvalues can only be accessed through
their name.

‘set-to’ ( to-xt -  ) gforth-1.0
   Changes the implementations of the to-class methods of the most
recently defined word to come from the to-class that has the xt to-xt.

   ---------- Footnotes ----------

   (1) The same to-table is often combined with different address
computation words (e.g., for global values, user values, value-flavoured
fields and locals), that's why the definition of the to-table is
separated from the definition of the to-class.


File: gforth.info,  Node: User-defined compile-comma,  Next: Creating from a prototype,  Prev: Words with user-defined TO etc.,  Up: User-defined Defining Words

6.11.10.7 User-defined ‘compile,’
.................................

You can also change the implementation of ‘compile,’ for a word, with

‘set-optimizer’ ( xt -  ) gforth-1.0
   Changes the current word such that ‘compile,’ing it executes xt (with
the same stack contents as passed to ‘compile,’).  Note that ‘compile,’
must be consistent with ‘execute’, so you must use ‘set-optimizer’ only
to install a more efficient implementation of the same behaviour.

‘opt:’ ( compilation - colon-sys2 ; run-time - nest-sys  ) gforth-1.0 "opt-colon"
   Starts a nameless colon definition; when it is complete, this colon
definition will become the ‘compile,’ implementation of the latest word
(before the ‘opt:’).

   Note that the resulting ‘compile,’ must still be equivalent to
‘postpone literal postpone execute’, so ‘set-optimizer’ is useful for
efficiency, not for changing the behaviour.  There is nothing that
prevents you from shooting yourself in the foot, however.  You can check
whether your uses of ‘set-optimizer’ are correct by comparing the
results when you use it with the results you get when you disable your
uses by first defining

     : set-optimizer drop ;

   As an example of the use of ‘set-optimizer’, we can enhance
‘myconstant3’ as follows.

     : myconstant4 ( n "name" -- ; name: -- n )
       create ,
       ['] @ set-does>
       [: >body @ postpone literal ;] set-optimizer
     ;

   The only change is the addition of the ‘set-optimizer’ line.  When
you define a constant and compile it:

     5 myconstant4 five
     : foo five ;

   the compiled ‘five’ in ‘foo’ is now compiled to the literal 5 instead
of a generic invocation of ‘five’.  The quotation has the same stack
effect as ‘compile,’: ‘( xt -- )’.  The passed xt belongs to the
‘compile,’d word, i.e., ‘five’ in the example.  In the example the xt is
first converted to the body address, then the value 5 at that place is
fetched, and that value is compiled with the ‘postpone literal’ (*note
Literals::).

   This use of ‘set-optimizer’ assumes that the user does not change the
value of a constant with, e.g., ‘6 ' five >body !’.  While ‘five’ has
been defined with ‘create’, that is an implementation detail of
‘CONSTANT’, and if you don't document it, the user must not rely on it.
And if you use ‘set-optimizer’ in a way that assumes that the body does
not change (like is done here), you must not document that ‘create’ is
used; and conversely, if you document it, you have to write the
‘compile,’ implementation such that it can deal with changing bodies.

   Note that the call to ‘set-optimizer’ has to be performed after the
call to ‘set-does>’ (or ‘does>’, because ‘set-does>’ overwrites the
‘compile,’ implementation itself.

   We can also apply ‘set-optimizer’ to individual words rather than
inside a defining word like ‘constant’.  In this case, the xt of the
word passed to optimizer is usually unnecessary and is ‘drop’ped.  As an
simple example, let's define a word that is inlined when being compiled:

     : compile-my2dup ( xt -- )
       drop ]] over over [[ ;

     : my2dup over over ;
     ' compile-my2dup set-optimizer

     : foo my2dup ;
     see my2dup

   An alternative way to define ‘my2dup’ is:

     : my2dup over over ;
     opt: drop ]] over over [[ ;

   ‘Opt:’ starts an anonymous definition that is then (internally)
attached to ‘my2dup’ with ‘set-optimize’.

   One disadvantage of these approaches is that ‘over over’ occurs
twice.  This can be avoided by using ‘compile-my2dup’ to define
‘my2dup’:

     : compile-my2dup ( xt -- )
         drop ]] over over [[ ;

     : my2dup [ 0 compile-my2dup ] ;
     ' compile-my2dup set-optimizer

   Finally, a convenient way to write words like ‘my2dup’ is to use
‘inline:’ (*note Inline Definitions::), but it is limited to inlining.

   The engine ‘gforth-itc’ uses ‘,’ for ‘compile,’ in nearly all cases
and ‘set-optimizer’ usually has no effect there.


File: gforth.info,  Node: Creating from a prototype,  Next: Making a word current,  Prev: User-defined compile-comma,  Up: User-defined Defining Words

6.11.10.8 Creating from a prototype
...................................

In the above we show how to define a word by first using ‘create’, and
then modifying it with ‘immediate’, ‘set-does>’, ‘set-to’,
‘set-optimizer’ etc.

   An alternative way is to create a prototype using these words, and
then create a new word from that prototype.  This kind of copying does
not cover the body, so that has to be allocated and initialized
explicitly.  Taking ‘dvalue’ above, we could instead define it as:

     create dvalue-prototype ( -- d )
     `2@ set-does>
     `dvalue-to set-to

     : dvalue ( d "name" -- ; name: -- d )
       ``dvalue-prototype create-from 2, reveal ;

   An advantage of this approach is that creating words with ‘dvalue’ is
now faster.(1)  But this advantage is only relevant if the number of
words created with this defining word is huge.

‘create-from’ ( nt "name" -  ) gforth-1.0
   Create a word name that behaves like nt, but with an empty body.  nt
must be the nt of a named word.  The resulting header is not yet
‘reveal’ed; use ‘reveal’ to reveal it or ‘latest’ to get its xt.
Creating a word with ‘create-from’ without using any ‘set-’ words is
faster than if you create a word using ‘set-’ words, ‘immediate’, or
‘does>’.  You can use ‘noname’ with ‘create-from’.

‘reveal’ ( -  ) gforth-0.2
   Put the current word in the wordlist current at the time of the
header definition.

‘reveal!’ ( xt wid -  ) core-ext "reveal-store"
   Add XT to a wordlist.  Mapped to ‘DEFER!’.

   The performance advantage does not extend to using ‘noname’ with the
defining word.  Therefore we also have

‘noname-from’ ( xt -  ) gforth-1.0
   Create a nameless word that behaves like xt, but with an empty body.
xt must be the nt of a nameless word.

   Here's a usage example:

     ``dvalue-prototype noname create-from
     latestnt constant noname-dvalue-prototype

     : noname-dvalue ( d -- xt ; xt execution: -- d )
       noname-dvalue-prototype noname-from 2,
       latestxt ;

   ---------- Footnotes ----------

   (1) The non-prototype method first duplicates the header methods of
‘create’, modify them, and eventually deduplicate them.  The
‘create-from’ approach eliminates this overhead.


File: gforth.info,  Node: Making a word current,  Next: Const-does>,  Prev: Creating from a prototype,  Up: User-defined Defining Words

6.11.10.9 Making a word current
...............................

Many words mentioned above, such as ‘immediate’ or ‘set-optimizer’
change the "current" or "most recently defined" word.  Sometimes you
want to change an earlier word.  You can do this with

‘make-latest’ ( nt -  ) gforth-1.0
   Make nt the latest definition, which can be manipulated by
‘immediate’ and ‘set-*’ operations.  If you have used (especially
compiled) the word referred to by nt already, do not change the
behaviour of the word (only its implementation), otherwise you may get a
surprising mix of behaviours that is not consistent between Gforth
engines and versions.


File: gforth.info,  Node: Const-does>,  Prev: Making a word current,  Up: User-defined Defining Words

6.11.10.10 ‘Const-does>’
........................

A frequent use of ‘create’...‘does>’ is for transferring some values
from definition-time to run-time.  Other ways of achieving this are
closures (*note Closures::), and with colon definitions (*note
User-defined defining words with colon definitions::), but another way
of achieving this is to use

‘const-does>’ ( run-time: w*uw r*ur uw ur "name" -  ) gforth-obsolete "const-does"
   Defines NAME and returns.

   NAME execution: pushes W*UW R*UR, then performs the code following
the ‘const-does>’.

   A typical use of this word is:

     : curry+ ( n1 "name" -- )
     1 0 CONST-DOES> ( n2 -- n1+n2 )
         + ;

     3 curry+ 3+

   Here the ‘1 0’ means that 1 cell and 0 floats are transferred from
definition to run-time.

   The advantages of using ‘const-does>’ compared to ‘create’...‘does>’
are:

   • You don't have to deal with storing and retrieving the values,
     i.e., your program becomes more writable and readable.

   • When using ‘does>’, you have to introduce a ‘@’ that cannot be
     optimized away automatically (because the system does not know
     whether you allow to access the data with ‘>body’...‘!’).  You can
     address this problem with ‘set-optimizer’ (*note User-defined
     compile-comma::), but ‘const-does>’ avoids it; however, the current
     implementation is still not particularly efficient.

   A Standard Forth implementation of ‘const-does>’ is available in
‘compat/const-does.fs’.


File: gforth.info,  Node: Deferred Words,  Next: Synonyms,  Prev: User-defined Defining Words,  Up: Defining Words

6.11.11 Deferred Words
----------------------

The defining word ‘Defer’ allows you to define a word by name without
defining its behaviour; the definition of its behaviour is deferred.
Here are two situation where this can be useful:

   • Where you want to allow the behaviour of a word to be altered
     later, and for all precompiled references to the word to change
     when its behaviour is changed.
   • For mutual recursion: *Note Calls and returns::.

   In the following example, ‘foo’ always invokes the version of ‘greet’
that prints "‘Good morning’" whilst ‘bar’ always invokes the version
that prints "‘Hello’".  There is no way of getting ‘foo’ to use the
later version without re-ordering the source code and recompiling it.

     : greet ." Good morning" ;
     : foo ... greet ... ;
     : greet ." Hello" ;
     : bar ... greet ... ;

   This problem can be solved by defining ‘greet’ as a ‘Defer’red word.
The behaviour of a ‘Defer’red word can be defined and redefined at any
time by using ‘IS’ to associate the xt of a previously-defined word with
it.  The previous example becomes:

     Defer greet ( -- )
     : foo ... greet ... ;
     : bar ... greet ... ;
     : greet1 ( -- ) ." Good morning" ;
     : greet2 ( -- ) ." Hello" ;
     ' greet2 IS greet  \ make greet behave like greet2

   Programming style note:

   You should write a stack comment for every deferred word, and put
only XTs into deferred words that conform to this stack effect.
Otherwise it's too difficult to use the deferred word.

   One thing to note is that ‘IS’ has special compilation semantics,
such that it parses the name at compile time (like ‘TO’):

     : set-greet ( xt -- )
       IS greet ;

     ' greet1 set-greet

‘Defer’ ( "name" -  ) core-ext
   Define a deferred word name; you have to set it to an xt before
executing it.
name execution: execute the xt that name has most recently been set to
execute.
‘Is name’ run-time: ( xt1 - ) Set name to execute xt1.
‘Action-of name’ run-time: ( - xt2 ) xt2 is the xt that name has most
recently been set to execute.

‘IS’ ( xt ... "name" -  ) core-ext
   Name is a defer-flavoured word, ...  is optional additional
addressing information, e.g., for a defer-flavoured field.  At run-time,
perform the is name semantics: change name (with the same additional
addressing information) to execute xt.

   You can extract the xt of a ‘defer’red word with ‘action-of’:

     action-of greet ( xt ) >name id.

‘action-of’ ( interpretation "name" ... - xt; compilation "name" - ; run-time ... - xt  ) core-ext
   Name is a defer-flavoured word, ...  is optional additional
addressing information, e.g., for a defer-flavoured field.  At run-time,
perform the action-of name semantics: Push the xt, that name (possibly
with additional addressing data on the stack) executes.

   One usage for deferred words is the definition of a an action (e.g.,
initialization) in several pieces, each piece in a different source file
dealing with the matters of that source file.  This can be done with

     defer myspeech ( -- )
     :noname cr ." <central message>" ; is myspeech

     \ and in every source file where you want to add a piece, something like
     :noname ( -- )
       cr ." <introduction>"
       [ action-of myspeech compile, ]
       cr ." <conclusion>"
     ; is myspeech

   The ‘[ action-of myspeech compile, ]’ calls the previous content of
‘myspeech’.  Gforth offers the words ‘:is’ and ‘defers’ to express the
last definition more conveniently:

     :is myspeech ( -- )
       cr ." <introduction>"
       defers myspeech
       cr ." <conclusion>" ;

‘:is’ ( "name" -  ) gforth-experimental "colon-is"
   define a noname that is assigned to the deferred word NAME at ‘;’.

‘defers’ ( compilation "name" - ; run-time ... - ...  ) gforth-0.2
   Compiles the present contents of the deferred word name into the
current definition.  I.e., this produces static binding as if name was
not deferred.

   Another usage is to change a deferred word temporarily, and later
change it back.  Gforth provides words for supporting this usage.  The
use of ‘preserve’ is shown in this example:

     : smalltalk ( -- )
       greet ."  Isn't the weather nice?" ;

     \ here GREET performs GREET2
     : when-in-rome ( xt -- )
       [: ." Buon Giorno!" ;] is greet
       execute
       preserve greet \ Equivalent to: ['] greet2 is greet
     ;

     ' greet1 is greet
     greet \ "Good Morning"
     ' smalltalk when-in-rome \ "Buon Giorno! Isn't the weather nice?"
     greet \ "Hello"

‘preserve’ ( compilation "name" - ; run-time -  ) gforth-1.0
   Name has to be a defer-flavoured word that does not consume
additional stack items for addressing (i.e., not a defer-flavoured
field).  ‘Preserve name’ changes name at run-time to execute the same XT
that it had at compile time.  I.e., ‘Preserve name’ is equivalent to ‘[
action-of name ] literal is name’.

   ‘Preserve’ is only appropriate when you want to restore the deferred
word to a fixed xt.  If you want to change a deferred temporarily and
then restore its old run-time value, use ‘wrap-xt’:

     : when-in-rome2 ( xt -- )
       [: ." Buon Giorno!" ;] ['] greet rot wrap-xt ;

     ' greet1 is greet
     greet \ "Good Morning"
     ' smalltalk when-in-rome2 \ "Buon Giorno! Isn't the weather nice?"
     greet \ "Good Morning"

‘wrap-xt’ ( ... xt1 xt2 xt3 - ...  ) gforth-1.0
   Set deferred word xt2 to xt1 and execute xt3.  Restore afterwards.

   For implementing words like ‘wrap-xt’ to which you pass the xt of a
deferred word, you cannot use ‘is’ and ‘action-of’, which consume a name
from the input stream.  Instead, you use the words ‘defer!’ and
‘defer@’.

‘defer!’ ( xt xt-deferred -  ) core-ext "defer-store"
   xt-deferred belongs to a word defined with ‘defer’, it is changed to
execute xt on execution.
If xt-deferred belongs to another defer-flavoured word (e.g., a
defer-flavoured field), the location associated with ...  xt-deferred is
changed to execut xt.
If xt-deferred is the xt of a word that is not defer-flavoured, throw
-21 (Unsupported operation).

‘defer@’ ( ... xt-deferred - xt  ) core-ext "defer-fetch"
   If xt-deferred belongs to a word defined with ‘defer’, xt represents
the word currently associated with the deferred word xt-deferred.
If xt-deferred belongs to another defer-flavoured word (e.g., a
defer-flavoured field), xt is the word associated with the location
indicated by ...  xt-deferred (e.g., for a defer-flavoured field ...  is
the structure address).
If xt-deferred is the xt of a word that is not defer-flavoured, throw
-21 (Unsupported operation).

   A deferred word can only inherit execution semantics from the xt
(because that is all that an xt can represent - for more discussion of
this *note Tokens for Words::); by default it will have default
interpretation and compilation semantics deriving from this execution
semantics.  However, you can change the interpretation and compilation
semantics of the deferred word in the usual ways:

     : bar .... ; immediate
     Defer fred immediate
     Defer jim

     ' bar IS jim  \ jim has default semantics
     ' bar IS fred \ fred is immediate


File: gforth.info,  Node: Synonyms,  Prev: Deferred Words,  Up: Defining Words

6.11.12 Synonyms
----------------

The defining word ‘synonym’ allows you to define a word by name that has
the same behaviour as some other word.  Here are two situation where
this can be useful:

   • When you want access to a word's definition from a different word
     list (for an example of this, see the definitions in the ‘Root’
     word list in the Gforth source).
   • When you want to create a synonym; a definition that can be known
     by either of two names (for example, ‘THEN’ and ‘ENDIF’ can be
     defined as synonyms).

‘Synonym’ ( "name" "oldname" -  ) tools-ext
   Define name to behave the same way as oldname: Same interpretation
semantics, same compilation semantics, same ‘to’, ‘+to’, ‘is’,
‘action-of’ and ‘addr’ semantics.

   Gforth also offers the Gforth-specific ‘alias’, that allows to define
another word with the same execution token, but otherwise default
semantics (no copying of compilation or other semantics).  You can then
change, e.g., the compilation semantics with, e.g., ‘immediate’.

‘Alias’ ( xt "name" -  ) gforth-0.2
   Define name as a word that performs xt.  Unlike for deferred words,
aliases don't have an indirection overhead when compiled.

   Example:

     : foo ." foo" ; immediate

     ' foo Alias bar1           \ bar1 is not an immediate word
     ' foo Alias bar2 immediate \ bar2 is an immediate word
     synonym bar3 foo           \ bar3 is an immediate word
     : test-bar1 bar1 ; \ no output
     test-bar1          \ "foo"
     : test-bar2 bar2 ; \ "foo"
     test-bar2          \ no output
     : test-bar3 bar3 ; \ "foo"
     test-bar3          \ no output

   Both synonyms and aliases have a different nt than the original, but
ticking it (or using ‘name>interpret’) produces the same xt as the
original (*note Tokens for Words::).


File: gforth.info,  Node: Structures,  Next: User-defined Stacks,  Prev: Defining Words,  Up: Words

6.12 Structures
===============

A structure (aka record) is a collection of fields that are stored
together.  The fields can have different types and are accessed by name.
There are typically several instances of a structure, otherwise
programmers tend to prefer using a variable or somesuch for each field.

   In Forth you can use raw address arithmetic to access fields of
structures, but using field names and defining field access words with
the defining words described in this section makes the code more
readable.

* Menu:

* Standard Structures::
* Value-Flavoured and Defer-Flavoured Fields::
* Structure Extension::
* Gforth structs::


File: gforth.info,  Node: Standard Structures,  Next: Value-Flavoured and Defer-Flavoured Fields,  Prev: Structures,  Up: Structures

6.12.1 Standard Structures
--------------------------

The Forth 2012 standard defines a number of words for defining fields
and structures.

   A typical example of defining a structure with several fields is:

     0 \ offset of first field, 0 in the usual case
       field: intlist-next ( intlist -- addr1 )
       field: intlist-val  ( intlist -- addr2 )
     constant intlist ( -- u )

   An equivalent alternative way of defining this structure is:

     begin-structure intlist ( -- u )
       field: intlist-next ( intlist -- addr1 )
       field: intlist-val  ( intlist -- addr2 )
     end-structure

   ‘Intlist’ returns the size of the structure.  The convention for the
field names here is to prepend the structure name, so that you don't run
into conflicts when several structures have ‘next’ and ‘val’ fields; in
Forth, by default field names are in the same wordlist (i.e., the same
name space) as the other words (including other field names), and trying
to use the search order (*note Word Lists::) for avoiding conflicts is
rather cumbersome (unless you use the scope recognizer *note Default
recognizers::).

   You can then use that to allocate an instance of that structure and
then use the field words to access the fields of that instance:

     intlist allocate throw constant my-intlist1
     0 my-intlist1 intlist-next !
     5 my-intlist1 intlist-val  !

     intlist allocate throw constant my-intlist2
     my-intlist1 my-intlist2 intlist-next !
     7           my-intlist2 intlist-val !

     : intlist-sum ( intlist -- n )
     \ "intlist" is a pointer to the first element of a linked list
     \ "n" is the sum of the intlist-val fields in the linked list
         0 BEGIN ( intlist1 n1 )
             over
         WHILE ( list1 n1 )
             over intlist-val @ +
             swap intlist-next @ swap
         REPEAT
         nip ;

     my-intlist2 intlist-sum . \ prints "12"

   The words for defining structures and fields of various types are:

‘begin-structure’ ( "name" - struct-sys 0  ) facility-ext

‘end-structure’ ( struct-sys +n -  ) facility-ext
   end a structure started with ‘begin-structure’

‘cfield:’ ( u1 "name" - u2  ) facility-ext "c-field-colon"
   Define a char-sized field

‘field:’ ( u1 "name" - u2  ) facility-ext "field-colon"
   Define an aligned cell-sized field

‘2field:’ ( u1 "name" - u2  ) gforth-0.7 "two-field-colon"
   Define an aligned double-cell-sized field

‘ffield:’ ( u1 "name" - u2  ) floating-ext "f-field-colon"
   Define a faligned float-sized field

‘sffield:’ ( u1 "name" - u2  ) floating-ext "s-f-field-colon"
   Define a sfaligned sfloat-sized field

‘dffield:’ ( u1 "name" - u2  ) floating-ext "d-f-field-colon"
   Define a dfaligned dfloat-sized field

‘wfield:’ ( u1 "name" - u2  ) gforth-1.0 "w-field-colon"
   Define a naturally aligned field for a 16-bit value.

‘lfield:’ ( u1 "name" - u2  ) gforth-1.0 "l-field-colon"
   Define a naturally aligned field for a 32-bit value.

‘xfield:’ ( u1 "name" - u2  ) gforth-1.0 "x-field-colon"
   Define a naturally aligned field for a 64-bit-value.

   If you need something beyond these field types, you can use ‘+field’
to define fields of arbitrary size.  You have to ensure the correct
alignment yourself in this case.  E.g., if you want to put one struct
inside another struct, you would do it with

     0
       cfield:                nested-foo
       aligned intlist +field nested-bar
     constant nested

   In this example the field ‘nested-bar’ contains an intlist structure,
so the size of ‘intlist’ is passed to ‘+field’.  An ‘intlist’ must be
cell-aligned (it contains cell fields), and this is achieved by aligning
the current field offset with ‘aligned’ before the field definition.
Our recommendation is to always precede the usage of ‘+field’ with an
appropriate alignment word (except if character-alignment is good enough
for the field); this ensures that the field will stay correctly aligned
even if other fields are later inserted before the ‘+field’-defined
field.

‘+field’ ( noffset1 nsize "name" - noffset2  ) facility-ext "plus-field"
   Defining word; defines name ‘( addr1 -- addr2 )’, where addr2 is
addr1+noffset1.  noffset2 is noffset1+nsize.

   The first field is at the base address of a structure and the word
for this field (e.g., ‘list-next’) actually does not change the address
on the stack.  You may be tempted to leave it away in the interest of
run-time and space efficiency.  This is not necessary, because Gforth
and other Forth systems optimize this case: If you compile a first-field
word, no code is generated.  So, in the interest of readability and
maintainability you should include the word for the field when accessing
the field.


File: gforth.info,  Node: Value-Flavoured and Defer-Flavoured Fields,  Next: Structure Extension,  Prev: Standard Structures,  Up: Structures

6.12.2 Value-Flavoured and Defer-Flavoured Fields
-------------------------------------------------

In addition to the variable-flavoured fields that produce an address
(*note Standard Structures::), Gforth also provides value-flavoured
fields.  Like all fields, value-flavoured fields consume the start
address of the struct, but they produce their value and you can apply
‘to’, ‘+to’ and (if the field is ‘addressable:’, *note Values::) ‘addr’
on them.  E.g., we can do something like the ‘intlist’ definition (*note
Standard Structures::):

     0
                    value: intlist>next ( intlista -- intlista1 )
       addressable: value: intlist>val  ( intlista -- n )
     constant intlista ( -- u )

   This means that there are the following ways of accessing
‘intlist>val’:

     intlist>val ( intlista -- n )
     ->intlist>val ( n intlista -- ) \ aka  to intlist>val
     +>intlist>val ( n intlista -- ) \ aka +to intlist>val
     addr intlist>val ( intlista -- addr )

   And here's the earlier example (*note Standard Structures::)
rewritten to use ‘intlista’:

     intlista allocate throw constant my-intlista1
     0 my-intlista1 to intlist>next
     5 my-intlista1 to intlist>val

     intlista allocate throw constant my-intlista2
     my-intlista1 my-intlista2 to intlist>next
     7            my-intlista2 to intlist>val

     : intlista-sum ( intlista -- n )
     \ "intlista" is a pointer to the first element of a linked list
     \ "n" is the sum of the intlist>val fields in the linked list
         0 BEGIN ( intlista1 n1 )
             over
         WHILE ( list1 n1 )
             over intlist>val +
             swap intlist>next swap
         REPEAT
         nip ;

     my-intlista2 intlista-sum . \ prints "12"

   Depending on the type of the field, the value can be something
different than a single cell.

‘value:’ ( u1 "name" - u2  ) gforth-experimental "value-colon"
   Name is a value-flavoured field; in-memory-size: cell; on-stack: cell

‘cvalue:’ ( u1 "name" - u2  ) gforth-experimental "cvalue-colon"
   Name is a value-flavoured field; in-memory-size: char; on-stack:
unsigned cell

‘wvalue:’ ( u1 "name" - u2  ) gforth-experimental "wvalue-colon"
   Name is a value-flavoured field; in-memory-size: 16 bits; on-stack:
unsigned cell

‘lvalue:’ ( u1 "name" - u2  ) gforth-experimental "lvalue-colon"
   Name is a value-flavoured field; in-memory-size: 32 bits; on-stack:
unsigned cell

‘scvalue:’ ( u1 "name" - u2  ) gforth-experimental "scvalue-colon"
   Name is a value-flavoured field; in-memory-size: char; on-stack:
signed cell

‘swvalue:’ ( u1 "name" - u2  ) gforth-experimental "swvalue-colon"
   Name is a value-flavoured field; in-memory-size: 16 bits; on-stack:
signed cell

‘slvalue:’ ( u1 "name" - u2  ) gforth-experimental "slvalue-colon"
   Name is a value-flavoured field; in-memory-size: 32 bits; on-stack:
signed cell

‘2value:’ ( u1 "name" - u2  ) gforth-experimental "two-value-colon"
   Name is a value-flavoured field; in-memory-size: 2 cells; on-stack: 2
cells; ‘+to’ performs double-cell addition (‘d+’).

‘fvalue:’ ( u1 "name" - u2  ) gforth-experimental "fvalue-colon"
   Name is a value-flavoured field; in-memory-size: float; on-stack:
float

‘sfvalue:’ ( u1 "name" - u2  ) gforth-experimental "sfvalue-colon"
   Name is a value-flavoured field; in-memory-size: 32-bit float;
on-stack: float

‘dfvalue:’ ( u1 "name" - u2  ) gforth-experimental "dfvalue-colon"
   Name is a value-flavoured field; in-memory-size: 64-bit float;
on-stack: float

‘zvalue:’ ( u1 "name" - u2  ) gforth-experimental "zvalue-colon"
   Name is a value-flavoured field; in-memory-size: 2 floats; on-stack:
2 floats; ‘+to’ performs componentwise addition.

‘$value:’ ( u1 "name" - u2  ) gforth-experimental "dollar-value-colon"
   Name is a value-flavoured field; in-memory-size: cell; on-stack:
c-addr u (*note $tring words::); ‘( c-addr u ) +to name’ appends c-addr
u to the string in the field.

   Gforth also has field words for dealing with dynamically-sized
arrays.  A field for such an array contains just a cell that points to
the actual data, and this cell has to be set to 0 before accessing the
array the first time.  When accessing the field (without operator, or
with ‘to’ or ‘+to’), there has to be the index and the structure address
on the stack, with the structure address on top.  Any further items
consumed by ‘to’ or ‘+to’ are below the index on the stack.  The array
expands to the size given by the maximum access; any unset elements are
0; for ‘$value[]’ accessing them produces a 0-length (i.e., empty)
string.

   Here is a usage example:

     0
       value[]:  bla>x[]
       $value[]: bla>$y[]
     constant bla

     bla allocate throw constant mybla
     mybla bla erase \ set all fields to 0

     5 2 mybla to bla>x[] \ access at index 2
     7 0 mybla to bla>x[] \ access at index 0
     2 mybla bla>x[] . \ prints "5"
     3 mybla bla>x[] . \ prints "0"
     "foo" 2 mybla to bla>$y[]  \ access at index 2
     "bla" 1 mybla to bla>$y[]  \ access at index 1
     "bar" 2 mybla +to bla>$y[] \ access at index 2
     0 mybla bla>$y[] . . \ prints "0 0"
     1 mybla bla>$y[] type \ prints "bla"
     2 mybla bla>$y[] type \ prints "foobar"

‘value[]:’ ( u1 "name" - u2  ) gforth-experimental "value-left-bracket-right-bracket-colon"
   Name is a value-flavoured array field; in-memory-size: cell;
on-stack: cell

‘$value[]:’ ( u1 "name" - u2  ) gforth-experimental "dollar-value-left-bracket-right-bracket-colon"
   Name is a value-flavoured array field; in-memory-size: cell;
on-stack: c-addr u (*note $tring words::); ‘( c-addr u ) +to name’
appends c-addr u to the string in the array element.

   Finally, you can define defer-flavoured fields.  Here is a usage
example:

     0
       addressable: defer: foo'bar
     constant foo

     foo allocate throw constant my-foo
     :noname ." test" ; my-foo is foo'bar
     my-foo foo'bar                   \ prints "test"
     my-foo addr foo'bar @ execute   \ prints "test"
     my-foo action-of foo'bar execute \ prints "test"
     my-foo `foo'bar defer@ execute   \ prints "test"
     :noname ." test1" ; my-foo `foo'bar defer!
     my-foo foo'bar                   \ prints "test1"

‘defer:’ ( u1 "name" - u2  ) gforth-experimental "defer-colon"
   Name is a defer-flavoured field

   For documentation of ‘is’, ‘action-of’, ‘defer@’, ‘defer!’, see *Note
Deferred Words::.  Note however, that when used on defer-flavoured
fields, all these words consume the start address of the structure,
unlike for words defined with ‘defer’.


File: gforth.info,  Node: Structure Extension,  Next: Gforth structs,  Prev: Value-Flavoured and Defer-Flavoured Fields,  Up: Structures

6.12.3 Structure Extension
--------------------------

You can create a new structure starting with an existing structure and
its fields.  E.g., if we also want to define ‘floatlist’, we can factor
out the ‘...-next’ field into a general structure ‘list’ without
payload, and then define ‘intlist’ and ‘floatlist’ as extensions of
‘list’:(1)

     0
       field: list-next ( list -- addr )
     constant list ( -- u )

     list
       field: intlist-val ( intlist -- addr )
     constant intlist ( -- u )

     list
       ffield: floatlist-val ( floatlist -- addr )
     constant floatlist ( -- u )

   Note that in this variant there is no ‘intlist-next’ nor a
‘floatlist-next’, just a ‘list-next’; so when you use, e.g., a
‘floatlist’, the organization through extension of ‘list’ is exposed.
This may make it harder to refactor things, so you may prefer to also
introduce synonyms ‘intlist-next’ and ‘floatlist-next’.

   If you prefer to use ‘begin-structure’...‘end-structure’, you can do
the equivalent definition as follows:

     begin-structure list ( -- u )
       field: list-next ( list -- addr )
     end-structure

     list extend-structure intlist
       field: intlist-val  ( intlist -- addr )
     end-structure

     list extend-structure floatlist
       ffield: floatlist-val  ( floatlist -- addr )
     end-structure

‘extend-structure’ ( n "name" - struct-sys n  ) gforth-1.0
   Start a new structure name as extension of an existing structure with
size n.

   ---------- Footnotes ----------

   (1) This feature is also known as _extended records_ in Oberon.


File: gforth.info,  Node: Gforth structs,  Prev: Structure Extension,  Up: Structures

6.12.4 Gforth structs
---------------------

Gforth has had structs before the standard had them; they are a little
different, and you can still use them.  One benefit of the Gforth
structs is that they propagate knowledge of alignment requirements, so
if you build the ‘nested’ structure (*note Standard Structures::), you
do not need to look inside ‘intlist’ to find out the proper alignment,
and you also do not need to mention alignment at all.  Instead, this
example would look like:

     struct
       cell% field intlist-next
       cell% field intlist-val
     end-struct intlist%

     struct
       char%    field nested-foo
       intlist% field nested-bar
     end-struct nested%

   The fields are variable-flavoured, i.e., they work in the same way as
those defined with ‘field:’, ‘+field’ etc.

   A disadvantage of the Gforth structs is that, with the standard going
for something else, you need to learn additional material to write and
understand code that uses them.  Another disadvantage of the Gforth
structs is that they do not support value-flavoured or defer-flavoured
fields.  On the balance, in our opinion the disadvantages now outweigh
the advantages, so we recommend using the standard structure words
(*note Standard Structures::).  Nevertheless, here is the documentation
for Gforth's structs.

   The ‘list’ and ‘intlist’ examples look like this with Gforth structs:

     struct
       cell% field list-next
     end-struct list%

     list%
       cell% field intlist-val
     end-struct intlist%

   ‘Intlist%’ contains information about size and alignment, and you use
‘%size’ to get the size, e.g., for allocation:

     intlist% %size allocate throw constant my-intlist1

   A shorthand for that is

     intlist% %alloc constant my-intlist1

   The fields behave the same way, so the rest of the example works as
with standard structures.

   In addition to specifying single cells with ‘cell%’, you can also
specify an array of, e.g., 10 cells like this:

       cell% 10 * field bla-blub
       \ equivalent to the standard:
       \ aligned 10 cells +field bla-blub

   You can use ‘cell% 10 *’ not just with ‘field’, but also in other
places where an alignment and size is expected, e.g., with ‘%alloc’.

‘%align’ ( align size -  ) gforth-0.4 "percent-align"
   Align the data space pointer to the alignment ALIGN.

‘%alignment’ ( align size - align  ) gforth-0.4 "percent-alignment"
   The alignment of the structure.

‘%alloc’ ( align size - addr  ) gforth-0.4 "percent-alloc"
   Allocate SIZE address units with alignment ALIGN, giving a data block
at ADDR; ‘throw’ an ior code if not successful.

‘%allocate’ ( align size - addr ior  ) gforth-0.4 "percent-allocate"
   Allocate SIZE address units with alignment ALIGN, similar to
‘allocate’.

‘%allot’ ( align size - addr  ) gforth-0.4 "percent-allot"
   Allot SIZE address units of data space with alignment ALIGN; the
resulting block of data is found at ADDR.

‘cell%’ ( - align size  ) gforth-0.4 "cell-percent"

‘char%’ ( - align size  ) gforth-0.4 "char-percent"

‘dfloat%’ ( - align size  ) gforth-0.4 "d-float-percent"

‘double%’ ( - align size  ) gforth-0.4 "double-percent"
   describes a double cell (equivalent to ‘cell% 2*’).

‘end-struct’ ( align size "name" -  ) gforth-0.2
   Define a structure/type descriptor NAME with alignment ALIGN and size
SIZE1 (SIZE rounded up to be a multiple of ALIGN).
‘name’ execution: - ALIGN SIZE1

‘field’ ( align1 offset1 align size "name" -  align2 offset2  ) gforth-0.2
   Create a field NAME with offset OFFSET1, and the type given by ALIGN
SIZE.  OFFSET2 is the offset of the next field, and ALIGN2 is the
alignment of all fields.
‘name’ execution: ADDR1 - ADDR2.
ADDR2=ADDR1+OFFSET1

‘float%’ ( - align size  ) gforth-0.4 "float-percent"

‘sfloat%’ ( - align size  ) gforth-0.4 "s-float-percent"

‘%size’ ( align size - size  ) gforth-0.4 "percent-size"
   The size of the structure.

‘struct’ ( - align size  ) gforth-0.2
   An empty structure, used to start a structure definition.


File: gforth.info,  Node: User-defined Stacks,  Next: Interpretation and Compilation Semantics,  Prev: Structures,  Up: Words

6.13 User-defined Stacks
========================

Gforth supports user-defined stacks.  They are used for implementing
features such as recognizer sequences, but you can also define stacks
for your own purposes.  And these stacks actually support inserting and
deleting at both ends, so they are actually double-ended queues
(deques).  In addition, they support inserting and deleting in the
middle.

   In Gforth the stacks grow as necessary, but the interface is designed
to also support resource-constrained systems that allocate fixed-size
stacks, where exceeding the stack size results in an error.  So you
should provide the size parameter accordingly.

   A stack is represented on the data stack by a cell.

‘stack’ ( n - stack  ) gforth-experimental
   Create an unnamed stack with at least N cells space.

‘stack:’ ( n "name" -  ) gforth-experimental "stack-colon"
   Create a named stack with at least N cells space.

‘stack>’ ( stack - x  ) gforth-experimental "stack-from"
   Pop item x from top of stack.

‘>stack’ ( x stack -  ) gforth-experimental "to-stack"
   Push x to top of stack.

‘>back’ ( x stack -  ) gforth-experimental "to-back"
   Insert x at the bottom of stack.

‘back>’ ( stack - x  ) gforth-experimental "back-from"
   Remove item x from bottom of stack.

‘+after’ ( x1 x2 stack -  ) gforth-experimental "plus-after"
   Insert X1 below every occurrence X2 in stack.

‘-stack’ ( x stack -  ) gforth-experimental "minus-stack"
   Delete every occurrence of x from anywhere in stack.

‘set-stack’ ( x1 .. xn n stack -  ) gforth-experimental
   Overwrite the contents of stack with n elements from the data stack,
with xn becoming the top of stack.

‘get-stack’ ( stack - x1 .. xn n  ) gforth-experimental
   Push the contents of stack on the data stack, with the top element in
stack being pushed as xn.


File: gforth.info,  Node: Interpretation and Compilation Semantics,  Next: Tokens for Words,  Prev: User-defined Stacks,  Up: Words

6.14 Interpretation and Compilation Semantics
=============================================

In Gforth every named word has interpretation and compilation semantics,
i.e., separate actions that are performed in various contexts.

   In principle these semantics can be anything and completely
independent of each other, but in practice they are usually connected,
and words usually have default compilation semantics (compile the
interpretation semantics) or immediate compilation semantics (perform
the interpretation semantics); a few have other combinations of
interpretation and compilation semantics (combined words).

   The standard also discusses execution semantics, but it uses them
only to define interpretation and/or compilation semantics, so they are
not as essential as interpretation and compilation semantics.  In
particular, for every word in the standard that has both interpretation
and execution semantics, they are the same.  In Gforth (since 1.0), they
are always the same, and this manual uses the terms interchangeably,
usually preferring interpretation semantics.  In the description of
defining words, you see "name execution", which describes the
interpretation/execution semantics of name.

   Some named words also have some of ‘to’/‘+to’/‘action-of’/‘is’/‘addr
name’ semantics, but these are mostly discussed elsewhere (*note
Values::, *note Deferred Words::, *note Words with user-defined TO
etc.::)

* Menu:

* Where are interpretation semantics used?::
* Where are compilation semantics used?::
* Which semantics do existing words have?::
* What semantics do normal definitions have?::
* How to define immediate words::
* How to define combined words::


File: gforth.info,  Node: Where are interpretation semantics used?,  Next: Where are compilation semantics used?,  Prev: Interpretation and Compilation Semantics,  Up: Interpretation and Compilation Semantics

6.14.1 Where are interpretation semantics used?
-----------------------------------------------

The most common use of the interpretation semantics of a word w is when
w is text-interpreted in interpretation state, the default state of the
text interpreter.

   I.e., when you start Gforth and type

     s" hello" type

   the text interpreter performs the interpretation semantics of the
words ‘s"’ and ‘type’.

   Also, when you get the execution token of a word w with ‘`w’, ‘' w’
or ‘['] w’ (*note Execution token::), the execution token represents the
interpretation semantics.

   When you get the execution token of the most recently defined word
with ‘latestxt’ (*note Anonymous Definitions::), that also refers to the
interpretation semantics of the word.

   Finally, ‘name>interpret’ (*note Name token::) produces an execution
token that represents the interpretation semantics of the word.


File: gforth.info,  Node: Where are compilation semantics used?,  Next: Which semantics do existing words have?,  Prev: Where are interpretation semantics used?,  Up: Interpretation and Compilation Semantics

6.14.2 Where are compilation semantics used?
--------------------------------------------

The most common use of the compilation semantics of a word w is when w
is text-interpreted in compile state, the state right after starting a
definition with, e.g., ‘:’.

     : hello
       s" hello" type ;

   In this example, the text interpreter performs the compilation
semantics of ‘s"’, ‘type’ and ‘;’ (after first performing the
interpretation semantics of ‘:’)

   When you postpone a word, you also use the compilation semantics.

     : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
       POSTPONE + ;

     : foo ( n1 n2 -- n )
       [ compile-+ ] ;

     see foo

   Here the ‘POSTPONE +’ compiles the compilation semantics of ‘+’ into
‘compile-+’ (By contrast, just writing ‘+’ in this place would result in
_performing_ the compilation semantics of ‘+’, and because this is a
word with default compilation semantics, that would compile the
_execution/interpretation_ semantics of ‘+’).  In the definition of
‘foo’, (the interpretation semantics of) ‘compile-+’ is performed, which
in turn performs the compilation semantics of ‘+’, i.e., it compiles ‘+’
into ‘foo’.

   The compilation semantics is represented by a compilation token
(*note Compilation token::).  You can get the compilation token of a
word w with ‘``w name>compile’, ‘comp' w’, or ‘[comp'] w’.  The first
form first gets the name token of w and then accesses the compilation
token with ‘name>compile’.


File: gforth.info,  Node: Which semantics do existing words have?,  Next: What semantics do normal definitions have?,  Prev: Where are compilation semantics used?,  Up: Interpretation and Compilation Semantics

6.14.3 Which semantics do existing words have?
----------------------------------------------

For words built into Gforth, the documentation specifies the semantics.

   Most words have default compilation semantics.  For such words (e.g.,
‘!’, *note Memory Access::) the documentation describes the
interpretation/execution semantics without explicitly labeling it as
such.  The compilation semantics of these words is to compile the
interpretation semantics into the current definition; the stack effect
of performing the default compilation semantics is ‘( -- )’.

   Some words have non-default compilation semantics.  This is either
indicated by labels for interpretation, compilation, and/or run-time in
the stack effects (e.g., for ‘IF’, *note Arbitrary control
structures::), or by having separate paragraphs for interpretation,
compilation, and/or run-time in the prose (e.g., for ‘S"’, *note String
and character literals::).

   You may wonder about the run-time semantics mentioned in the previous
paragraphs.  For some words (e.g., ‘if’), the compilation semantics
compiles something that is not the interpretation/execution semantics.
We (and the standard) describe the behaviour of the code that these
words compile with under the label "run-time semantics"; if you see
"run-time" in a word description (e.g., in its stack effect), that
usually refers to run-time semantics that the compilation semantics of
the word compiles.

   Concerning the description of the various semantics, both the
standard and this manual describe the interpretation/execution semantics
of words with default semantics without preceding these semantics with a
label (the label "execution" or "interpretation" would be appropriate).
The compilation semantics of such words are the implied default
compilation semantics (*note What semantics do normal definitions
have?::).

   For words that have some non-default semantics, the standard
specifies the different semantics of the word in separate subsections,
each preceded with a label ("interpretation:", "compilation:", and, if
necessary, "execution:" or "run-time:"(1)).  This manual often takes a
more informal approach.  The approach taken in this manual may be more
accommodating for everyday use, while the standard approach is more
precise for reasoning about details of the language.

   ---------- Footnotes ----------

   (1) In some cases the standard leaves the subsection for
interpretation or compilation semantics away, and leaves it to the
default mechanism to derive those semantics from execution semantics.


File: gforth.info,  Node: What semantics do normal definitions have?,  Next: How to define immediate words,  Prev: Which semantics do existing words have?,  Up: Interpretation and Compilation Semantics

6.14.4 What semantics do normal definitions have?
-------------------------------------------------

Most defining words normally produce words with default interpretation
semantics and default compilation semantics; those that do not (e.g,
‘synonym’ or ‘interpret/compile:’) are documented appropriately.

   The interpretation semantics of the newly defined word name are
described in the "name execution:" part of the description of the
defining word.  Things are a little more complicated for colon
definitions (*note Colon Definitions::) and words using
‘create’...‘does>’ (*note User-defined defining words using CREATE::),
but again, the description of what these words do is about the
interpretation semantics.

   For a word w with default compilation semantics, the compilation
semantics are to compile the interpretation semantics.  More formally:
to append the interpretation semantics of w to the interpretation
semantics of the current definition.  As an example, consider the
definition

     : name ... w ... ;

   Here the interpretation semantics of w is appended to the
interpretation semantics of name.


File: gforth.info,  Node: How to define immediate words,  Next: How to define combined words,  Prev: What semantics do normal definitions have?,  Up: Interpretation and Compilation Semantics

6.14.5 How to define immediate words
------------------------------------

You can change the compilation semantics of a word to be the same as the
interpretation semantics with

‘immediate’ ( -  ) core
   Change the compilation semantics of the most recently defined word to
be the same as its interpretation semantics.

   A contrived example:

     : [foo]
       ." foo" ; immediate

     : bar
       [foo] ; \ prints "foo"
     bar \ no output

   The ‘immediate’ causes ‘[foo]’ to perform the interpretation
semantics during the definition of ‘bar’ rather than compiling them.  A
convention sometimes (but not always) used for immediate words is to
have their names in brackets, e.g.  ‘[']’.

   A common use of ‘immediate’ is to define macros (*note Macros::).

   The text interpretation of a macro in interpret state is often a
mistake, so you can turn the macro into a ‘compile-only’ word with

‘compile-only’ ( -  ) gforth-0.2
   Mark the last definition as compile-only; as a result, the text
interpreter and ‘'’ will warn when they encounter such a word.

   Example:

     : endif
       postpone then ; immediate compile-only

     : foo
       if ." true" endif ;

     endif \ "warning: endif is compile-only"

   The warning is followed by a stack underflow error because ‘then’
wants to consume an orig (*note Arbitrary control structures::).

   Note that compiling code while the text interpreter is in interpret
state is not a problem in itself, even if a number of words are marked
‘compile-only’.  A more serious problem is compiling code if the current
definition is not an unfinished colon definition: there is no way to run
the resulting code.  Gforth warns about that even if a word is not
marked compile-only or if you text-interpret it in compile state:

     : compile-+
       postpone + ;

     : foo [ compile-+ ] ; \ no warning; interpretation semantics of compile-+

     compile-+ \ warning: Compiling outside a definition
     if        \ warning: IF is compile-only
               \ warning: Compiling outside a definition
     compile-+ \ warning: Compiling outside a definition
     then      \ warning: THEN is compile-only
     ] if      \ warning: Compiling outside a definition
       +       \ warning: Compiling outside a definition
       then
     [

   Note that switching to compile state in the last four lines silences
the "is compile-only" warnings, because in these lines the compilation
semantics of the words is performed.

   Why does ‘then’ not produce "Compiling outside a definition" warnings
in the example above?  ‘Then’ does not generate any code by itself, it
just changes the target of the code compiled by the matching ‘if’ or
‘ahead’.

‘restrict’ ( -  ) gforth-0.2
   A synonym for ‘compile-only’


File: gforth.info,  Node: How to define combined words,  Prev: How to define immediate words,  Up: Interpretation and Compilation Semantics

6.14.6 How to define combined words
-----------------------------------

In a few cases (and most of those are a bad idea) you want to define a
word that has some other combination of interpretation and compilation
semantics than words with default compilation semantics or immediate
words; we call such a word a combined word(1)).  The following contrived
example shows how you can define a combined word:

     : foo ." foo" ;
     : bar ." bar" ;
     ' foo ' bar interpret/compile: foobar1

     foobar1     \ "foo"
     ] foobar1 [ \ "bar"

‘interpret/compile:’ ( int-xt comp-xt "name" -  ) gforth-0.2 "interpret-slash-compile-colon"
   Defines name.
Name execution: execute int-xt.
Name compilation: execute comp-xt.

   There are two kinds of uses for combined words:

   One use of combined words is parsing words that should be
copy-pasteable between interpreted and compiled code; these words should
parse at text-interpret time both in their interpretation and their
compilation semantics (like an immediate word), but then should perform
an action in their interpretation semantics and compile that action in
their compilation semantics, like a normal word.  An example is ‘."’ in
Gforth:

     : ."-int ( 'ccc"' -- )  '"' parse type ;
     : ."-comp ( 'ccc"' -- ) '"' parse postpone sliteral postpone type ;

     ' ."-int ' ."-comp interpret/compile: ."
     ( interpretation 'ccc"' -- ; compilation 'ccc"' -- ; run-time -- )

     ." foo"         \ "foo"
     : foo ." foo" ;
     foo             \ "foo"

   The parsing code is the same in both cases, the action ‘type’ is
directly executed in the interpretation semantics and compiled in the
compilation semantics.  The compilation semantics also contains
‘postpone sliteral’ to transfer the parsed string from
text-interpretation time to the run-time of the action.  This kind of
parse/literal/action split with the use of ‘postpone’ is typical for the
implementations of the compilation semantics of such parsing words, and
the interpretation semantics consist just of the parse and the action
parts.

   We discourage the definition of additional combined words for
copy-pasteability.  They do not work as intended within ‘]]’...‘[[’
(*note Macros::) and their behaviour is also confusing in other
contexts, e.g., when ticking or ‘postpone’ing such a word.  A way to
achieve copy-pasteability without needing to define combined words is
recognizers (*note Recognizers::).  ‘"foo" type’ uses the string
recognizer (*note Default recognizers::) and can be copied and pasted
between interpreted code, compiled code and code inside ‘]]’...‘[[’
without problem.

   On the other hand, combined words are still far better than
‘state’-smart words.(2)

   The other kind of use of combined words is for words like ‘[:’ (*note
Quotations::).  These are not parsing words, but ‘[:’...‘;]’ sequences
should be copy-pasteable between interpreted and compiled code; the
whole sequence pushes an xt at its run-time.  At text-interpret time, it
restores the state at the end to what it was at the start.  Ideally we
would find a clean way to implement all this without needing combined
words, but for now the implementation is pretty messy, including
combined words.

   Some people also have the idea to use combined words for
optimization.  However, the resulting words do not work as intended with
‘[compile]’ (*note Macros::).  Gforth has a better mechanism for
optimization: ‘set-optimizer’ (*note User-defined compile-comma::).

   Some people worry about the aesthetics of ‘interpret/compile:’ and
have proposed alternative syntaxes, and the following ones are supported
in Gforth:

     : foobar2
       ." foo" ;
     [: ." bar" ;] set-compsem

     foobar2     \ "foo"
     ] foobar2 [ \ "bar"

     : foobar3
       ." foo" ;
     compsem:
       ." bar" ;

     foobar3     \ "foo"
     ] foobar3 [ \ "bar"

     : foobar4
       ." bar" ;
     intsem:
       ." foo" ;

     foobar4     \ "foo"
     ] foobar4 [ \ "bar"

   You can use ‘where’ (*note Locating uses of a word::) to find out how
rarely which syntax is used in Gforth.

‘set-compsem’ ( xt -  ) gforth-experimental
   change compilation semantics of the last defined word

‘compsem:’ ( -  ) gforth-experimental "comp-sem-colon"
   Changes the compilation semantics of the current definition to
perform the definition starting at the ‘compsem:’.

‘intsem:’ ( -  ) gforth-experimental "int-sem-colon"
   The current definition's compilation semantics are changed to perform
its interpretation semantics.  Then its interpretation semantics are
changed to perform the definition starting at the ‘intsem:’ (without
affecting the compilation semantics).  Note that if you then call
‘immediate’, the compilation semantics are changed to perform the word's
new interpretation semantics.

   ---------- Footnotes ----------

   (1) Some people call combined words "NDCS", but immediate words also
have non-default compilation semantics

   (2) ‘State’-smart words are immediate words that do ‘state’-dependent
things at run-time.  For a more detailed discussion of this topic, see
M.  Anton Ertl, ‘‘State’-smartness--Why it is Evil and How to Exorcise
it (https://www.complang.tuwien.ac.at/papers/ertl98.ps.gz)’, EuroForth
'98.


File: gforth.info,  Node: Tokens for Words,  Next: Compiling words,  Prev: Interpretation and Compilation Semantics,  Up: Words

6.15 Tokens for Words
=====================

This section describes the creation and use of tokens that represent
words.

* Menu:

* Execution token::             represents execution/interpretation semantics
* Name token::                  represents named words
* Compilation token::           represents compilation semantics


File: gforth.info,  Node: Execution token,  Next: Name token,  Prev: Tokens for Words,  Up: Tokens for Words

6.15.1 Execution token
----------------------

An “execution token” (_xt_) represents some behaviour of a word.  You
can use ‘execute’ to invoke the behaviour represented by the xt and
‘compile,’ (*note Macros::) to compile it into the current definition.
Other uses include deferred words (*note Deferred Words::).

   In particular, there is _the_ execution token of a word that
represents its interpretation semantics (*note Interpretation and
Compilation Semantics::).

   For a named word x, you can use ‘`x’ to get its execution token:

     5 `. ( n xt )
     execute ( )        \ "5"
     : foo `. execute ;
     5 foo              \ "5"

   However, the tick-recognizer that recognizes the ‘`’ prefix is a
Gforth extension, so you may prefer to use the Standard Forth words:

‘'’ ( "name" - xt  ) core "tick"
   xt represents name's interpretation semantics.

‘[']’ ( compilation. "name" - ; run-time. - xt  ) core "bracket-tick"
   xt represents name's interpretation semantics.

   These are parsing words (whereas ‘`x’ is treated as a literal by a
recognizer), and you may find the behaviour in interpreted and compiled
code unintuitive:

     5 ' .   ( n xt )
     execute ( )          \ "5"

     : foo ['] . ;
     5 foo execute        \ "5"

     : bar ' dup ;
     5 bar . drop execute \ "5"

   ‘'’ parses at run-time, so if you put ‘'’ in a colon definition, as
in ‘bar’, it does not consume the next word in the colon definition, but
the next word at run-time (i.e., the ‘.’ in the invocation of ‘bar’).
If you want to push the xt of x inside a colon definition, write ‘`x’ or
‘['] x’.

   Gforth's ‘`x’, ‘'’ and ‘[']’ warn when you use them on compile-only
words, because such usage may be non-portable between different Forth
systems.

   You get the xt of the most recently defined word with ‘latestxt’
(*note Anonymous Definitions::).  For words defined using ‘noname’, this
is the usual way of getting a token.

   For words defined with ‘:noname’, the definition already pushes the
xt, so you do not need to use ‘latestxt’ for ‘:noname’-defined words.

     :noname ." hello" ;
     execute

   An xt occupies one cell and can be manipulated like any other cell.

   In Standard Forth the xt is just an abstract data type (i.e., defined
by the operations that produce or consume it).  The concrete
implementation (since Gforth 1.0) is the body address (for old hands:
PFA) of the word; in Gforth 0.7 and earlier, the xt was implemented as
code field address (CFA, 2 cells before the PFA).

‘execute’ ( xt - ) core "execute"
   Perform the semantics represented by the execution token, xt.

‘execute-exit’ ( compilation - ; run-time xt nest-sys -  ) gforth-1.0
   Execute ‘xt’ and return from the current definition, in a
tail-call-optimized way: The return address ‘nest-sys’ and the locals
are deallocated before executing ‘xt’.

‘perform’ ( a-addr - ) gforth-0.2 "perform"
   ‘@ execute’.

   ‘[Noop]’ is sometimes used as a placeholder execution token:

‘[noop]’ ( -  ) gforth-experimental "bracket-noop"
   Does nothing, both when executed and when compiled.

‘noop’ ( - ) gforth-0.2 "noop"
   Does nothing.  However, code generation does not optimize it away;
use ‘[noop]’ for that.


File: gforth.info,  Node: Name token,  Next: Compilation token,  Prev: Execution token,  Up: Tokens for Words

6.15.2 Name token
-----------------

A “name token” (nt) represents a word, primarily a named word, but in
Gforth since 1.0 unnamed words have a name token, too.

   The name token is a cell-sized abstract data type that occurs as
argument or result of the words below.

   The difference between name token and execution token is that an
execution token represents one behaviour, whereas a name token
represents a word and all its properties, in particular its name and its
behaviours (interpretation semantics, compilation semantics, possibly
‘TO word’ semantics, etc.)

   You get the nt of a word x with ‘``x’ (since Gforth 1.0) or with

‘find-name’ ( c-addr u - nt | 0  ) gforth-0.2
   Find the name c-addr u in the current search order.  Return its nt,
if found, otherwise 0.

‘find-name-in’ ( c-addr u wid - nt | 0  ) gforth-1.0
   Find the name c-addr u in the word list wid.  Return its nt, if
found, otherwise 0.

‘latest’ ( - nt|0  ) gforth-0.6
   If the most recent word defined in the current section has a name, nt
is its name token; otherwise, return 0.

‘latestnt’ ( - nt  ) gforth-1.0
   nt is the name token of the most recent word (named or unnamed)
defined in the current section.

‘>name’ ( xt - nt|0  ) gforth-0.2 "to-name"
   For most words (all words with the default implementation of
‘name>interpret’), ‘>name’ is the inverse of ‘name>interpret’: for these
words ‘nt name>interpret’ produces xt.  For the other words ‘name’
produces an nt for which ‘nt default-name>int’ produces xt.  Returns 0
if xt is not an xt (using a heuristic check that has a small chance of
misidentifying a non-xt as xt), or (before Gforth 1.0) if xt is of an
unnamed word.  As of Gforth 1.0, unnamed words have nts, too, and
‘>name’ produces an nt for xts of unnamed words.

‘xt>name’ ( xt - nt  ) gforth-1.0 "xt-to-name"
   If xt is an execution token, produces the same nt as ‘>name’.
Otherwise, nt is an arbitrary value.

   You can get all the nts in a wordlist with

‘traverse-wordlist’ ( ... xt wid - ...  ) tools-ext
   perform xt ( ...  nt - f ...  )  once for every word nt in the
wordlist wid, until f is false or the wordlist is exhausted.  xt is free
to use the stack underneath.

   You can use the nt to access the interpretation and compilation
semantics of a word, its name, and the next word in the wordlist:

‘name>interpret’ ( nt - xt  ) tools-ext "name-to-interpret"
   xt represents the interpretation semantics of the word nt.

‘name>compile’ ( nt - xt1 xt2  ) tools-ext "name-to-compile"
   xt1 xt2 is the compilation token for the word nt (*note Compilation
token::).

‘name>string’ ( nt - addr u  ) tools-ext "name-to-string"
   addr count is the name of the word represented by nt.

‘id.’ ( nt -  ) gforth-0.6 "i-d-dot"
   Print the name of the word represented by NT.

‘.id’ ( nt -  ) gforth-0.6 "dot-i-d"
   F83 name for ‘id.’.

‘compile-only?’ ( nt - flag  ) gforth-1.0 "compile-only-question"
   true if nt is marked as compile-only.

‘obsolete?’ ( nt - flag  ) gforth-1.0 "obsolete-question"
   true if nt is obsolete, i.e., will be removed in a future version of
Gforth.

‘name>link’ ( nt1 - nt2 / 0  ) gforth-1.0 "name-to-link"
   For a word nt1, returns the previous word nt2 in the same wordlist,
or 0 if there is no previous word.

   As a usage example, the following code lists all the words in
‘forth-wordlist’ with non-default compilation semantics (including
immediate words):

     : ndcs-words ( wid -- )
       [: dup name>compile ['] compile, <> if over id. then 2drop true ;]
       swap traverse-wordlist ;

     forth-wordlist ndcs-words

   This code assumes that a word has default compilation semantics if
the xt part of its compilation token is the xt of ‘compile,’.

   Since Gforth 1.0 (but not in earlier versions or many other Forth
systems), nameless words (*note Anonymous Definitions::) have nts and
compilation semantics, and ‘name>string’ works on them (producing a
zero-length name).  They are not in a wordlist, however.  You can get
the nt of a nameless word with ‘latestnt’.

   Since Gforth 1.0, for most words the concrete implementation of their
nt has the same numeric value as the xt that ‘name>interpret’ produces
for the nt.  However for word w that is a synonym, alias, or is defined
with ‘interpret/compile:’, ‘intsem:’ etc., the xt produced by
‘name>interpret’ has a different numeric value than the nt (and using
‘>name’ on these xts will not produce the nt of w).  Therefore, you
cannot use xts and nts interchangeably, even if you are prepared to
write code specific to Gforth 1.0.

   The closest thing to the nt in classic Forth systems like fig-Forth
is the name field address (NFA), but there are significant differences:
in older Forth systems each word has a unique NFA, LFA, CFA and PFA (in
this order, or LFA, NFA, CFA, PFA) and there are words for getting from
one to the next.  By contrast, in Gforth in general there is an n:1
relation between name tokens and the xt representing interpretation
semantics; i.e., when you pass different nts to ‘name>interpret’, the
result may be the same xt.

   Another difference is that the NFA usually points to the start of the
header, whereas the nt in Gforth 1.0 points to the body (and header
fields are accessed with a negative offset).

   Moreover, all of the header fields of the old systems correspond to
fields in Gforth, but Gforth 1.0 has a few additional ones (*note Header
fields::).


File: gforth.info,  Node: Compilation token,  Prev: Name token,  Up: Tokens for Words

6.15.3 Compilation token
------------------------

The compilation semantics of a word is represented by a “compilation
token” consisting of two cells: xt1 xt2.

   You get the compilation token of, e.g., ‘if’ in a standard way with
‘name>compile’, e.g., ‘s" if" find-name name>compile’, but there are
also parsing words to get the compilation token of a word:

‘[COMP']’ ( compilation "name" - ; run-time - xt1 xt2  ) gforth-0.2 "bracket-comp-tick"
   Compilation token xt1 xt2 represents name's compilation semantics.

‘COMP'’ ( "name" - xt1 xt2  ) gforth-0.2 "comp-tick"
   Compilation token xt1 xt2 represents name's compilation semantics.

   You can perform the compilation semantics represented by the
compilation token with ‘execute’.  ‘Execute’ing the compilation token
consumes the whole compilation token and there is possibly an additional
stack effect determined by the represented compilation semantics (e.g.,
‘execute’ing the compilation token of ‘if’ pushes an orig).

   You can compile the compilation semantics represented by a
compilation token with ‘postpone,’.  I.e., ‘``x name>compile postpone,’
is equivalent to ‘postpone x’.

‘postpone,’ ( xt1 xt2 -  ) gforth-0.2 "postpone-comma"
   Compile the compilation semantics represented by the compilation
token xt1 xt2.

   Implementation: The top cell xt2 of a compilation token xt1 xt2 is an
execution token that represents either ‘execute’ or ‘compile,’(1) Xt1 is
more specific to the represented word; for most words, it is the xt
produced by ‘name>interpret’, but there are exceptions, e.g., for words
defined with ‘interpret/compile:’.

   ---------- Footnotes ----------

   (1) Depending upon the compilation semantics of the word.  If the
word has default compilation semantics, xt2 will represent ‘compile,’.
Otherwise (e.g., for immediate words), xt2 will represent ‘execute’.


File: gforth.info,  Node: Compiling words,  Next: The Text Interpreter,  Prev: Tokens for Words,  Up: Words

6.16 Compiling words
====================

In contrast to most other languages, Forth has no strict boundary
between compilation and run-time.  E.g., you can run arbitrary code
between defining words (or for computing data used by defining words
like ‘constant’).  Moreover, ‘Immediate’ (*note Interpretation and
Compilation Semantics::) and ‘[’...‘]’  (*note Literals::) allow running
arbitrary code while compiling a colon definition (exception: any
dictionary space you allot must be in a different section, *note
Sections::).

* Menu:

* Literals::                    Compiling data values
* Macros::                      Compiling words


File: gforth.info,  Node: Literals,  Next: Macros,  Prev: Compiling words,  Up: Compiling words

6.16.1 Literals
---------------

The simplest and most frequent example is to compute a literal during
compilation.  E.g., the following definition prints an array of strings,
one string per line:

     : .strings ( addr u -- ) \ gforth
         2* cells bounds U+DO
             cr i 2@ type
         2 cells +LOOP ;

   With a simple-minded compiler like Gforth 0.7, this computes ‘2
cells’ on every loop iteration.  You can compute this value at compile
time and compile it into the definition like this:

     : .strings ( addr u -- ) \ gforth
         2* cells bounds U+DO
             cr i 2@ type
         [ 2 cells ] literal +LOOP ;

   ‘[’ switches the text interpreter to interpret state (you will get an
‘ok’ prompt if you type this example interactively and insert a newline
between ‘[’ and ‘]’), so it performs the interpretation semantics of ‘2
cells’; this computes a number.  ‘]’  switches the text interpreter back
into compile state.  It then performs ‘Literal’'s compilation semantics,
which are to compile this number into the current word.  You can
decompile the word with ‘see .strings’ to see the effect on the compiled
code.(1)

   You can also optimize the ‘2* cells’ into ‘[ 2 cells ] literal *’ in
this way.(2)

‘[’ ( -  ) core "left-bracket"
   Enter interpretation state.  Immediate word.

‘]’ ( -  ) core "right-bracket"
   Enter compilation state.

‘Literal’ ( compilation n - ; run-time - n  ) core
   Compilation semantics: ( n - ) compile the run-time semantics.
Run-time Semantics: ( - n ).
Interpretation semantics: not defined in the standard.

‘lit,’ ( x -  ) gforth-1.0 "lit-comma"
   This is a non-immediate variant of ‘literal’
Execution semantics: ( x - ) Compile the following semantics:
Compiled semantics: ( - x ).

‘ALiteral’ ( compilation addr - ; run-time - addr  ) gforth-0.2
   Works like ‘literal’, but (when used in cross-compiled code) tells
the cross-compiler that the literal is an address.

‘]L’ ( compilation: n - ; run-time: - n  ) gforth-0.5 "right-bracket-L"
   equivalent to ‘] literal’

   There are also words for compiling other data types than single cells
as literals:

‘2Literal’ ( compilation w1 w2 - ; run-time  - w1 w2  ) double "two-literal"
   Compilation semantics: ( w1 w2 - ) compile the run-time semantics.
Run-time Semantics: ( - w1 w2 ).
Interpretation semantics: not defined in the standard.

‘2lit,’ ( x1 x2 -  ) gforth-1.0 "two-lit-comma"
   This is a non-immediate variant of ‘2literal’
Execution semantics: ( x1 x2 - ) Compile the following semantics:
Compiled semantics: ( - x1 x2 ).

‘FLiteral’ ( compilation r - ; run-time - r  ) floating "f-literal"
   Compilation semantics: ( r - ) compile the run-time semantics.
Run-time Semantics: ( - r ).
Interpretation semantics: not defined in the standard.

‘flit,’ ( r -  ) gforth-1.0 "flit-comma"
   This is a non-immediate variant of ‘fliteral’
Execution semantics: ( r - ) Compile the following semantics:
Compiled semantics: ( - r ).

‘SLiteral’ ( Compilation c-addr1 u - ; run-time - c-addr2 u  ) string
   Compilation semantics: ( c-addr1 u - ) Copy the string described by
c-addr1 u to c-addr2 u and compile the run-time semantics.
Run-time Semantics: ( - c-addr2 u ).
Interpretation semantics: not defined in the standard.

‘slit,’ ( c-addr1 u -  ) gforth-1.0 "slit-comma"
   This is a non-immediate variant of ‘sliteral’
Execution semantics: ( c-addr1 u - ) Copy the string described by
c-addr1 u to c-addr2 u and compile the following semantics:
Compiled semantics: ( - c-addr2 u ).

   You might be tempted to pass data from outside a colon definition to
the inside on the data stack.  The straightforward approach to do this
does not work, because ‘:’ pushes a colon-sys, making stuff below
unaccessible.  E.g., this does not work:

     5 : foo literal ; \ error: "unstructured"

   Instead, you have to pass the value in some other way, e.g., through
the return stack:

     5 >r : foo [ r> ] literal ;

   The interpretive use of the return stack is Gforth-specific; the use
of a variable also works on other Forth systems:

     variable temp
     5 temp !
     : foo [ temp @ ] literal ;

   ---------- Footnotes ----------

   (1) In Gforth 1.0, the compiler performs constant folding, and ‘see’
of the original ‘.strings’ will show the same effect.

   (2) In Gforth 1.0, ‘2 cells *’ is sufficient.


File: gforth.info,  Node: Macros,  Prev: Literals,  Up: Compiling words

6.16.2 Macros
-------------

‘Literal’ and friends compile data values into the current definition.
You can also write words that compile other words into the current
definition.  E.g.,

     : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
       POSTPONE + ;

     : foo ( n1 n2 -- n )
       [ compile-+ ] ;
     1 2 foo .

   This is equivalent to ‘: foo + ;’ (‘see foo’ to check this).  What
happens in this example?  ‘Postpone’ compiles the compilation semantics
of ‘+’ into ‘compile-+’; later the text interpreter executes ‘compile-+’
and thus the compilation semantics of +, which compile (the execution
semantics of) ‘+’ into ‘foo’.

‘postpone’ ( "name" -  ) core
   Compiles the compilation semantics of name.

   Compiling words like ‘compile-+’ are usually immediate (*note How to
define immediate words::) so you do not have to switch to interpret
state to execute them; modifying the last example accordingly produces:

     : [compile-+] ( compilation: --; interpretation: -- )
       \ compiled code: ( n1 n2 -- n )
       POSTPONE + ; immediate

     : foo ( n1 n2 -- n )
       [compile-+] ;
     1 2 foo .

   You will occasionally find the need to POSTPONE several words;
putting POSTPONE before each such word is cumbersome, so Gforth provides
a more convenient syntax: ‘]] ... [[’.  This allows us to write
‘[compile-+]’ as:

     : [compile-+] ( compilation: --; interpretation: -- )
       ]] + [[ ; immediate

‘]]’ ( -  ) gforth-0.6 "right-bracket-bracket"
   Switch into postpone state: All words and recognizers are processed
as if they were preceded by ‘postpone’.  Postpone state ends when ‘[[’
is recognized.

   The unusual direction of the brackets indicates their function: ‘]]’
switches from compilation to postponing (i.e., compilation of
compilation), just like ‘]’ switches from immediate execution
(interpretation) to compilation.  Conversely, ‘[[’ switches from
postponing to compilation, ananlogous to ‘[’ which switches from
compilation to immediate execution.

   The real advantage of ‘]] ’...‘ [[’ becomes apparent when there are
many words to POSTPONE. E.g., the word ‘compile-map-array’ (*note
Advanced macros Tutorial::) can be written much shorter as follows:

     : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
     \ at run-time, execute xt ( ... x -- ... ) for each element of the
     \ array beginning at addr and containing u elements
       {: xt: xt :}
       ]] cells over + swap ?do
         i @ xt 1 cells +loop [[ ;

     : sum-array ( addr u -- n )
       0 [ ' + compile-map-array ] ;

   If you then say ‘see sum-array’, it shows the following code:

     : sum-array
       #0 over + swap ?do
         i @ + #8 +LOOP
     ;

   In addition to ‘]]’...‘[[’, this example shows off some other
features:

   • It uses a defer-flavoured (defined with ‘xt:’) local ‘xt’;
     mentioning such a local inside ‘]]’...‘[[’ results in ‘compile,’ing
     the xt in the local, i.e., ‘]] xt [[’ is equivalent to ‘action-of
     xt compile,’.

   • Not used in the example, but related to the previous point: For a
     normal (value-flavoured) local, using it inside ‘]]’...‘[[’
     compiles the value of the local, i.e., ‘]] x [[’ is equivalent to
     ‘x ]] literal [[’.

   • It uses the literal ‘1’ inside ‘]]’...‘[[’.  This results in
     ‘postpone’ing the ‘1’, i.e.  compiling it when ‘compile-map-array’
     is run.  ‘]] 1 [[’ is equivalent to ‘1 ]] literal [[’.

   • When ‘compile-map-array’ is run (while ‘sum-array’ is compiled), ‘1
     cells’ is compiled and optimized into ‘#8’ by Gforth's constant
     folding.

   Note that parsing words such as ‘s\"’ don't parse at postpone time
and therefore not inside ‘]]’...‘[[’.  Instead of ‘s\" mystring\n"’ you
can use the string recognizer and write ‘"mystring\n"’, which works
inside ‘]]’...‘[[’.  Likewise, the parsing word ‘[']’ does not parse
inside ‘]]’...‘[[’ while the recognizer notation starting with ‘`’ works
inside ‘]]’...‘[[’.

   But if you prefer to use ‘s\"’ (or have a parsing word that has no
recognizer replacement), you can do it by switching back to compilation:

     ]] ... [[ s\" mystring\n" ]] sliteral ... [[

   Definitions of ‘]]’ and friends in Standard Forth are provided in
‘compat/macros.fs’.

   Immediate compiling words are similar to macros in other languages
(in particular, Lisp).  The important differences to macros in, e.g., C
are:

   • You use the same language for defining and processing macros, not a
     separate preprocessing language and processor.

   • Consequently, the full power of Forth is available in macro
     definitions.  E.g., you can perform arbitrarily complex
     computations, or generate different code conditionally or in a loop
     (e.g., *note Advanced macros Tutorial::).  This power is very
     useful when writing a parser generators or other code-generating
     software.

   • Macros defined using ‘postpone’ etc.  deal with the language at a
     higher level than strings; name binding and other resolutions
     happen at macro definition time, so you can avoid the pitfalls of
     name collisions that can happen in C macros.  Of course, Forth is a
     liberal language and also allows you to define text-based macros
     using ‘evaluate’ (see below).

   You may want the macro to compile a number into a word.  The word to
do it is ‘literal’, but you have to ‘postpone’ it, so its compilation
semantics take effect when the macro is executed, not when it is
compiled:

     : [compile-5] ( -- ) \ compiled code: ( -- n )
       5 POSTPONE literal ; immediate

     : foo [compile-5] ;
     foo .

   A more convenient, but less portable way to write ‘[compile-5]’ is:

     : [compile-5] ( -- ) \ compiled code: ( -- n )
       ]] 5 [[ ; immediate

   You may want to pass parameters to a macro, that the macro should
compile into the current definition.  If the parameter is a number, then
you can use ‘postpone literal’ (similar for other values).

   If you want to pass a word that is to be compiled, the usual way is
to pass an execution token and ‘compile,’ it:

     : twice ( xt -- ) \ compiled code: ... -- ...
       dup compile, compile, ;

     : 2+ ( n1 -- n2 )
       [ ' 1+ twice ] ;

‘compile,’ ( xt -  ) core-ext "compile-comma"
   Append the semantics represented by xt to the current definition.
When the resulting code fragment is run, it behaves the same as if xt is
‘execute’d.

   A more convenient, but less portable way to write ‘twice’ is:

     : twice {: xt: xt -- :} \ compiled code: ... -- ...
       ]] xt xt [[ ;

   An alternative that allows you to pass the compilation semantics as
parameters is to use the compilation token (*note Compilation token::).
The same example in this technique:

     : ctwice ( ... ct -- ... ) \ compiled code: ... -- ...
       2dup 2>r execute 2r> execute ;

     : 2+ ( n1 -- n2 )
       [ ``1+ name>compile ctwice ] ;

   In particular, you want to pass the compilation token and ‘execute’
it in case of words without interpretation semantics or with non-default
and non-immediate compilation semantics (i.e., not for ‘1+’).

   In the example above ‘2>r’ and ‘2r>’ ensure that ‘ctwice’ works even
if the executed compilation semantics has an effect on the data stack.

   You can also define complete definitions with these words; this
provides an alternative to using ‘does>’ (*note User-defined Defining
Words::).  E.g., instead of

     : curry+ ( n1 "name" -- )
         CREATE ,
     DOES> ( n2 -- n1+n2 )
         @ + ;

   you could define

     : curry+ ( n1 "name" -- )
       \ name execution: ( n2 -- n1+n2 )
       >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;

     -3 curry+ 3-
     see 3-

   The sequence ‘>r : r>’ is necessary, because ‘:’ puts a colon-sys on
the data stack that makes everything below it unaccessible.

   A more convenient, but less portable way to define ‘curry+’ is:

     : curry+ ( n1 "name" -- )
       \ name execution: ( n2 -- n1+n2 )
       {: n1 :} : ]] n1 + ; [[ ;

   This way of writing defining words is sometimes more, sometimes less
convenient than using ‘does>’ (*note Advanced does> usage example::).
One advantage of this method is that it can be optimized better, because
the compiler knows that the value compiled with ‘literal’ is fixed,
whereas the data associated with a ‘create’d word can be changed.  But
if you use ‘does>’/‘set-does>’ with ‘set-optimizer’, the resulting code
will be at least as good, and the defined word will consume less memory.

‘[compile]’ ( compilation "name" - ; run-time ? - ?  ) core-ext "bracket-compile"
   Legacy word.  Use ‘postpone’ instead.  Works like ‘postpone’ if name
has non-default compilation semantics.  If name has default compilation
semantics (i.e., is a normal word), compiling ‘[compile] name’ is
equivalent to compiling name (i.e.  ‘[compile]’ is redundant in this
case).

‘in-colon-def?’ ( - flag  ) gforth-experimental "in-colon-def-question"
   flag is true if and only if there is an active colon definition to
which ‘compile,’ and friends would append code.

   Some people argue in favour of ‘evaluate’-based macros like:

     : my2dup s" over over" evaluate ; immediate

   We do not recommend using this technique, because it moves a number
of decisions to macro-use time, when the setup may be different than you
intended:

   • The recognizer order may be different.  This will usually not make
     a difference, but in case of doubt, you can use ‘rec-meta’ to
     reduce potential ambiguity.

   • The search order and the contents of individual wordlists may be
     different.  You can use ‘rec-scope’ to eliminate the search order
     dependency, but there is no easy way to eliminate the changes in
     the wordlists, except to avoid ‘evaluate’-based macros altogether.

   • ‘State’ may be different, and if this influences the behaviour of
     the macro, it will be ‘state’-smart (*note state-smartness::).

   • ‘Base’ may be different, potentially changing the meaning of
     multi-digit numbers.  Use number prefixes to avoid this problem.

   An advantage of an ‘evaluate’-based macros is that you may be able to
use it interpretively, whereas ‘postpone’-based macros are useful only
inside colon definitions and other macros.  Our recommended alternative
is to instead use an inline definition (*note Inline Definitions::) or
define a colon definition and an optimizer for it (e.g., see the
‘my2dup’ examples in *note User-defined compile-comma::).


File: gforth.info,  Node: The Text Interpreter,  Next: The Input Stream,  Prev: Compiling words,  Up: Words

6.17 The Text Interpreter
=========================

The text interpreter processes Forth source code, and performs the
semantics of the words in the source code.  The text interpreter works
on Forth source code coming from the standard input (the “user input
device” in Forth standard terminology), from a file (through ‘included’
and friends), from ‘evaluate’, or from a ‘load’ed block.

   The text interpreter is also called the outer interpreter, in
contrast to the inner interpreter of traditional Forth implementations
which interprets the threaded code that is the output of the Forth
compiler on these implementations; many Forth systems nowadays compile
to native code and have no inner interpreter.  Concerning Gforth's
approach, *note Engine::.

   The text interpreter works line by line (using ‘refill’).  Therefore,
most parsing words (e.g., ‘'’ and ‘s"’) only try to find their parsed
arguments in the current line; if a word parses across line boundaies,
that is stated explicitly in the documentation of the word.  However, a
block is interpreted like one line, their division into "lines" is just
for display purposes; ‘Evaluate’ interprets the string as a whole.  The
current line/block/string is available to programs through ‘source’, and
its content is valid until the current line is changed; it has to be
treated as read-only region.

   Within a line, the text interpreter parses for white-space-delimited
words (with ‘parse-name’).  The text interpreter's position within the
line is stored in ‘>in’, and by changing ‘>in’, a program can change
where the text interpreter or parsing word continues to parse.

   The text interpreter then tries to recognize the word with one of the
recognizers in the system recognizer sequence.  On success, this
produces a _translation_ (a translation token and additional data),
which represents the recognized word on the stack, as far as the text
interpreter is concerned (*note Defining recognizers::).

   It then performs the interpretation, compilation, or postponing
action of the translation, depending on the state of the text
interpreter: Is it inside ‘]]’...‘[[’?  If not, what is the value of
‘state’?  E.g., when a word from the search order is recognized, and the
text interpreter is in compile state, the compilation semantics of this
word will be performed.  This translation action may perform additional
parsing, e.g., when the recognizer has recognized a parsing word.  If no
recognizer recognizes the word, the text interpreter ‘throw’s -13
("undefined word").

   The text interpreter then continues to parse, recognize, and
translate words.  At the end of the line, it ‘refill’s and continues
with the next line.  At the end of an input source (e.g., at the end of
a file), the text interpreter returns to its caller, and that caller
(e.g., ‘included’) restores the previous input stream before returning
itself.

   If an exception is not caught earlier, the same unnesting of input
streams and the associated calls are performed.  If not ‘catch’
intervenes, the ‘throw’ is eventually caught by the system.  In Gforth,
the system then prints an error message with a backtrace of both the
call stack and the stack of nested input streams (*note Error
messages::).  In interactive mode, Gforth then calls a text interpreter
for the user input device, while in scripting mode (while processing OS
command-line arguments, *note Scripting mode::) Gforth then terminates
with a non-zero exit code.

   You can read about this in more detail in *note Input Sources::.

‘source’ ( - c-addr u  ) core "source"
   c-addr u is the input buffer, i.e., the line/block/‘evaluate’d-string
currently processed by the text interpreter

‘>in’ ( - addr  ) core "to-in"
   Addr contains the offset into ‘source’ where the text interpreter or
parsing words parse next.  A word can write to addr in order to change
what is parsed next.  Addr can be different for different tasks, and for
different input streams within a task.

‘tib’ ( - addr  ) gforth-obsolete "t-i-b"
   Addr is the start of the input buffer.  OBSOLETE: This word has been
de-standardized in Forth-2012.  ‘source’ supersedes the function of this
word.

‘#tib’ ( - addr  ) gforth-obsolete "number-t-i-b"
   Addr is the address of a cell containing the number of characters in
the terminal input buffer.  Addr can be different for different tasks,
and for different input streams within a task.  OBSOLETE: This word has
been de-standardized in Forth-2012.  ‘source’ supersedes the function of
this word.

* Menu:

* Input Sources::
* Interpret/Compile states::
* Interpreter Directives::
* Recognizers::
* Text Interpreter Hooks::


File: gforth.info,  Node: Input Sources,  Next: Interpret/Compile states,  Prev: The Text Interpreter,  Up: The Text Interpreter

6.17.1 Input Sources
--------------------

By default, the text interpreter processes input from the user input
device (the keyboard) when Forth starts up.  The text interpreter can
process input from any of these sources:

   • The user input device - the keyboard.
   • A file, using the words described in *note Forth source files::.
   • A text string, using ‘evaluate’; a variant of this is when Gforth
     processes an OS command line argument of the form ‘-e string’.
   • A block, *note Blocks::.

   A program can identify the current input device from the values of
‘source-id’ and ‘blk’.

‘evaluate’ ( ... addr u - ...  ) core,block
   Save the current input source.  Store ‘-1’ in ‘source-id’ and ‘0’ in
‘blk’.  Set ‘>IN’ to ‘0’ and make the string c-addr u the input source
and input buffer.  Tex-interpret the input buffer.  When the parse area
is empty, restore the input source.

‘source-id’ ( - 0 | -1 | fileid  ) core-ext,file "source-i-d"
   Return 0 (the input source is the user input device), -1 (the input
source is a string being processed by ‘evaluate’) or a fileid (the input
source is the file specified by fileid).

‘blk’ ( - addr  ) block "b-l-k"
   addr contains the current block number (or 0 if the current input
source is not a block).

‘save-input’ ( - x1 .. xn n  ) core-ext
   The n entries xn - x1 describe the current state of the input source
specification, in some platform-dependent way that can be used by
‘restore-input’.

‘restore-input’ ( x1 .. xn n - flag  ) core-ext
   Attempt to restore the input source specification to the state
described by the n entries xn - x1.  flag is true if the restore fails.
In Gforth 1.0, it is possible to save and restore between different
active input streams.  Note that closing the input streams must happen
in the reverse order as they have been opened, but as long as they are
both active, everything is allowed.  These Gforth versions only produce
non-zero flags as results of ‘catch’ing some exception, and the flag
itself is the ‘throw’n ball and can be re‘throw’n.

‘query’ ( -  ) gforth-obsolete
   Make the user input device the input source.  Receive input into the
Terminal Input Buffer.  Set ‘>IN’ to zero.  OBSOLETE: This Forth-94 word
has been de-standardized in Forth-2012.  It is superceeded by ‘accept’.


File: gforth.info,  Node: Interpret/Compile states,  Next: Interpreter Directives,  Prev: Input Sources,  Up: The Text Interpreter

6.17.2 Interpret/Compile states
-------------------------------

A standard program is not permitted to change ‘state’ explicitly.
However, it can change ‘state’ implicitly, using the words ‘[’ and ‘]’.
When ‘[’ is executed it switches ‘state’ to interpret state, and
therefore the text interpreter starts interpreting.  When ‘]’ is
executed it switches ‘state’ to compile state and therefore the text
interpreter starts compiling.  The most common usage for these words is
for switching into interpret state and back from within a colon
definition; this technique can be used to compile a literal (for an
example, *note Literals::) or for conditional compilation (for an
example, *note Interpreter Directives::).

‘state’ ( - a-addr  ) core,tools-ext
   Don't use ‘state’!  ‘State’ is the state of the text interpreter, and
ordinary words should work independently of it; in particular, ‘state’
does not tell you whether the interpretation semantics or compilation
semantics of a word are being performed.  See ‘‘State’-smartness-Why it
is evil and how to exorcise it’.  For an alternative to ‘state’-smart
words, see *note How to define combined words::.
A-addr is the address of a cell containing the compilation state flag.
0 => interpreting, -1 => compiling.  A standard program must not store
into ‘state’, but instead use ‘[’ and ‘]’.


File: gforth.info,  Node: Interpreter Directives,  Next: Recognizers,  Prev: Interpret/Compile states,  Up: The Text Interpreter

6.17.3 Interpreter Directives
-----------------------------

These words are usually used in interpret state; typically to control
which parts of a source file are processed by the text interpreter.
There are only a few Standard Forth words, but Gforth supplements these
with a rich set of immediate control structure words to compensate for
the fact that the non-immediate versions can only be used in compile
state (*note Control Structures::).  Typical usage:

     [undefined] \G [if]
       : \G source >in ! drop ; immediate
     [endif]

   So if the system does not define ‘\G’, compile replacement code (with
reduced functionality).

‘[IF]’ ( flag -  ) tools-ext "bracket-if"
   If flag is ‘TRUE’ do nothing (and therefore execute subsequent words
as normal).  If flag is ‘FALSE’, parse and discard words from the parse
area (refilling it if necessary using ‘REFILL’) including nested
instances of ‘[IF]’..  ‘[ELSE]’..  ‘[THEN]’ and ‘[IF]’..  ‘[THEN]’ until
the balancing ‘[ELSE]’ or ‘[THEN]’ has been parsed and discarded.
Immediate word.

‘[ELSE]’ ( -  ) tools-ext "bracket-else"
   Parse and discard words from the parse area (refilling it if
necessary using ‘REFILL’) including nested instances of ‘[IF]’..
‘[ELSE]’..  ‘[THEN]’ and ‘[IF]’..  ‘[THEN]’ until the balancing ‘[THEN]’
has been parsed and discarded.  ‘[ELSE]’ only gets executed if the
balancing ‘[IF]’ was ‘TRUE’; if it was ‘FALSE’, ‘[IF]’ would have parsed
and discarded the ‘[ELSE]’, leaving the subsequent words to be executed
as normal.  Immediate word.

‘[THEN]’ ( -  ) tools-ext "bracket-then"
   Do nothing; used as a marker for other words to parse and discard up
to.  Immediate word.

‘[ENDIF]’ ( -  ) gforth-0.2 "bracket-end-if"
   Do nothing; synonym for ‘[THEN]’

‘[defined]’ ( "<spaces>name" - flag  ) tools-ext "bracket-defined"
   returns true if name is found in current search order.  Immediate
word.

‘[undefined]’ ( "<spaces>name" - flag  ) tools-ext "bracket-undefined"
   returns false if name is found in current search order.  Immediate
word.

‘[IFDEF]’ ( "<spaces>name" -  ) gforth-0.2 "bracket-if-def"
   If name is found in the current search-order, behave like ‘[IF]’ with
a ‘TRUE’ flag, otherwise behave like ‘[IF]’ with a ‘FALSE’ flag.
Immediate word.

‘[IFUNDEF]’ ( "<spaces>name" -  ) gforth-0.2 "bracket-if-un-def"
   If name is not found in the current search-order, behave like ‘[IF]’
with a ‘TRUE’ flag, otherwise behave like ‘[IF]’ with a ‘FALSE’ flag.
Immediate word.

‘[?DO]’ ( n-limit n-index -  ) gforth-0.2 "bracket-question-do"

‘[DO]’ ( n-limit n-index -  ) gforth-0.2 "bracket-do"

‘[LOOP]’ ( -  ) gforth-0.2 "bracket-loop"

‘[+LOOP]’ ( n -  ) gforth-0.2 "bracket-question-plus-loop"

‘[FOR]’ ( n -  ) gforth-0.2 "bracket-for"

‘[NEXT]’ ( n -  ) gforth-0.2 "bracket-next"

‘[I]’ ( run-time - n  ) gforth-0.2 "bracket-i"
   At run-time, ‘[I]’ pushes the loop index of the
text-interpretation-time ‘[do]’ iteration.  If you want to process the
index at text-interpretation time, use ‘INT-[I]’ or perform the
interpretation semantics of ‘[I]’.

‘INT-[I]’ ( - n  ) gforth-1.0 "int-bracket-i"
   Push the loop index of the ‘[do]’ iteration at text-interpretation
time.

‘[BEGIN]’ ( -  ) gforth-0.2 "bracket-begin"

‘[UNTIL]’ ( flag -  ) gforth-0.2 "bracket-until"

‘[AGAIN]’ ( -  ) gforth-0.2 "bracket-again"

‘[WHILE]’ ( flag -  ) gforth-0.2 "bracket-while"

‘[REPEAT]’ ( -  ) gforth-0.2 "bracket-repeat"

   You can use ‘#line’ to change Gforth's idea about the current source
line number and source file.  This is useful in cases where the Forth
file is generated from some other source code file, and you want to get,
e.g.  error messages etc.  that refer to the original source code; then
the Forth-code generator needs to insert ‘#line’ lines in the Forth code
wherever appropriate.

‘#line’ ( "u" "["file"]" -  ) gforth-1.0 "number-line"
   Set the line number to u and (if present) the file name to file.
Consumes the rest of the line.


File: gforth.info,  Node: Recognizers,  Next: Text Interpreter Hooks,  Prev: Interpreter Directives,  Up: The Text Interpreter

6.17.4 Recognizers
------------------

The recognizer concepts factor the central part of the text interpreter:
The processing of one word after its name has been parsed.

   The words and descriptions in this section are those that have found
consensus in the standardization committee and will probably be
standardized.  There are also additional words implemented by Gforth and
described in this section.  Currently this manual does not tell which
words are planned to be standardized and which are not.  If you want to
know that, see ‘Recognizer committee proposal 2025-09-11
(https://forth-standard.org/proposals/recognizer-committee-proposal-2025-09-11?hideDiff#reply-1535)’.

   Most programs just use the text interpreter as-is, and you can skip
this chapter completely in this case, but if you are curious, *note
Default recognizers::.  The next level of recognizer usage is to change
which of the existing recognizers are used and in what order (*note
Recognizer order::).

   You may also want to define a new recognizer; a recognizer produces
an on-stack representation of the recognized string, called a
“translation”, which contains a “translation token”.  You can use
predefined translation tokens for defining your recognizer (*note
Defining recognizers::), or first define a new tranlation token (*note
Defining translation tokens::).  Finally, you may want to process the
translation (*note Performing translation actions::).

* Menu:

* Default recognizers::
* Recognizer order::
* Defining recognizers::
* Defining translation tokens::
* Performing translation actions::


File: gforth.info,  Node: Default recognizers,  Next: Recognizer order,  Prev: Recognizers,  Up: Recognizers

6.17.4.1 Default recognizers
............................

Type ‘recs’ to find out with which recognizers are currently being used
by Gforth.  When invoked in a colon definition after defining a local,
the output of ‘recs’ is (at the time of this writing):

   ‘rec-name ( rec-local search-order ( Forth Forth Root ) ) rec-scope
rec-number rec-float rec-complex rec-string rec-to rec-dtick rec-tick
rec-body rec-env rec-meta’

   Here the notation name ( name1 ...  namen ) indicates that name is a
recognizer sequence that contains the recognizers name1 ...  namen.

   The recognizers in this sequence are:

‘rec-name’
     Recognizes locals and words in the search order.

‘rec-local’
     Recognizes locals.

‘search-order’
     Recognizes words in the search order.  This is shown as recognizer
     sequence, because the wordlists (*note Word Lists::) themselves are
     also recognizers: They implement the recognizer interface (*note
     Defining recognizers::) in addition to working with ‘find-name-in’.

‘rec-scope’
     Recognizes ‘voc1:voc2:..vocn:word’, where voc1 is a vocabulary in
     the search order, voc2 is a vocabulary found in voc1, and so on,
     until word is found in vocn.  The result behaves as if word had
     been found directly in the search order.  Example:
     ‘environment:max-n’.

‘rec-number’
     Single-cell integers (‘#-15’, ‘$-f’), characters (‘'A'’), and
     double-cell integers ‘#-15.’, with or without number prefixes
     (*note Integer and character literals::).

‘rec-float’
     Floating-point numbers (‘1e’, *note Floating-point number and
     complex literals::)

‘rec-complex’
     Complex numbers (‘1e+2ei’, *note Floating-point number and complex
     literals::)

‘rec-string’
     Strings (‘"abc"’, *note String and environment variable
     literals::).

‘rec-to’
     Recognizes ‘->v’ (equivalent to ‘to v’), ‘+>v’ (equivalent to ‘+to
     v’), and ‘'>v’ (equivalent to ‘addr v’), where v is a
     value-flavoured word (*note Values::).  Also recognizes ‘@>d’
     (equivalent to ‘action-of d’), and ‘=>d’ (equivalent to ‘is d’),
     where d is a defer-flavoured word (*note Deferred Words::).

‘rec-dtick’
     Recognizes ‘``word’ and produces the name token of word (*note
     Literals for tokens and addresses::).

‘rec-tick’
     Recognizes ‘`word’ and produces the execution token of word (*note
     Literals for tokens and addresses::).

‘rec-body’
     Recognizes ‘<word>’ for the body address of word and ‘<word+num>’
     for an offset num from the body address of word (*note Literals for
     tokens and addresses::).

‘rec-env’
     Recognizes ‘${env}’ for the string contained at run-time in the
     environment variable env *note String and environment variable
     literals::).

‘rec-meta’
     Recognizes ‘rec?string’, e.g., ‘float?1.’.  ‘Rec-rec’ is a
     recognizer found in the search order (e.g., ‘rec-float’), and this
     recognizer then tries to recognize string (e.g, ‘1.’), and the
     result becomes the result of ‘rec-meta’.  This may be useful in
     cases where you want to use a specific recognizer, e.g., to deal
     with conflicts.

   The order of the recognizers is significant, because they are tried
from left to right, and the first recognizer that recognizes a word is
actually used.  E.g., if you define a local ‘b’, it will supersede
Gforth's predefined word ‘b’.

   In most cases, however, recognizers are designed to avoid matching
the same strings as other recognizers.  E.g., ‘rec-env’ (the environment
variable recognizer) requires braces to avoid a conflict with the number
recognizer when recognizing environment variables like ‘ADD’; i.e.,
‘rec-env’ recognizes ‘${ADD}’, while ‘rec-number’ recognizes ‘$ADD’.

   There are a few cases where Gforth's recognizers can recognize the
same string, however:

   • Word names can be anything, so they can conflict with any other
     recognizer (and locals and the search order are searched before
     other recognizers).

     However, there are no conflicts of Gforth-defined words with
     decimal numbers prefixed with ‘#’ or hex numbers prefixed with ‘$’,
     so it is a good practice to use these prefixes (it's also a good
     idea to make sure that the right ‘base’ is used).  An older
     practice (before number prefixes were introduced) was to prefix hex
     numbers with ‘0’.

     In the code bases we have looked at, starting words with ‘'’ (quote
     aka tick) is much more common than starting them with ‘`’
     (backquote aka backtick), so the recognizers for the xt and the nt
     use ‘`’ to reduce the number of conflicts.

   • Both the integer recognizer ‘rec-number’ and the floating-point
     recognizer ‘rec-float’ recognize, e.g., ‘1.’.  Because ‘rec-number’
     is (by default) earlier, ‘1.’ is recognized as a double-cell
     integer.  If you change the recognizer order to use ‘rec-float’
     first, ‘1.’ is recognized as a floating-point number, but loading
     code written in Standard Forth may behave in a non-standard way.

     In any case, it's a good practice to avoid that conflict in your
     own code as follows: Always write double-cell integers with a
     number prefix, e.g., ‘#1.’; and always write floating-point numbers
     with an ‘e’, e.g., ‘1e’.

   • We have seen a few word names that start with ‘->’.  You can avoid
     a conflict by using ‘to myvalue’ or ‘to?->myvalue’ (the latter
     works with ‘postpone’).

   Note that most Forth systems do not support all the recognizers we
describe above, but ‘rec-name rec-number rec-float’ are relatively
common (even if a system uses a hard-coded text interpreter instead of
the flexible recognizer system).

   You can use ‘locate’ (*note Locating source code definitions::) to
determine which recognizer recognizes a piece of source code.  E.g.:

     locate float?1.

   will show that ‘rec-meta’ recognizes ‘float?1.’.  However, if the
recognizer recognizes a dictionary word (e.g., the scope recognizer),
‘locate’ will show that word.

   Wordlists are also recognizers, as can be seen by the search order
being shown as recognizer sequence containing the wordlists, .  A
wordlist recognizes the words that it contains.  Just ‘execute’ the
wordlist-id, and it will behave as a recognizer:

     "dup" forth-wordlist execute

   produces the same result as

     "dup" rec-name

   Actually, ‘rec-name’ searches all wordlists in the search order; with
the default search order, that finds the ‘dup’ in ‘forth-wordlist’.

‘recs’ ( -  ) gforth-experimental
   Print the system recognizer order, with the first-searched recognizer
leftmost.  For recognizer sequences, first the name is printed, then
‘(’, then the content of the sequence, then ‘)’.  For a deferred word,
the name of the deferred word is shown, not that of the recognizer
inside; if it contains a recognizer sequence, the name of the deferred
word and the contents of the sequence are shown.

   All recognizers produce the translation ‘translate-none’ if they do
not recognize the string.  This is not mentioned every time in the
following descriptions.

‘rec-name’ ( c-addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) a visible local or a
visible named word.  If successful, translation represents the
text-interpretation semantics (interpreting, compiling, postponing) of
that word (see ‘translate-name’).

‘rec-local’ ( c-addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) a visible local.  If
successful, translation represents pushing the value of the local at
run-time (for details *note Gforth locals:: and *note Macros::).

‘rec-scope’ ( c-addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) ‘vocabulary:word’, where
vocabulary is found in the search order.  Otherwise the behaviour is
like that of ‘rec-name’.  The general form can have several vocabularies
preceding word, separated by ‘:’; the first (leftmost) vocabulary is
found in the search order, the second in the first, etc.  word is looked
up in the rightmost vocabulary.

‘rec-number’ ( c-addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) a single or double number
(without or with prefix), or a character.  If successful, translation
represents pushing that number at run-time (see ‘translate-cell’ and
‘translate-dcell’).  If and only if ‘.-is-dcell?’ is true, strings
without prefix that contain a dot are recognized as double numbers.

‘.-is-dcell?’ ( - flag  ) gforth-experimental "dot-is-dcell-question"
   If this user flag is true (default), ‘rec-number’ recognizes numbers
without prefix that contain a decimal point as double-cell numbers.
Otherwise ‘rec-number’ does not recognize the number, and, if present,
‘rec-float’ will recognize it as a floating-point number.
‘to .-is-dcell?’ run-time: ( x - ) If x=0 change the value of
‘.-is-dcell?’ to false, otherwise to true.

‘rec-float’ ( c-addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) a floating-point number,
translation represents pushing that number at run-time (see
‘translate-float’).  For recognizing a string as a float, Gforth
requires decimal ‘base’; it also requires the string to contain an
exponent (‘e’ followed by an optional sign and 0 or more exponent
digits) or a decimal point (the syntax with the decimal point only is
shadowed by the double-cell syntax by default, see ‘rec-number’); in
Gforth there can also be an SI prefix (e.g., ‘M’) instead of the decimal
point, but then no ‘e’ is allowed.  Examples: ‘1234e’, ‘1234.’,
‘1.234e3’, ‘12340e-1’, ‘1k234’.

‘rec-complex’ ( c-addr u - translation  ) gforth-experimental
   A complex number has the format ‘a+bi’, where a and b are floating
point numbers including their signs.  If c-addr u is a complex number,
translation represents pushing that number at run-time (see
‘translate-complex’).

‘rec-string’ ( c-addr u - translation  ) gforth-experimental
   A string starts and ends with ‘"’ and may contain escaped characters,
including ‘\"’ (*note String and character literals::).  If c-addr u is
the start of a string, the translation represents parsing the rest of
the string, if necessary, converting the escaped characters, and pushing
the string at run-time (‘translate-string’ ‘scan-translate-string’).

‘rec-to’ ( c-addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) ‘->v’ (‘TO v’), ‘+>v’ (‘+TO
v’), ‘'>v’ (‘ADDR v’), ‘@>d’ (‘ACTION-OF d’) and ‘=>d’ (‘IS d’), where v
is a value-flavoured word and d is a defer-flavoured word.  If
successful, translation represents performing the operation on v/d at
run-time.

‘rec-dtick’ ( c-addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) ‘``word’.  If successful,
translation represents pushing the name token of word at run-time (see
‘translate-cell’).  Example: ‘``S"’ gives the nt of ‘S"’.

‘rec-tick’ ( c-addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) ‘`word’.  If successful,
translation represents pushing the execution token of word at run-time
(see ‘translate-cell’).  Example: ‘`dup’ gives the xt of dup.

‘rec-body’ ( addr u - translation  ) gforth-experimental
   Recognizes (*note Defining recognizers::) ‘<word>’ and
‘<word+number>’.  If successful, translation represents pushing the sum
of the body address word and number (0 if absent) at run-time (see
‘translate-cell’).

‘rec-env’ ( c-addr u - translation  ) gforth-1.0
   Recognizes (*note Defining recognizers::) ‘${envvar}’.  If
successful, translation represents passing envvar to ‘getenv’ at
run-time (see ‘translate-env’).  Example: ‘${HOME}’ gives the home
directory.

‘rec-meta’ ( addr u - xt translate-to | 0  ) gforth-1.0
   Recognizes (*note Defining recognizers::) ‘myrec?mystring’.  Produces
the result of passing mystring to ‘rec-myrec’.
Example: ‘hex num?cafe’ will be recognized as number even if a word
‘cafe’ is in the search order.
Example: ‘float?123.’ will be recognized as float.


File: gforth.info,  Node: Recognizer order,  Next: Defining recognizers,  Prev: Default recognizers,  Up: Recognizers

6.17.4.2 Recognizer order
.........................

You may prefer to use a different recognizer sequence, but with (some of
the) existing recognizers.  You can use the following words for that:

‘rec-forth’ ( c-addr u - translation  ) gforth-experimental
   The system recognizer: ‘rec-forth’ is a ‘defer’red word that contains
a recognizer (sequence).  The system's text interpreter calls
‘rec-forth’.

‘rec-sequence:’ ( xtu .. xt1 u "name" -  ) gforth-experimental "rec-sequence-colon"
   Define a recognizer sequence name.  xtu..xt1 are xts of recognizers,
and are the initial contents of the recognizer sequence, with xt1
searched first.  The order of operands is inspired by ‘get-order’ and
‘set-order’.
name execution: ( c-addr u - translation )
Execute the first xt in the recognizer sequence name.  If the resulting
translation has a translation token other than ‘translate-none’, this is
the result of name and no further recognizers are tried.  Otherwise, the
stacks are restored to the initial state (c-addr u), and the next xt is
tried.  If all xts produce ‘translate-none’, translation is
‘translate-none’.  name is a recognizer itself, which makes recognizer
sequences nestable.

‘get-recs’ ( recs-xt - xtu .. xt1 u  ) gforth-experimental
   Recs-xt is the execution token of a recognizer sequence.  xt1 is the
first recognizer searched by this sequence, xtu is the last one.  If
recs-xt refers to a deferred word, perform ‘defer@ get-recs’.

‘set-recs’ ( xtu .. xt1 u recs-xt -  ) gforth-experimental
   rec-xt is the execution token of a recognizer sequence.  Replace the
contents of this sequence with xtu...xt_1, where xt1 is searched first,
and xtu is searched last.  If recs-xt refers to a deferred word, perform
‘defer@ set-recs’.

   You probably don't want to create a new recognizer sequence every
time you want to change the system recognizer sequence.  There are
several ways to change an existing recognizer sequence:

   • Put one or more ‘defer’red words in a recognizer sequence, and
     change the recognizer in this word later.  If you do not want such
     a deferred word to recognize anything for now, put ‘rec-none’ in
     it.

   • Use ‘set-recs’ on the recognizer sequence, possibly after getting
     the current sequence with ‘get-recs’ and modifying it.

   • The body of a recognizer sequence is a ‘stack’ (*note User-defined
     Stacks::), and you can use the words for manipulating stacks on it.
     In particular, if you add a recognizer with ‘>stack’, that
     recognizer will be tried first; if you add it with ‘>back’, it will
     be tried last.

‘rec-none’ ( c-addr u - translate-none  ) gforth-experimental
   This recognizer recognizes nothing.  It can be useful as a
placeholder.

   Here is an example of adding ‘rec-none’ as last recognizer to the
system recognizers:

     ' rec-none action-of rec-forth get-recs 1+ action-of rec-forth set-recs

     \ alternative
     ' rec-none action-of rec-forth >body >back


File: gforth.info,  Node: Defining recognizers,  Next: Defining translation tokens,  Prev: Recognizer order,  Up: Recognizers

6.17.4.3 Defining recognizers
.............................

A “recognizer” is a Forth word with the stack effect ‘( c-addr u --
translation )’.  c-addr u describes the string to be recognized.  The
returned “translation” is an abstract, but transparent data type: On the
top of stack, there is a single-cell “translation token”.  If the
recognizer does not recognize the string, it returns the translation
token ‘translate-none’.  If it does recognize the string, it returns a
translation with a different translation token.  The translation token
also identifies how many other stack items the translation contains and
how the translation will be processed later.

   E.g., when you perform

     "5" rec-number

   it pushes ‘5 translate-cell’ on the stack, which is a translation
with the translation token ‘translate-cell’.

   You typically write a recognizer as ordinary colon definition that
examines the string in some way, and then pushes the appropriate
translation.  E.g., a simple variant of ‘rec-tick’ can be implemented as
follows:

     : rec-tick ( addr u -- translation )
         2dup "`" string-prefix? if
             1 /string find-name dup if
                 name>interpret translate-cell exit then
             drop translate-none exit then
         rec-none ;

   The only appropriate use of a translation is to pass it to one of the
words for performing translation actions (*note Performing translation
actions::).

   A number of translation tokens already exist in Gforth and can be
used in a recognizer you write.  If none of them is appropriate for your
recognizer, read the next section about defining your own translation
tokens.

   The system-defined translation-token words are documented as removing
some stack items and pushing a complete translation on the stack, e.g.,
for ‘translate-cell’ ‘( x -- translation )’.  This makes the
documentation uniform and avoids cumbersome descriptions.  However,
actually the current translation-token words just push a cell-sized
translation token on the stack (for ‘translate-cell’: ‘( --
translate-cell )’), and, combined with the additional stack items (for
‘translate-cell’: ‘( x -- x translate-cell )’), the result is a
translation (for ‘translate-cell’: ‘( x -- translation )’).

   The text interpreter passes the output of the recognizer to a
translation action (*note Performing translation actions::).  Every
translation action removes the translation from the stack, then may
perform additional parsing, and finally performs the interpreting
run-time of the translation token, or the compiling run-time, or the
postponing run-time.

   For each system-defined translation token we specify the interpreting
run-time explicitly.  Unless otherwise specified, the compiling run-time
compiles the interpreting run-time.  Unless otherwise specified, the
postponing run-time compiles the compiling run-time.

   In the ‘rec-tick’ example above, if the recognizer recognizes, say,
‘`dup’, it returns xt-dup translate-cell.  If the text interpreter then
performs the compiling action, that action first removes this
translation (these two cells), and compiles code that pushes xt-dup.

‘translate-name’ ( nt - translation  ) gforth-experimental
   Interpreting run-time: ‘( ... -- ... )’
Perform the interpretation semantics of nt.
Compiling run-time: ‘( ... -- ... )’
Perform the compilation semantics of nt.

‘translate-cell’ ( x - translation  ) gforth-experimental
   Interpreting run-time: ‘( -- x )’

‘translate-dcell’ ( xd - translation  ) gforth-experimental
   Interpreting run-time: ‘( -- xd )’

‘translate-float’ ( r - translation  ) gforth-experimental
   Interpreting run-time: ‘( -- r )’

‘translate-complex’ ( r1 r2 - translation  ) gforth-experimental
   Interpreting run-time: ‘( -- r1 r2 )’

‘translate-string’ ( c-addr1 u1 - translation  ) gforth-experimental
   Interpreting run-time: ‘( -- c-addr2 u2 )’
c-addr2 u2 is the result of translating the ‘\’-escapes in c-addr1 u1.

‘scan-translate-string’ ( c-addr1 u1 'ccc"' - translation  ) gforth-experimental
   Every translation action also parses until the first non-escaped ‘"’.
The string c-addr u and the parsed input are concatenated, then the
‘\’-escapes are translated, giving c-addr2 u2.
Interpreting run-time: ‘( -- c-addr2 u2 )’

‘translate-env’ ( c-addr1 u1 - translation  ) gforth-experimental
   Interpreting run-time: ‘( -- c-addr2 u2 )’
c-addr2 u2 is the content of the environment variable with name c-addr1
u1.

‘translate-to’ ( n xt - translation  ) gforth-experimental
   xt belongs to a value-flavoured (or defer-flavoured) word, n is the
index into the ‘to-table:’ for xt (*note Words with user-defined TO
etc.::).
Interpreting run-time: ‘( ... -- ... )’
Perform the to-action with index n in the ‘to-table:’ of xt.  Additional
stack effects depend on n and xt.

   One way to write a recognizer r is to call a recognizer (for the
whole input of r or a substring) that recognizes more strings (e.g.,
‘rec-forth’), and then look at the result to see if something was
recognized that r actually deals with.

   E.g., the actual implementation of ‘rec-tick’ passes its input
without the prefix ‘`’ to ‘rec-forth’ and checks whether the resulting
translation-token is nt translate-name, then converts nt to xt, and
replaces translate-name with translate-cell.  The benefit of this
approach compared to our example implementation above is that, e.g.,
‘`environment:max-n’ works, where ‘rec-scope’ recognizes
‘environment:max-n’.

   The specific check for an nt used in ‘rec-tick’ is ‘rec-forth-nt?’;
it is implemented on top of the more general ‘rec-filter’.

‘rec-filter’ ( c-addr u xt: filter xt: rec - translation  ) gforth-experimental
   Execute rec ‘( c-addr u -- translation1 )’; translation1 is then
examined with filter ‘( translation1 -- translation1 f )’.  If f is
non-zero, translation is translation1, otherwise translation is
translate-none.

‘rec-forth-nt?’ ( c-addr u - nt | 0  ) gforth-experimental "rec-forth-nt-question"
   If ‘rec-forth’ produces a result nt ‘translate-name’, return nt,
otherwise 0.


File: gforth.info,  Node: Defining translation tokens,  Next: Performing translation actions,  Prev: Defining recognizers,  Up: Recognizers

6.17.4.4 Defining translation tokens
....................................

Before you define a translation token, you should think about the
interpreting run-time, compiling run-time, and postponing run-time that
the corresponding actions should perform for translations with this
translation token.  Also, you should think about whether the translation
actions should perform additional scanning (like
‘scan-translate-string’).

   You then need to define three words, one for the interpreting action,
one for the compiling action, and one for the postponing action.

   Each of these words will eventually be called after removing the
translation token from the stack (but the remainder of the translation
is still on the stack(s)).  It should remove this remainder, perform the
additional scanning (if any), and then perform the appropriate run-time.

   Once you have these three words, you can define a translation token
by passing the xts of these words to

‘translate:’ ( int-xt comp-xt post-xt "name" -  ) gforth-experimental "translate-colon"
   Defines name, a translation token (*note Defining recognizers::).
name execution: ( - translation-token )
name interpreting action: ( ...  translation - ...  )
Remove the translation token from the stack and execute int-xt.
name compiling action: ( ...  translation - ...  )
Remove the translation token from the stack and execute comp-xt.
name postponing action: ( translation - )
Remove the translation token from the stack and execute post-xt.

   To make this a little more concrete, here is an implementation for
‘translate-cell’:

     ' noop                       ( x -- x )                             \ int-xt
     ' lit,                       ( compilation: x -- ; run-time: -- x ) \ comp-xt
     :noname lit, postpone lit, ; ( postponing: x -- ;  run-time: -- x ) \ post-xt
     translate: translate-cell

   If a recognizer recognizes something as a single-cell literal x, it
pushes x and then calls ‘translate-cell’.  Later the text interpreter
(or ‘postpone’ or some other consumer of translations) removes the
translation token and executes one of the three xts above (depending on
what translation action is desired).

   When the interpretation semantics is needed, int-xt is executed, and
x stays on the stack.

   For the compilation semantics, x is compiled into the current
definition as literal.

   For postponing, more time levels are involved: at text-interpretation
time (when the recognizer runs and the translation token action is
performed) the current definition is d1.  When d1 runs, the current
definition is d2(1).  The post-xt of the ‘translate-cell’ implementation
above first compiles x into d1 and also compiles ‘lit,’ into d1 (that's
the ‘postpone lit,’ part).  When d1 runs, it pushes x and then the
‘lit,’ compiles x into d2.

   Many literal translation tokens follow this scheme.

   A translation token that is quite different is ‘translate-name’.
Here's an implementation:

     : name-intsem ( ... nt -- ... )
       name>interpret execute-exit ;
     : name-compsem ( ... nt -- ... )
       name>compile execute-exit ;
     : name-compcompsem ( nt -- )
       lit, postpone name-compsem ;
     ' name-intsem ' name-compsem ' name-compcompsem translate: translate-name

   ‘Name-intsem’ performs the interpretation semantics of nt, by getting
the xt of the interpretation semantics and executing it.  Here
‘execute-exit’ is used, in order for return-stack words to work (that's
a Gforth 1.0 feature).  Also, in Gforth 1.0 all words have
interpretation semantics, so the result of ‘name-interpret’ is not
tested for 0.

   ‘Name-compsem’ performs the compilation semantics of nt.

   ‘Name-compcompsem’ compiles the compilation semantics of nt.  This is
achieved by compiling nt and ‘name-compsem’ into the current definition
d1.  When d1 runs, the result performs the compilation semantics of nt
at that time.

   ---------- Footnotes ----------

   (1) If there is no current definition when something is compiled,
Gforth outputs a warning.


File: gforth.info,  Node: Performing translation actions,  Prev: Defining translation tokens,  Up: Recognizers

6.17.4.5 Performing translation actions
.......................................

There are the following words for performing the various translation
token actions:

‘interpreting’ ( ... translation - ...  ) gforth-experimental
   Perform the interpreting action of translation.  For a system-defined
translation token, first remove translation from the stack, then
possibly perform additional scanning specified for the translation
token, and finally perform the interpreting run-time of the translation
token.  For a user-defined translation token, remove it from the stack
and execute its int-xt.

‘compiling’ ( ... translation - ...  ) gforth-experimental
   Perform the compiling action of translation.  For a system-defined
translation token, first remove translation from the stack, then
possibly perform additional scanning specified for the translation
token, and finally perform the compiling run-time of the translation
token.  For a user-defined translation token, remove it from the stack
and execute its comp-xt.

‘postponing’ ( ... translation -  ) gforth-experimental
   Perform the postponing action of translation.  For a system-defined
translation token, first remove translation from the stack, then
possibly perform additional scanning specified for the translation
token, and finally perform the postponing run-time of the translation
token.  For a user-defined translation token, remove it from the stack
and execute its post-xt.

‘?rec-found’ ( translation - translation  ) gforth-experimental "question-rec-found"
   ‘throw’s -13 (undefined word) if translation is ‘translate-none’.

   Their typical use is in a text interpreter.  A simple text
interpreter could look like this:

     : myinterpret ( -- )
       \ refill happens outside
       begin
         parse-name dup while
           forth-recognize ?rec-found state @ if compiling else interpreting then
       repeat
       2drop ;

   This text interpreter itself does not deal with postponing; ‘]]’ can
be implemented as a text interpreter that performs the postponing:

     : ]] ( -- )
       \ works only within a line
       begin
         parse-name dup 0= abort" [[ missing"
         2dup "[[" str= 0= while
           forth-recognize ?rec-found postponing
        repeat
        2drop ; immediate


File: gforth.info,  Node: Text Interpreter Hooks,  Prev: Recognizers,  Up: The Text Interpreter

6.17.5 Text Interpreter Hooks
-----------------------------

‘before-line’ ( -  ) gforth-1.0
   Deferred word called before the text interpreter parses the next line

‘before-word’ ( -  ) gforth-0.7
   Deferred word called before the text interpreter parses the next word

‘line-end-hook’ ( -  ) gforth-0.7
   Deferred word called at every end-of-line when text-interpreting from
a file.


File: gforth.info,  Node: The Input Stream,  Next: Word Lists,  Prev: The Text Interpreter,  Up: Words

6.18 The Input Stream
=====================

The text interpreter reads from the input stream, which can come from
several sources (*note Input Sources::).  Some words, in particular
defining words, but also words like ‘'’, read parameters from the input
stream instead of from the stack.

   Such words are called parsing words, because they parse the input
stream.  Parsing words are hard to use in other words, because it is
hard to pass program-generated parameters through the input stream.
They also usually have an unintuitive combination of interpretation and
compilation semantics when implemented naively, leading to various
approaches that try to produce a more intuitive behaviour (*note
Combined words::).

   It should be obvious by now that parsing words are a bad idea.  If
you want to implement a parsing word for convenience, also provide a
factor of the word that does not parse, but takes the parameters on the
stack.  To implement the parsing word on top if it, you can use the
following words:

‘parse’ ( xchar "ccc<xchar>" - c-addr u  ) core-ext,xchar-ext
   Parse ccc, delimited by xchar, in the parse area.  c-addr u specifies
the parsed string within the parse area.  If the parse area was empty, u
is 0.

‘string-parse’ ( c-addr1 u1 "ccc<string>" - c-addr2 u2  ) gforth-1.0
   Parse ccc, delimited by the string c-addr1 u1, in the parse area.
c-addr2 u2 specifies the parsed string within the parse area.  If the
parse area was empty, u2 is 0.

‘parse-name’ ( "name" - c-addr u  ) core-ext
   Get the next word from the input buffer

‘parse-word’ ( - c-addr u  ) gforth-obsolete
   old name for ‘parse-name’; this word has a conflicting behaviour in
some other systems.

‘name’ ( - c-addr u  ) gforth-obsolete
   old name for ‘parse-name’

‘word’ ( char "<chars>ccc<char>- c-addr  ) core
   We recommend to use ‘parse-name’ instead of ‘bl word’ and, for other
delimiters, ‘parse’ instead of ‘word’.
Skip leading delimiters.  Parse ccc, delimited by char, in the parse
area.  c-addr is the address of a transient region containing the parsed
string in counted-string format (*note Counted string words::.  If the
parse area is empty or contains no characters other than delimiters, the
resulting string has zero length.  A program may replace characters
within the counted string.  OBSOLESCENT: the counted string has a
trailing space that is not included in its length.

‘refill’ ( - flag  ) core-ext,block-ext,file-ext
   Attempt to fill the input buffer from the input source.  When the
input source is the user input device, attempt to receive input into the
terminal input device.  If successful (including lines of length 0),
make the result the input buffer, set ‘>IN’ to 0 and return true;
otherwise return false.
When the input source is a text file, attempt to read the next line from
the file.  If successful, make the result the current input buffer, set
‘>IN’ to 0 and return true; otherwise, return false.
When the input source is a block, add 1 to the value of ‘BLK’ to make
the next block the input source and current input buffer, and set ‘>IN’
to 0; return true if the new value of ‘BLK’ is a valid block number,
false otherwise.

   If you have to deal with a parsing word that does not have a
non-parsing factor, you can use ‘execute-parsing’ to pass a string to
it:

‘execute-parsing’ ( ... addr u xt - ...  ) gforth-0.6
   Make addr u the current input source, execute xt ‘( ... -- ... )’,
then restore the previous input source.

   Example:

     5 s" foo" ' constant execute-parsing
     \ equivalent to
     5 constant foo

   A definition of this word in Standard Forth is provided in
‘compat/execute-parsing.fs’.

   If you want to run a parsing word on a file, the following word
should help:

‘execute-parsing-file’ ( i*x fileid xt - j*x  ) gforth-0.6
   Make fileid the current input source, execute xt ‘( i*x -- j*x )’,
then restore the previous input source.


File: gforth.info,  Node: Word Lists,  Next: Number conversion,  Prev: The Input Stream,  Up: Words

6.19 Word Lists
===============

A wordlist is a list of named words; you can add new words and look up
words by name (and you can remove words in a restricted way with
markers).  Every named (and ‘reveal’ed) word is in one wordlist.

   The text interpreter searches the wordlists present in the search
order (a stack of wordlists, *note User-defined Stacks::), from the top
to the bottom.  Within each wordlist, the search starts conceptually at
the newest word; i.e., if two words in a wordlist have the same name,
the newer word is found.

   New words are added to the “compilation wordlist” (aka current
wordlist).

   A word list is identified by a cell-sized word list identifier (wid)
in much the same way as a file is identified by a file handle.  The
numerical value of the wid has no (portable) meaning, and might change
from session to session.

   The Standard Forth "Search order" word set is intended to provide a
set of low-level tools that allow various different schemes to be
implemented.  Gforth also provides ‘vocabulary’, a traditional Forth
word.  ‘compat/vocabulary.fs’ provides an implementation in Standard
Forth.

‘forth-wordlist’ ( - wid  ) search
   ‘Constant’ - wid identifies the word list that includes all of the
standard words provided by Gforth.  When Gforth is invoked, this word
list is the compilation word list and is at the top of the search order.

‘definitions’ ( -  ) search
   Set the compilation word list to be the same as the word list that is
currently at the top of the search order.

‘get-current’ ( - wid  ) search
   wid is the identifier of the current compilation word list.

‘set-current’ ( wid -  ) search
   Set the compilation word list to the word list identified by wid.

‘in-wordlist’ ( wordlist "defining-word" -  ) gforth-experimental
   execute DEFINING-WORD with WORDLIST as one-shot current directory.
Example: ‘gui-wordlist in-wordlist : init-gl ... ;’ will define
‘init-gl’ in the ‘gui-wordlist’ wordlist.

‘in’ ( "voc" "defining-word" -  ) gforth-experimental
   execute DEFINING-WORD with VOC as one-shot current directory.
Example: ‘in gui : init-gl ... ;’ will define ‘init-gl’ in the ‘gui’
vocabulary.

‘get-order’ ( - widn .. wid1 n  ) search
   Copy the search order to the data stack.  The current search order
has n entries, of which wid1 represents the wordlist that is searched
first (the word list at the top of the search order) and widn represents
the wordlist that is searched last.

‘set-order’ ( widn .. wid1 n -  ) search
   If N=0, empty the search order.  If N=-1, set the search order to the
implementation-defined minimum search order (for Gforth, this is the
word list ‘Root’).  Otherwise, replace the existing search order with
the N wid entries such that WID1 represents the word list that will be
searched first and WIDN represents the word list that will be searched
last.

‘wordlist’ ( - wid  ) search
   Create a new, empty word list represented by wid.

‘table’ ( - wid  ) gforth-0.2
   Create a lookup table (case-sensitive, no warnings).

‘cs-wordlist’ ( - wid  ) gforth-1.0
   Create a case-sensitive wordlist.

‘cs-vocabulary’ ( "name" -  ) gforth-1.0
   Create a case-sensitive vocabulary

‘>order’ ( wid -  ) gforth-0.5 "to-order"
   Push WID on the search order.

‘previous’ ( -  ) search-ext
   Drop the wordlist at the top of the search order.

‘also’ ( -  ) search-ext
   Like ‘DUP’ for the search order.  Usually used before a vocabulary
(e.g., ‘also Forth’); the combined effect is to push the wordlist
represented by the vocabulary on the search order.

‘Forth’ ( -  ) search-ext
   Replace the wid at the top of the search order with the wid
associated with the word list ‘forth-wordlist’.

‘Only’ ( -  ) search-ext
   Set the search order to the implementation-defined minimum search
order (for Gforth, this is the word list ‘Root’).

‘order’ ( -  ) search-ext
   Print the search order and the compilation word list.  The word lists
are printed in the order in which they are searched (which is reversed
with respect to the conventional way of displaying stacks).  The
compilation word list is displayed last.

‘.voc’ ( wid -  ) gforth-0.2 "dot-voc"
   print the name of the wordlist represented by WID.  Can only print
names defined with ‘vocabulary’ or ‘wordlist constant’, otherwise prints
‘address’.

‘find’ ( c-addr - xt +-1 | c-addr 0  ) core,search
   We recommend to use ‘find-name’ instead of ‘find’.  Search all word
lists in the current search order for the definition named by the
counted string at c-addr.  If the definition is not found, return 0.  If
the definition is found, return 1 (if the definition has non-default
compilation semantics) or -1 (if the definition has default compilation
semantics).  The xt returned in interpret state represents the
interpretation semantics.  The xt returned in compile state represented
either the compilation semantics (for non-default compilation semantics)
or the run-time semantics that the compilation semantics would
‘compile,’ (for default compilation semantics).  The Forth-2012 standard
does not specify clearly what the returned xt represents (and also talks
about immediacy instead of non-default compilation semantics), so this
word is questionable in portable programs.  If non-portability is ok,
‘find-name’ and friends are better (*note Name token::).

‘search-wordlist’ ( c-addr count wid - 0 | xt +-1  ) search
   We recommend to use ‘find-name-in’ instead of ‘search-wordlist’.
Search the word list identified by wid for the definition named by the
string at c-addr count.  If the definition is not found, return 0.  If
the definition is found return 1 (if the definition has non-default
compilation semantics) or -1 (if the definition has default compilation
semantics) together with the xt.  In Gforth, the xt returned represents
the interpretation semantics.  Forth-2012 does not specify clearly what
xt represents.

‘words’ ( -  ) tools
   Display a list of all of the definitions in the word list at the top
of the search order.

‘vlist’ ( -  ) gforth-0.2
   Old (pre-Forth-83) name for ‘WORDS’.

‘wordlist-words’ ( wid -  ) gforth-0.6
   Display the contents of the wordlist wid.

‘mwords’ ( ["pattern"] -  ) gforth-1.0
   List all words in the word list on top of the search order.  If a
pattern is given, show only the words matching PATTERN.  Words are
listed old to new (reverse from ‘words’).  By default ‘search’ is used
to determine matching.  You can switch to globbing as used by shells for
files with ‘' mword-filename-match is mword-match’.

‘Root’ ( -  ) gforth-0.2
   Replace the top of the search order by the root wordlist.  This
vocabulary makes up the minimum search order and contains only a few
search-order words.

‘Vocabulary’ ( "name" -  ) gforth-0.2
   Create a definition "name" and associate a new word list wid1 with
it.
name execution: ( - ) replace the wid2 at the top of the search order
with wid1.

‘seal’ ( -  ) gforth-0.2
   Remove all word lists from the search order stack other than the word
list that is currently on the top of the search order stack.

‘vocs’ ( -  ) gforth-0.2
   List vocabularies and wordlists defined in the system.

‘current’ ( - addr  ) gforth-0.2
   ‘Variable’ - holds the wid of the compilation word list.

‘context’ ( - addr  ) gforth-0.2
   ‘context’ ‘@’ is the wid of the word list at the top of the search
order.

‘map-vocs’ ( ... xt - ...  ) gforth-1.0
   Perform xt ( ...  wid - ...  )  for all wordlists (including tables
and cs-wordlists) in the system.

* Menu:

* Why use word lists?::
* Wordlist and vocabulary usage::


File: gforth.info,  Node: Why use word lists?,  Next: Wordlist and vocabulary usage,  Prev: Word Lists,  Up: Word Lists

6.19.1 Why use word lists?
--------------------------

Here are some reasons why people use wordlists:

   • To prevent a set of words from being used outside the context in
     which they are valid.  Two classic examples of this are an
     integrated editor (all of the edit commands are defined in a
     separate word list; the search order is set to the editor word list
     when the editor is invoked; the old search order is restored when
     the editor is terminated) and an integrated assembler (the op-codes
     for the machine are defined in a separate word list which is used
     when a ‘CODE’ word is defined).

   • To organize the words of an application or library into a
     user-visible set (in ‘forth-wordlist’ or some other common
     wordlist) and a set of helper words used just for the
     implementation (hidden in a separate wordlist).  This keeps
     ‘words’' output smaller, separates implementation and interface,
     and reduces the chance of name conflicts within the common
     wordlist.

   • To prevent a name-space clash between multiple definitions with the
     same name.  For example, when building a cross-compiler you might
     have a word ‘IF’ that generates conditional code for your target
     system.  By placing this definition in a different word list you
     can control whether the host system's ‘IF’ or the target system's
     ‘IF’ get used in any particular context by controlling the order of
     the word lists on the search order stack.

   The downsides of using wordlists are:

   • Debugging becomes more cumbersome, because you have to use the
     scope recognizer or put the wordlist in the search order in order
     to refer to a word in a wordlist.  Neither ‘locate’ nor (currently)
     ‘see’ show the names of words with their wordlist or vocabulary.

   • Name conflicts worked around with wordlists are still there, and
     you have to arrange the search order carefully to get the desired
     results; if you forget to do that, you get hard-to-find errors (as
     in any case where you read the code differently from the compiler;
     ‘see’ can help seeing which of several possible words the name
     resolves to in such cases).  ‘See’ displays just the name of the
     words, not what wordlist they belong to, so it might be misleading.
     Using unique names is a better approach to avoid name conflicts.


File: gforth.info,  Node: Wordlist and vocabulary usage,  Prev: Why use word lists?,  Up: Word Lists

6.19.2 Wordlist and vocabulary usage
------------------------------------

If you have an existing wordlist in constant ‘foo-wordlist’ and want to
push it on the search order, here's how you do it:

     foo-wordlist >order
     ... \ code that may use words from foo-wordlist
     previous
     \ now the search order is back to where we started

   If instead you have a vocabulary ‘foo’, the same task can be
accomplished as follows:

     also foo
     ... \ code that may use words from foo
     previous
     \ now the search order is back to where we started

   Also, if you need only one or a few words from ‘foo’, you can use the
scope recognizer (‘rec-scope’, *note Default recognizers::) and write
‘foo:word’.  Currently the scope recognizer only uses vocabularies for
the scope, not wordlists.

   A common usage is to define implementation words (which would be
private in other programming languages) in a separate wordlist, and
(public) interface words in a wordlist for public words (usually
‘forth-wordlist’).  This can be achieved as follows:

     wordlist constant foo-wordlist \ the implementation wordlist
     get-current ( wid )
     foo-wordlist >order definitions
     \ foo-wordlist is now visible and definitions go into it
     ... \ define implementation words
     ( wid ) set-current
     \ foo-wordlist is visible, but definitions go into wid
     ... \ define interface words
     previous
     \ search order and current wordlist are back to where we started

   The same can be done with vocabularies as follows:

     vocabulary foo \ the implementation vocabulary
     get-current ( wid )
     also foo definitions
     \ foo is now visible and definitions go into it
     ... \ define implementation words
     ( wid ) set-current
     \ foo is visible, but definitions go into wid
     ... \ define interface words
     previous
     \ search order and current wordlist are back to where we started

   If you want to define just one word in a given wordlist, you can do
it as follows:

     foo-wordlist in-wordlist : bar ... ;

   For vocabularies, the corresponding usage is:

     in foo : bar ... ;


File: gforth.info,  Node: Number conversion,  Next: Environmental Queries,  Prev: Word Lists,  Up: Words

6.20 Number conversion
======================

This section is about conversion between numbers and strings.  For
conversion between integers and FP numbers, *note Floating Point::.

   In addition to the number-to-string conversion words mentioned in
this section, you can also convert numbers to strings by using a number
output word (*note Simple numeric output::, *note Floating-point
output::), and outputting the result in a string with ‘>string-execute’
(*note String words::).

* Menu:

* Base and integer decimal point::
* String to number conversion::
* Integer to string conversion::
* Floating-point to string conversion::


File: gforth.info,  Node: Base and integer decimal point,  Next: String to number conversion,  Prev: Number conversion,  Up: Number conversion

6.20.1 Base and integer decimal point
-------------------------------------

By default, the number base used for integer number conversion is given
by the contents of the variable ‘base’.  ‘Base’ affects both input
integer conversion (unless a number prefix is used, *note Literals in
source code::) and output integer conversion (unless a base-specific
word such as ‘h.’ or ‘dec.’ is used, *note Simple numeric output::,
*note Integer to string conversion::).  In Gforth, non-decimal ‘base’
disables floating-point conversion.

   Note that a lot of confusion can result from unexpected values of
‘base’.  If you change ‘base’ anywhere, make sure to save the old value
and restore it afterwards; better yet, use ‘base-execute’, which does
this for you.

   In general I recommend keeping ‘base’ decimal; For dealing with the
popular non-decimal bases, use number prefixes for inputting them (*note
Literals in source code::) and ‘h.’ and ‘base-execute’ for outputting
them.

‘base-execute’ ( i*x xt u - j*x  ) gforth-0.7
   execute xt with the content of ‘BASE’ being u, and restoring the
original ‘BASE’ afterwards.

‘base’ ( - a-addr  ) core
   User variable - a-addr is the address of a cell that stores the
number base used by default for number conversion during input and
output.  Don't store to ‘base’, use ‘base-execute’ instead.

‘hex’ ( -  ) core-ext
   Set ‘base’ to $10 (hexadecimal).  In many cases ‘base-execute’ is a
better alternative.

‘decimal’ ( -  ) core
   Set ‘base’ to #10 (decimal).  In many cases ‘base-execute’ is a
better alternative.

‘dpl’ ( - a-addr  ) gforth-0.2 "d-p-l"
   User variable - a-addr is the address of a cell that stores the
position of the decimal point in the most recent input integer
conversion.  After the conversion of a number containing no decimal
point, ‘dpl’ is -1.  After the conversion of ‘2341239.’ it holds 0.
After the conversion of 234123.9 it contains 1, and so forth.

Number conversion has a number of traps for the unwary:

   • A .  in or at the end of a number by default indicates a double
     number, not a floating-point number.
   • Input FP conversion does not happen if ‘base’ is non-decimal.
   • You cannot determine the current number base using the code
     sequence ‘base @ .’ - the number base is always 10 in the current
     number base.  Instead, use something like ‘base @ dec.’
   • There is a word ‘bin’ but it does not set the number base!  (*note
     General files::).
   • Standard Forth requires the ‘.’ of a double-precision number to be
     the final character in the string.  Gforth allows the ‘.’ to be
     anywhere.
   • The input integer conversion process does not check for overflow.
     Instead, you get a value in the range of the result integer type
     (single or double cell) that is congruent with the input number
     modulo the number of values in the integer type (e.g., modulo 2^128
     for doubles with 64-bit cells).

   Words affected by ‘base’ are ‘rec-number’ (*note Default
recognizers::), ‘>number’ (*note String to number conversion::), and the
words described in the sections *note Simple numeric output::, and *note
Integer to string conversion::.  ‘Rec-number’ sets ‘dpl’.


File: gforth.info,  Node: String to number conversion,  Next: Integer to string conversion,  Prev: Base and integer decimal point,  Up: Number conversion

6.20.2 String to number conversion
----------------------------------

‘>number’ ( ud1 c-addr1 u1 - ud2 c-addr2 u2  ) core "to-number"
   Attempt to convert the character string C-ADDR1 U1 to an unsigned
number in the current number base.  The double UD1 accumulates the
result of the conversion to form UD2.  Conversion continues,
left-to-right, until the whole string is converted or a character that
is not convertable in the current number base is encountered (including
+ or -).  For each convertable character, UD1 is first multiplied by the
value in ‘BASE’ and then incremented by the value represented by the
character.  C-ADDR2 is the location of the first unconverted character
(past the end of the string if the whole string was converted).  U2 is
the number of unconverted characters in the string.  Overflow is not
detected.

   For higher-level integer-to-number conversion (with number prefixes,
group separators (‘_’), and double indicators (‘.’), use ‘rec-number’
(*note Default recognizers::).

‘convert’ ( ud1 c-addr1 - ud2 c-addr2  ) gforth-obsolete
   OBSOLETE: This word has been de-standardized in Forth-2012.  It is
superseded by ‘>number’.

‘>float’ ( c-addr u - f:... flag ) floating "to-float"
   Actual stack effect: ( c_addr u - r t | f ).  Attempt to convert the
character string c-addr u to internal floating-point representation.  If
the string represents a valid floating-point number, r is placed on the
floating-point stack and flag is true.  Otherwise, flag is false.  A
string of blanks is a special case and represents the floating-point
number 0.

   You can alternatively use ‘rec-float’ (*note Default recognizers::),
which accepts a smaller set of input strings: ‘>float’ is used for
known-FP-data possibly coming from another program with funny output
syntax and is therefore more liberal in accepting input, while the
strings that the text interpreter passes to ‘rec-float’ are not all
intended to be interpreted as FP numbers, and therefore ‘rec-float’ is
more restrictive.

‘>float1’ ( c-addr u c - f:... flag ) gforth-1.0 "to-float1"
   Actual stack effect: ( c_addr u c - r t | f ).  Attempt to convert
the character string c-addr u to internal floating-point representation,
with c being the decimal separator.  If the string represents a valid
floating-point number, r is placed on the floating-point stack and flag
is true.  Otherwise, flag is false.  A string of blanks is a special
case and represents the floating-point number 0.


File: gforth.info,  Node: Integer to string conversion,  Next: Floating-point to string conversion,  Prev: String to number conversion,  Up: Number conversion

6.20.3 Integer to string conversion
-----------------------------------

Forth uses a technique called “pictured numeric output” for formatted
printing of integers.  In this technique, digits are extracted from the
number (using the current output radix defined by ‘base’, *note Base and
integer decimal point::), converted to ASCII codes and prepended to a
string that is built in the pictured numeric output buffer, aka ‘hold’
buffer (total size, including all nestings and the ‘word’ buffer, is at
most 104 bytes on a 32-bit machine, *note Implementation-defined
options: core-idef.).  Arbitrary characters can be prepended to the
string during the extraction process.  The completed string is specified
by an address and length and can be manipulated (‘TYPE’ed, copied,
modified) under program control.

   All of the integer output words described in the previous section
(*note Simple numeric output::) are implemented in Gforth using pictured
numeric output.

   Three important things to remember about pictured numeric output:

   • It always operates on double-precision numbers; to display a
     single-precision number, convert it first (for ways of doing this
     *note Double precision::).
   • It always treats the double-precision number as though it were
     unsigned.  The examples below show ways of printing signed numbers.
   • The string is built up from right to left; least significant digit
     first.

   Standard Forth supports a single output buffer (aka ‘hold’ area) that
you empty and initialize with ‘<#’ and for which you get the result
string with ‘#>’.

   Gforth additionally supports nested usage of this buffer, allowing,
e.g., to nest output from the debugging tracer ‘~~’ inside code dealing
with the hold area: ‘<<#’ starts a new nest, ‘#>’ produces the result
string, and ‘#>>’ unnests: the hold area for the nest is reclaimed, and
‘#>’ now produces the string for the next-outer nest.  All of Gforth's
higher-level numeric output words use ‘<<#’ ...  ‘#>’ ...  ‘#>>’ and can
be nested inside other users of the hold area.

‘<#’ ( -  ) core "less-number-sign"
   Initialise/clear the pictured numeric output string.

‘<<#’ ( -  ) gforth-0.5 "less-less-number-sign"
   Start a hold area that ends with ‘#>>’.  Can be nested in each other
and in ‘<#’.  Note: if you do not match up the ‘<<#’s with ‘#>>’s, you
will eventually run out of hold area; you can reset the hold area to
empty with ‘<#’.

‘#’ ( ud1 - ud2  ) core "number-sign"
   Used between ‘<<#’ and ‘#>’.  Prepend the least-significant digit
(according to ‘base’) of UD1 to the pictured numeric output string.  UD2
is UD1/BASE, i.e., the number representing the remaining digits.

‘#s’ ( ud - 0 0  ) core "number-sign-s"
   Used between ‘<<#’ and ‘#>’.  Prepend all digits of UD to the
pictured numeric output string.  ‘#s’ will convert at least one digit.
Therefore, if UD is 0, ‘#s’ will prepend a "0" to the pictured numeric
output string.

‘hold’ ( char -  ) core
   Used between ‘<<#’ and ‘#>’.  Prepend the ASCII character CHAR to the
pictured numeric output string.  Use ‘holds’ for prepending non-ASCII
characters.

‘holds’ ( addr u -  ) core-ext
   Used between ‘<<#’ and ‘#>’.  Prepend the string ‘addr u’ to the
pictured numeric output string.

‘sign’ ( n -  ) core
   Used between ‘<<#’ and ‘#>’.  If N (a SINGLE number) is negative,
prepend "‘-’" to the pictured numeric output string.

‘#>’ ( xd - addr u  ) core "number-sign-greater"
   Complete the pictured numeric output string by discarding XD and
returning ADDR U; the address and length of the formatted string.  A
Standard program may modify characters within the string.  Does not
release the hold area; use ‘#>>’ to release a hold area started with
‘<<#’, or ‘<#’ to release all hold areas.

‘#>>’ ( -  ) gforth-0.5 "number-sign-greater-greater"
   Release the hold area started with ‘<<#’.

Here are some examples of using pictured numeric output:

     : my-u. ( u -- )
       \ Simplest use of pns.. behaves like Standard u.
       0              \ convert to unsigned double
       <<#            \ start conversion
       #s             \ convert all digits
       #>             \ complete conversion
       TYPE SPACE     \ display, with trailing space
       #>> ;          \ release hold area

     : cents-only ( u -- )
       0              \ convert to unsigned double
       <<#            \ start conversion
       # #            \ convert two least-significant digits
       #>             \ complete conversion, discard other digits
       TYPE SPACE     \ display, with trailing space
       #>> ;          \ release hold area

     : dollars-and-cents ( u -- )
       0              \ convert to unsigned double
       <<#            \ start conversion
       # #            \ convert two least-significant digits
       '.' hold       \ insert decimal point
       #s             \ convert remaining digits
       '$' hold       \ append currency symbol
       #>             \ complete conversion
       TYPE SPACE     \ display, with trailing space
       #>> ;          \ release hold area

     : my-. ( n -- )
       \ handling negatives.. behaves like Standard .
       s>d            \ convert to signed double
       swap over dabs \ leave sign byte followed by unsigned double
       <<#            \ start conversion
       #s             \ convert all digits
       rot sign       \ get at sign byte, append "-" if needed
       #>             \ complete conversion
       TYPE SPACE     \ display, with trailing space
       #>> ;          \ release hold area

     : account. ( n -- )
       \ accountants don't like minus signs, they use parentheses
       \ for negative numbers
       s>d            \ convert to signed double
       swap over dabs \ leave sign byte followed by unsigned double
       <<#            \ start conversion
       2 pick         \ get copy of sign byte
       0< IF ')' hold THEN \ right-most character of output
       #s             \ convert all digits
       rot            \ get at sign byte
       0< IF '(' hold THEN
       #>             \ complete conversion
       TYPE SPACE     \ display, with trailing space
       #>> ;          \ release hold area

   Here are some examples of using these words:

     1 my-u. 1
     hex -1 my-u. decimal FFFFFFFF
     1 cents-only 01
     1234 cents-only 34
     2 dollars-and-cents $0.02
     1234 dollars-and-cents $12.34
     123 my-. 123
     -123 my. -123
     123 account. 123
     -456 account. (456)


File: gforth.info,  Node: Floating-point to string conversion,  Prev: Integer to string conversion,  Up: Number conversion

6.20.4 Floating-point to string conversion
------------------------------------------

‘f>str-rdp’ ( rf +nr +nd +np - c-addr nr  ) gforth-0.6 "f-to-str-rdp"
   Convert rf into a string at c-addr nr.  The conversion rules and the
meanings of nr +nd np are the same as for ‘f.rdp’ (*note Floating-point
output::).  The result is in in the pictured numeric output buffer and
will be destroyed by anything overwriting that buffer.

‘f>buf-rdp’ ( rf c-addr +nr +nd +np -  ) gforth-0.6 "f-to-buf-rdp"
   Convert rf into a string at c-addr nr.  The conversion rules and the
meanings of nr nd np are the same as for ‘f.rdp’ (*note Floating-point
output::).

   There is also a primitive used for implementing the higher-level
FP-to-string and FP output words:

‘represent’ ( r c-addr u - n f1 f2 ) floating "represent"
   Convert the decimal significand (aka mantissa) of r into a string in
buffer c-addr u; n is the exponent, f1 is true if r is negative, and f2
is true if r is valid (a finite number in Gforth).


File: gforth.info,  Node: Environmental Queries,  Next: Files,  Prev: Number conversion,  Up: Words

6.21 Environmental Queries
==========================

Forth-94 introduced the idea of "environmental queries" as a way for a
program running on a system to determine certain characteristics of the
system.  The Standard specifies a number of strings that might be
recognised by a system, and a way of querying them:

‘environment?’ ( c-addr u - false / ... true  ) core "environment-query"
   c-addr, u specify a counted string.  If the string is not recognised,
return a ‘false’ flag.  Otherwise return a ‘true’ flag and some
(string-specific) information about the queried string.

   Note that, while the documentation for (e.g.)  ‘ADDRESS-UNIT-BITS’
shows that it returns one cell on the stack, querying it using
‘environment?’ will return an additional item; the ‘true’ flag that
shows that the string was recognised; so for querying
‘ADDRESS-UNIT-BITS’ the stack effect of ‘environment?’ may be ‘( c-addr
u -- n true )’ or ‘( c-addr u -- false )’.  The support of various
environmental queries by systems (even on hardware with enough memory)
is somewhat lackluster, so you have to take the possibility of
‘environment?’ returning false seriously.

   Several environmental queries deal with the system's limits:

‘ADDRESS-UNIT-BITS’ ( - n  ) environment
   Size of one address unit, in bits.

‘MAX-CHAR’ ( - u  ) environment
   Maximum value of any character in the character set (there is also
‘max-xchar’).

‘/COUNTED-STRING’ ( - n  ) environment "slash-counted-string"
   Maximum size of a counted string, in characters.

‘/HOLD’ ( - n  ) environment "slash-hold"
   Size of the pictured numeric string output buffer, in characters.

‘/PAD’ ( - n  ) environment "slash-pad"
   Size of the scratch area pointed to by ‘PAD’, in characters.

‘CORE’ ( - f  ) environment
   True if the complete core word set is present.  Always true for
Gforth.

‘CORE-EXT’ ( - f  ) environment
   True if the complete core extension word set is present.  Always true
for Gforth.

‘FLOORED’ ( - f  ) environment
   True if ‘/’ etc.  perform floored division

‘MAX-N’ ( - n  ) environment
   Largest usable signed integer.

‘MAX-U’ ( - u  ) environment
   Largest usable unsigned integer.

‘MAX-D’ ( - d  ) environment
   Largest usable signed double.

‘MAX-UD’ ( - ud  ) environment
   Largest usable unsigned double.

‘return-stack-cells’ ( - n  ) environment
   Maximum size of the return stack, in cells.

‘stack-cells’ ( - n  ) environment
   Maximum size of the data stack, in cells.

‘floating-stack’ ( - n  ) environment
   N is non-zero, showing that Gforth maintains a separate
floating-point stack of depth N.

‘#locals’ ( - n  ) environment "number-locals"
   The maximum number of locals in a definition

‘wordlists’ ( - n  ) environment
   the maximum number of wordlists usable in the search order

‘max-float’ ( - r  ) environment
   The largest usable floating-point number (implemented as largest
finite number in Gforth)

‘XCHAR-ENCODING’ ( - addr u  ) environment
   Returns a printable ASCII string that reperesents the encoding, and
use the preferred MIME name (if any) or the name in
<http://www.iana.org/assignments/character-sets> like "ISO-LATIN-1" or
"UTF-8", with the exception of "ASCII", where we prefer the alias
"ASCII".

‘MAX-XCHAR’ ( - xchar  ) environment
   Maximal value for xchar.  This depends on the encoding.

‘XCHAR-MAXMEM’ ( - u  ) environment
   Maximal memory consumed by an xchar in address units

   Several environmental queries are there for determining the presence
of the Forth-94 version of a wordset; they all have the stack effect ‘(
-- f )’ if the string is present (so the ‘environment?’ stack effect for
these queries is ‘( c-addr u -- false / f true )’.

   ‘block block-ext double double-ext exception exception-ext facility
facility-ext file file-ext floating floating-ext locals locals-ext
memory-alloc memory-alloc-ext tools tools-ext search-order
search-order-ext string string-ext’

   These wordset queries were rarely used and implemented, so Forth-2012
did not introduce a way to query for the Forth-2012 variants of the
wordsets.  Instead, the idea is that you use ‘[defined]’ (*note
Interpreter Directives::) for checking the presence of individual
standard words instead.

   Forth-200x (a group that works on the next standard; the documents
that they produce are also called Forth-200x) defines extension queries
for the extension proposals once they finish changing (CfV stage), so
programs using these proposals can check whether a system has them, and
maybe load the reference implementation (if one exists).  If
‘environment?’ finds such a query, then the corresponding proposal on
<www.forth200x.org> is implemented on the system (but the absence tells
you nothing, as usual with ‘environment?’).  These queries have the
stack effect ‘( -- )’, which means that for them ‘environment?’ has the
stack effect ‘( c-addr u -- false / true )’, which is more convenient
than that of wordset queries.  A number of these proposals have been
incorporated into Forth-2012.  The extension queries are also not
particularly popular among Forth system implementors, so going for
‘[defined]’ may be the better approach.  Anyway, Gforth implements the
following extension queries:

   ‘X:2value X:buffer X:deferred X:defined X:ekeys X:escaped-strings
X:extension-query X:fp-stack X:ftrunc X:fvalue X:locals X:n-to-r
X:number-prefixes X:parse-name X:required X:s-escape-quote X:s-to-f
X:structures X:synonym X:text-substitution X:throw-iors
X:traverse-wordlist X:xchar’

   In addition, Gforth implements the following Gforth-specific queries:

‘gforth’ ( - c-addr u  ) gforth-environment
   Counted string representing a version string for this version of
Gforth (for versions>0.3.0).  The version strings of the various
versions are guaranteed to be ordered lexicographically.

‘os-class’ ( - c-addr u  ) gforth-environment
   Counted string representing a description of the host operating
system.

‘os-type’ ( - c-addr u  ) gforth-environment
   Counted string equal to "$host_os"

   The Standard requires that the header space used for environmental
queries be distinct from the header space used for definitions.

   Typically, a Forth system supports environmental queries by creating
a set of definitions in a wordlist that is only used for environmental
queries; that is what Gforth does.  There is no Standard way of adding
definitions to the set of recognised environmental queries, but in
Gforth and other systems that use the wordlist mechanism, the wordlist
used to honour environmental queries can be manipulated just like any
other word list.

‘environment-wordlist’ ( - wid  ) gforth-0.2
   wid identifies the word list that is searched by environmental
queries (present in SwiftForth and VFX).

‘environment’ ( -  ) gforth-0.6
   A vocabulary for ‘environment-wordlist’ (present in Win32Forth and
VFX).

   Here are some examples of using environmental queries:

     s" address-unit-bits" environment? 0=
     [IF]
          cr .( environmental attribute address-units-bits unknown... ) cr
     [ELSE]
          drop \ ensure balanced stack effect
     [THEN]

     \ this might occur in the prelude of a standard program that uses THROW
     s" exception" environment? [IF]
        0= [IF]
           : throw abort" exception thrown" ;
        [THEN]
     [ELSE] \ we don't know, so make sure
        : throw abort" exception thrown" ;
     [THEN]

     s" gforth" environment? [IF] .( Gforth version ) TYPE
                             [ELSE] .( Not Gforth..) [THEN]

     \ a program using v*
     s" gforth" environment? [IF]
       s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
        : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
          >r swap 2swap swap 0e r> 0 ?DO
            dup f@ over + 2swap dup f@ f* f+ over + 2swap
          LOOP
          2drop 2drop ;
       [THEN]
     [ELSE] \
       : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
       ...
     [THEN]

   Here is an example of adding a definition to the environment word
list:

     get-current environment-wordlist set-current
     true constant block
     true constant block-ext
     set-current

   You can see what definitions are in the environment word list like
this:

     environment-wordlist wordlist-words


File: gforth.info,  Node: Files,  Next: Blocks,  Prev: Environmental Queries,  Up: Words

6.22 Files
==========

Gforth provides facilities for accessing files that are stored in the
host operating system's file-system.

* Menu:

* Forth source files::
* General files::
* Redirection::
* Directories::
* Search Paths::


File: gforth.info,  Node: Forth source files,  Next: General files,  Prev: Files,  Up: Files

6.22.1 Forth source files
-------------------------

The simplest way to interpret the contents of a file is to use one of
these two equivalent syntaxes:

     include mysource.fs
     s" mysource.fs" included

   You usually want to include a file only if it is not included already
(by, say, another source file).  In that case, you can replace ‘include’
with ‘require’:

     require mysource.fs
     s" mysource.fs" required

   It is good practice to write your source files such that interpreting
them does not change the stack.  Source files designed in this way can
be used with ‘required’ and friends without complications.  For example,
assume that including ‘foo.fs’ has the stack effect ‘( u -- u )’ (u
might be a configuration parameter, such as a buffer size).  Then you
can use it with ‘require’:

     1024 require foo.fs drop

   If ‘require’ actually includes ‘foo.fs’, the 1024 will be on the
stack at the end, just like if ‘require’ does nothing.  With such
parameters to required files, you have to ensure that the first
‘require’ fits for all uses (i.e., ‘require’ the file early in the
master load file).

   Another alternative is to pass configuration parameters by defining
words (often constants) for them.

‘include-file’ ( i*x wfileid - j*x  ) file
   Interpret (process using the text interpreter) the contents of the
file WFILEID.

‘included’ ( i*x c-addr u - j*x  ) file
   ‘include-file’ the file whose name is given by the string C-ADDR U.

‘included?’ ( c-addr u - f  ) gforth-0.2 "included-question"
   True only if the file C-ADDR U is in the list of earlier included
files.  If the file has been loaded, it may have been specified as, say,
‘foo.fs’ and found somewhere on the Forth search path.  To return ‘true’
from ‘included?’, you must specify the exact path to the file, even if
that is ‘./foo.fs’

‘include’ ( ... "file" - ...  ) file-ext
   ‘include-file’ the file FILE.

‘required’ ( i*x addr u - i*x  ) file-ext
   ‘include-file’ the file with the name given by ADDR U, if it is not
‘included’ (or ‘required’) already.  Currently this works by comparing
the name of the file (with path) against the names of earlier included
files.

‘require’ ( ... "file" - ...  ) file-ext
   ‘include-file’ FILE only if it is not included already.

‘needs’ ( ... "name" - ...  ) gforth-0.2
   An alias for ‘require’; exists on other systems (e.g., Win32Forth).

‘\\\’ ( -  ) gforth-1.0 "triple-backslash"
   skip remaining source file

‘.included’ ( -  ) gforth-0.5 "dot-included"
   List the names of the files that have been ‘included’.

‘sourcefilename’ ( - c-addr u  ) gforth-0.2
   The name of the source file which is currently the input source.  The
result is valid only while the file is being loaded.  If the current
input source is no (stream) file, the result is an arbitrary string.  In
Gforth, the result is valid during the whole session (but not across
‘savesystem’ etc.).

‘sourceline#’ ( - u  ) gforth-0.2 "sourceline-number"
   The line number of the line that is currently being interpreted from
a (stream) file.  The first line has the number 1.  If the current input
source is not a (stream) file, the result is an unspecified number.

   A definition in Standard Forth for ‘required’ is provided in
‘compat/required.fs’.


File: gforth.info,  Node: General files,  Next: Redirection,  Prev: Forth source files,  Up: Files

6.22.2 General files
--------------------

Files are opened/created by name and type.  The following file access
methods (FAMs) are recognised:

‘r/o’ ( - fam  ) file "r-o"

‘r/w’ ( - fam  ) file "r-w"

‘w/o’ ( - fam  ) file "w-o"

‘bin’ ( fam1 - fam2  ) file

‘+fmode’ ( fam1 rwxrwxrwx - fam2  ) gforth-1.0 "plus-f-mode"
   Rwxrwxrwx is a 9-bit number; e.g.  ‘%110_010_000’ specifies that the
owner can read and write a file, the group can read a file, and others
cannot access the file.  When passing fam2 to ‘create-file’, the created
file will have the mode specified by rwxrwxrwx, modified by the umask.
Default: ‘%110_110_110’ i.e.  RW for everyone (modified by umask).

   When a file is opened/created, it returns a file identifier, wfileid
that is used for all other file commands.  All file commands also return
a status value, wior, that is 0 for a successful operation and an
implementation-defined non-zero value in the case of an error.

‘open-file’ ( c-addr u wfam - wfileid wior ) file "open-file"

‘create-file’ ( c-addr u wfam - wfileid wior ) file "create-file"

‘close-file’ ( wfileid - wior ) file "close-file"

‘delete-file’ ( c-addr u - wior ) file "delete-file"

‘rename-file’ ( c-addr1 u1 c-addr2 u2 - wior ) file-ext "rename-file"
   Rename file c_addr1 u1 to new name c_addr2 u2

‘read-file’ ( c-addr u1 wfileid - u2 wior ) file "read-file"
   Read u1 characters from file wfileid into the buffer at c_addr.  A
non-zero wior indicates an error.  U2 indicates the length of the read
data.  End-of-file is not an error and is indicated by u2<u1 and wior=0.

‘read-line’ ( c_addr u1 wfileid - u2 flag wior  ) file
   Reads a line from wfileid into the buffer at c_addr u1.  Gforth
supports all three common line terminators: LF, CR and CRLF. A non-zero
wior indicates an error.  A false flag indicates that ‘read-line’ has
been invoked at the end of the file.  u2 indicates the line length
(without terminator): u2<u1 indicates that the line is u2 chars long;
u2=u1 indicates that the line is at least u1 chars long, u1 chars of the
buffer have been filled with chars from the line, and the next slice of
the line will be read with the next ‘read-line’.  If the line is u1
chars long, the first ‘read-line’ returns u2=u1 and the next read-line
returns u2=0.

‘key-file’ ( fd - key  ) gforth-0.4
   Read one character n from wfileid.  This word disables buffering for
wfileid.  If you want to read characters from a terminal in
non-canonical (raw) mode, you have to put the terminal in non-canonical
mode yourself (using the C interface); the exception is ‘stdin’: Gforth
automatically puts it into non-canonical mode.

‘key?-file’ ( wfileid - f ) gforth-0.4 "key-q-file"
   f is true if at least one character can be read from wfileid without
blocking.  If you also want to use ‘read-file’ or ‘read-line’ on the
file, you have to call ‘key?-file’ or ‘key-file’ first (these two words
disable buffering).

‘file-eof?’ ( wfileid - flag ) gforth-0.6 "file-eof-query"
   FLAG is true if the end-of-file indicator for WFILEID is set.

‘write-file’ ( c-addr u1 wfileid - wior ) file "write-file"

‘write-line’ ( c-addr u wfileid - ior  ) file

‘emit-file’ ( c wfileid - wior ) gforth-0.2 "emit-file"

‘flush-file’ ( wfileid - wior ) file-ext "flush-file"

‘file-status’ ( c-addr u - wfam wior ) file-ext "file-status"

‘file-position’ ( wfileid - ud wior ) file "file-position"

‘reposition-file’ ( ud wfileid - wior ) file "reposition-file"

‘file-size’ ( wfileid - ud wior ) file "file-size"

‘resize-file’ ( ud wfileid - wior ) file "resize-file"

‘slurp-file’ ( c-addr1 u1 - c-addr2 u2  ) gforth-0.6
   C-ADDR1 U1 is the filename, C-ADDR2 U2 is the file's contents.  You
should ‘free’ c-addr2 when you no longer need the contents of the file.

‘slurp-fid’ ( fid - c-addr u  ) gforth-0.6
   C-ADDR U is the content of the file FID.  You should ‘free’ c-addr
when you no longer need the contents of the file.

‘stdin’ ( - wfileid ) gforth-0.4 "stdin"
   The standard input file of the Gforth process.

‘stdout’ ( - wfileid ) gforth-0.2 "stdout"
   The standard output file of the Gforth process.

‘stderr’ ( - wfileid ) gforth-0.2 "stderr"
   The standard error output file of the Gforth process.


File: gforth.info,  Node: Redirection,  Next: Directories,  Prev: General files,  Up: Files

6.22.3 Redirection
------------------

You can redirect the output of ‘type’ and ‘emit’ and all the words that
use them (all output words that don't have an explicit target file) to
an arbitrary file with the ‘outfile-execute’, used like this:

     : some-warning ( n -- )
         cr ." warning# " . ;

     : print-some-warning ( n -- )
         ['] some-warning stderr outfile-execute ;

   After ‘some-warning’ is executed, the original output direction is
restored; this construct is safe against exceptions.  Similarly, there
is ‘infile-execute’ for redirecting the input of ‘key’ and its users
(any input word that does not take a file explicitly).

‘outfile-execute’ ( ... xt file-id - ...  ) gforth-0.7
   execute xt with the output of ‘type’ etc.  redirected to file-id.

‘outfile-id’ ( - file-id  ) gforth-0.2
   File-id is used by ‘emit’, ‘type’, and any output word that does not
take a file-id as input.  By default ‘outfile-id’ produces the process's
‘stdout’, unless changed with ‘outfile-execute’.

‘infile-execute’ ( ... xt file-id - ...  ) gforth-0.7
   execute xt with the input of ‘key’ etc.  redirected to file-id.

‘infile-id’ ( - file-id  ) gforth-0.4
   File-id is used by ‘key’, ‘?key’, and anything that refers to the
"user input device".  By default ‘infile-id’ produces the process's
‘stdin’, unless changed with ‘infile-execute’.

   If you do not want to redirect the input or output to a file, you can
also make use of the fact that ‘key’, ‘emit’ and ‘type’ are deferred
words (*note Deferred Words::).  However, in that case you have to worry
about the restoration and the protection against exceptions yourself;
also, note that for redirecting the output in this way, you have to
redirect both ‘emit’ and ‘type’.


File: gforth.info,  Node: Directories,  Next: Search Paths,  Prev: Redirection,  Up: Files

6.22.4 Directories
------------------

You can split a file name into a directory and base component:

‘basename’ ( c-addr1 u1 - c-addr2 u2  ) gforth-0.7
   Given a file name c-addr1 u1, c-addr2 u2 is the part of it with any
leading directory components removed.

‘dirname’ ( c-addr1 u1 - c-addr1 u2  ) gforth-0.7
   C-addr1 u2 is the directory name of the file name c-addr1 u1,
including the final ‘/’.  If caddr1 u1 does not contain a ‘/’, u2=0.

   You can open and read directories similar to files.  Reading gives
you one directory entry at a time; you can match that to a filename
(with wildcards).

‘open-dir’ ( c-addr u - wdirid wior ) gforth-0.5 "open-dir"
   Open the directory specified by c-addr, u and return wdirid for
futher access to it.

‘read-dir’ ( c-addr u1 wdirid - u2 flag wior ) gforth-0.5 "read-dir"
   Attempt to read the next entry from the directory specified by wdirid
to the buffer of length u1 at address c-addr.  If the attempt fails
because there is no more entries, ior=0, flag=0, u2=0, and the buffer is
unmodified.  If the attempt to read the next entry fails because of any
other reason, return ior<>0.  If the attempt succeeds, store file name
to the buffer at c-addr and return ior=0, flag=true and u2 equal to the
size of the file name.  If the length of the file name is greater than
u1, store first u1 characters from file name into the buffer and
indicate "name too long" with ior, flag=true, and u2=u1.

‘close-dir’ ( wdirid - wior ) gforth-0.5 "close-dir"
   Close the directory specified by dir-id.

‘filename-match’ ( c-addr1 u1 c-addr2 u2 - flag ) gforth-0.5 "match-file"
   match the file name C-ADDR1 U1 with the pattern C-ADDR2 U2.  Patterns
match char by char except for the special characters '*' and '?', which
are wildcards for several ('*') or one ('?')  character.

‘get-dir’ ( c-addr1 u1 - c-addr2 u2 ) gforth-0.7 "get-dir"
   Store the current directory name in the buffer specified by c-addr1,
u1; if there is sufficient space, c-addr2=c-addr1 and u2 is the length
of the directory name.  If the buffer size is not sufficient, return 0 0

‘set-dir’ ( c-addr u - wior ) gforth-0.7 "set-dir"
   Change the current directory to c-addr, u.  Return an error if this
is not possible

‘=mkdir’ ( c-addr u wmode - wior ) gforth-0.7 "equals-mkdir"
   Create directory c-addr u with mode wmode modified by umask.  wmode
is a 9-bit number rwxrwxrwx (see ‘+fmode’, *note General files::).

‘mkdir-parents’ ( c-addr u mode - ior  ) gforth-0.7
   create the directory c-addr u and all its parents with mode mode
(modified by umask).  mode is a 9-bit number rwxrwxrwx (see ‘+fmode’,
*note General files::).


File: gforth.info,  Node: Search Paths,  Prev: Directories,  Up: Files

6.22.5 Search Paths
-------------------

If you specify an absolute filename (i.e., a filename starting with ‘/’
or ‘~’, or with ‘:’ in the second position (as in ‘C:...’)) for
‘included’ and friends, that file is included just as you would expect.

   If the filename starts with ‘./’, this refers to the directory that
the present file was ‘included’ from.  This allows files to include
other files relative to their own position (irrespective of the current
working directory or the absolute position).  This feature is essential
for libraries consisting of several files, where a file may include
other files from the library.  It corresponds to ‘#include "..."’ in C.
If the current input source is not a file, ‘.’ refers to the directory
of the innermost file being included, or, if there is no file being
included, to the current working directory.

   For relative filenames (not starting with ‘./’), Gforth uses a search
path similar to Forth's search order (*note Word Lists::).  It tries to
find the given filename in the directories present in the path, and
includes the first one it finds.  There are separate search paths for
Forth source files and general files.  If the search path contains the
directory ‘.’, this refers to the directory of the current file, or the
working directory, as if the file had been specified with ‘./’.

   Use ‘~+’ to refer to the current working directory (as in the
‘bash’).

‘absolute-file?’ ( addr u - flag  ) gforth-1.0 "absolute-file-question"
   A filename is absolute if it starts with a / or a ~ (~ expansion), or
if it is in the form ./*, extended regexp: ^[/~]|./, or if it has a
colon as second character ("C:...").  Paths simply containing a / are
not absolute!

* Menu:

* Source Search Paths::
* General Search Paths::


File: gforth.info,  Node: Source Search Paths,  Next: General Search Paths,  Prev: Search Paths,  Up: Search Paths

6.22.5.1 Source Search Paths
............................

The search path is initialized when you start Gforth (*note Invoking
Gforth::).  You can display it and change it using ‘fpath’ in
combination with the general path handling words.

‘fpath’ ( - path-addr  ) gforth-0.4

‘.fpath’ ( -  ) gforth-0.4 "dot-fpath"
   Display the contents of the Forth search path.

‘file>fpath’ ( addr1 u1 - addr2 u2  ) gforth-1.0 "file-to-fpath"
   Searches for a file with the name c-addr1 u1 in the ‘fpath’.  If
successful, c-addr u2 is the absolute file name or the file name
relative to the current working directory.  Throws an exception if the
file cannot be opened.

Here is an example of using ‘fpath’ and ‘require’:

     fpath path= /usr/lib/forth/|./
     require timer.fs


File: gforth.info,  Node: General Search Paths,  Prev: Source Search Paths,  Up: Search Paths

6.22.5.2 General Search Paths
.............................

Your application may need to search files in several directories, like
‘included’ does.  To facilitate this, Gforth allows you to define and
use your own search paths, by providing generic equivalents of the Forth
search path words:

‘open-path-file’ ( addr1 u1 path-addr - wfileid addr2 u2 0 | ior  ) gforth-0.2
   Look in path PATH-ADDR for the file specified by ADDR1 U1.  If found,
the resulting path and an (read-only) open file descriptor are returned.
If the file is not found, IOR is what came back from the last attempt at
opening the file (in the current implementation).

‘file>path’ ( c-addr1 u1 path-addr - c-addr2 u2  ) gforth-1.0 "file-to-path"
   Searches for a file with the name c-addr1 u1 in path stored in
path-addr.  If successful, c-addr u2 is the absolute file name or the
file name relative to the current working directory.  Throws an
exception if the file cannot be opened.

‘clear-path’ ( path-addr -  ) gforth-0.5
   Set the path path-addr to empty.

‘also-path’ ( c-addr len path-addr -  ) gforth-0.4
   add the directory c-addr len to path-addr.

‘.path’ ( path-addr -  ) gforth-0.4 "dot-path"
   Display the contents of the search path PATH-ADDR.

‘path+’ ( path-addr  "dir" -  ) gforth-0.4 "path-plus"
   Add the directory DIR to the search path PATH-ADDR.

‘path=’ ( path-addr "dir1|dir2|dir3" -  ) gforth-0.4 "path-equals"
   Make a complete new search path; the path separator is |.

   Here's an example of creating a custom search path:
     variable mypath \ no special allocation required, just a variable
     mypath path= /lib|/usr/lib \ assign initial directories
     mypath path+ /usr/local/lib \ append directory
     mypath .path \ output:"/lib /usr/lib /usr/local/lib"

   Search file and show resulting path:
     s" libm.so" mypath open-path-file throw type close-file \ output:"/lib/libm.so"


File: gforth.info,  Node: Blocks,  Next: Other I/O,  Prev: Files,  Up: Words

6.23 Blocks
===========

Traditionally, Forth has been used on systems without an operating
system(1), and in particular without a file system.  Forth provides a
mechanism, called “blocks”, for accessing mass storage on such systems.

   A block is a 1024-byte data area, which can be used to hold data or
Forth source code.  No structure is imposed on the contents of the
block.  A block is identified by its number; blocks are numbered
contiguously from 1 to an implementation-defined maximum.

   A typical system that used blocks but no operating system might use a
single floppy-disk drive for mass storage, with the disks formatted to
provide 256-byte sectors.  Blocks would be implemented by assigning the
first four sectors of the disk to block 1, the second four sectors to
block 2 and so on, up to the limit of the capacity of the disk.  The
disk would not contain any file system information, just the set of
blocks.

   On systems that do provide file services, blocks are typically
implemented by storing a sequence of blocks within a single “blocks
file”.  The size of the blocks file will be an exact multiple of 1024
bytes, corresponding to the number of blocks it contains.  This is the
mechanism that Gforth uses.

   Only one blocks file can be open at a time.  If you use block words
without having specified a blocks file, Gforth defaults to the blocks
file ‘blocks.fb’.  Gforth uses the Forth search path when attempting to
locate a blocks file (*note Source Search Paths::).

   When you access blocks, Gforth uses a number of “block buffers” as
intermediate storage.  The behaviour of the block buffers is analogous
to that of a cache.  Each block buffer has three states:

   • Unassigned
   • Assigned-clean
   • Assigned-dirty

   Initially, all block buffers are unassigned.  In order to access a
block, the block (specified by its block number) must be assigned to a
block buffer.

   The assignment of a block to a block buffer is performed by ‘block’
or ‘buffer’.  Use ‘block’ when you wish to modify the existing contents
of a block.  Use ‘buffer’ don't care about the existing contents of the
block and just want to overwrite it.

   Once a block has been assigned to a block buffer using ‘block’ or
‘buffer’, that block buffer becomes the current block buffer.  Data may
only be manipulated (read or written) within the current block buffer.

   When the contents of the current block buffer has been modified, it
is necessary, _before calling ‘block’ or ‘buffer’ again_, to either
abandon the changes (by doing nothing) or mark the block as changed
(assigned-dirty), using ‘update’.  Using ‘update’ does not change the
blocks file; it simply changes a block buffer's state to assigned-dirty.
The block will be written implicitly when it's buffer is needed for
another block, or explicitly by ‘flush’ or ‘save-buffers’.

   ‘Flush’ writes all assigned-dirty blocks back to the blocks file on
disk.  Leaving Gforth with ‘bye’ also performs a ‘flush’.

   When a block is used for storing source code, it is traditional to
display the contents as 16 lines each of 64 characters (with ‘list’).  A
block provides a single, continuous stream of input (for example, it
acts as a single parse area) - there are no end-of-line characters
within a block, and no end-of-file character at the end of a block.
There are two consequences of this:

   • The last character of one line A is contiguous with the first
     character of the following line B, so you need to either put at
     least one blank at the end of A, or at the start of B in order to
     separate the last word of A from the first word of B.
   • The word ‘\’ - comment to end of line - requires special treatment;
     in the context of a block it causes all characters until the end of
     the current 64-character "line" to be ignored.

   In Gforth, when you use ‘block’ with a non-existent block number, the
current blocks file will be extended to the appropriate size and the
block buffer will be initialised with spaces.

   Gforth includes a simple block editor (type ‘use blocked.fb 0 list’
for details) but doesn't encourage the use of blocks; the mechanism is
only provided for backward compatibility.

   Common techniques that are used when working with blocks include:

   • A screen editor that allows you to edit blocks without leaving the
     Forth environment.
   • Shadow screens; where every code block has an associated block
     containing comments (for example: code in odd block numbers,
     comments in even block numbers).  Typically, the block editor
     provides a convenient mechanism to toggle between code and
     comments.
   • Load blocks; a single block (typically block 1) contains a number
     of ‘thru’ commands which ‘load’ the whole of the application.

   See Frank Sergeant's Pygmy Forth to see just how well blocks can be
integrated into a Forth programming environment.

‘open-blocks’ ( c-addr u -  ) gforth-0.2
   C-addr u is the name of a file; ‘open-blocks’ opens this file as the
current blocks file.

‘use’ ( "file" -  ) gforth-0.2
   Open file as the current blocks file.

‘get-block-fid’ ( - wfileid  ) gforth-0.2
   Return the file-id of the current blocks file.  If no blocks file has
been opened, use ‘blocks.fb’ as the default blocks file.

‘block-offset’ ( - addr  ) gforth-0.5
   User variable containing the number of the first block (default since
0.5.0: 0).  Block files created with Gforth versions before 0.5.0 have
the offset 1.  If you use these files you can: ‘1 offset !’; or add 1 to
every block number used; or prepend 1024 characters to the file.

‘block’ ( u - addr  ) block
   The contents of block u are found at addr (and the following 1023
bytes).  Addr is valid until there is another call to ‘block’ or
‘buffer’ (possibly inside another block-access word).  If the block is
not yet in a buffer, ‘block’ reads it from mass storage.

‘buffer’ ( u - addr  ) block
   ‘Addr’ (and the following 1023 bytes) are the buffer of block u; this
memory area is initialized arbitrarily.  Addr is valid until there is
another call to ‘block’ or ‘buffer’ (possibly inside another
block-access word).  The subtle difference between ‘buffer’ and ‘block’
mean that you should only use ‘buffer’ if you don't care about the
previous contents of block u.

‘update’ ( -  ) block
   Mark the state of the current block buffer as assigned-dirty.

‘updated?’ ( u - f  ) gforth-0.2 "updated-question"
   If and only if there is a buffer for block u and it has been
‘update’d, return true.

‘save-buffers’ ( -  ) block
   Transfer the contents of each ‘update’d block buffer to mass storage,
then mark all block buffers as assigned-clean.

‘empty-buffers’ ( -  ) block-ext
   Mark all block buffers as unassigned; if any had been marked as
assigned-dirty (by ‘update’), the changes to those blocks will be lost.

‘flush’ ( -  ) block
   Perform the functions of ‘save-buffers’ then ‘empty-buffers’.

‘list’ ( u -  ) block-ext
   Display block u as 16 numbered lines, each of 64 characters.

‘scr’ ( - a-addr  ) block-ext "s-c-r"
   User variable containing the block number of the block most recently
processed by ‘list’.

‘load’ ( i*x u - j*x  ) block
   Text-interpret block u.  Block 0 cannot be ‘load’ed.

‘thru’ ( i*x n1 n2 - j*x  ) block-ext
   ‘load’ the blocks n1 up to and including n2 in sequence.

‘+load’ ( i*x n - j*x  ) gforth-0.2 "plus-load"
   Used within a block to load the block specified as the current block
+ n.

‘+thru’ ( i*x n1 n2 - j*x  ) gforth-0.2 "plus-thru"
   Used within a block to load the range of blocks specified as the
current block + n1 up to and including the current block + n2.

‘-->’ ( -  ) gforth-0.2 "dash-dash-greater-than"
   If this symbol is encountered whilst loading block n, discard the
remainder of the block and load block n+1.  Used for chaining multiple
blocks together as a single loadable unit.  Not recommended, because it
destroys the independence of loading.  Use ‘thru’ (which is standard) or
‘+thru’ instead.

‘block-included’ ( a-addr u -  ) gforth-0.2
   Use within a block that is to be processed by ‘load’.  Save the
current blocks file specification, open the blocks file specified by
a-addr u and ‘load’ block 1 from that file (which may in turn chain or
load other blocks).  Finally, close the blocks file and restore the
original blocks file.

   ---------- Footnotes ----------

   (1) This is called “native”, whereas Forth running on top of an OS is
called “hosted”.


File: gforth.info,  Node: Other I/O,  Next: OS command line arguments,  Prev: Blocks,  Up: Words

6.24 Other I/O
==============

* Menu:

* Simple numeric output::       Predefined formats
* Floating-point output::
* Miscellaneous output::
* Displaying characters and strings::  Other stuff
* Terminal output::             Cursor positioning etc.
* Single-key input::
* String input from the terminal::
* Pipes::                       How to create your own pipes
* CSV reading and writing::


File: gforth.info,  Node: Simple numeric output,  Next: Floating-point output,  Prev: Other I/O,  Up: Other I/O

6.24.1 Simple numeric output
----------------------------

The simplest output functions are those that display integers from the
data stack.  Numbers are displayed in the base (aka radix) stored in
‘base’ (*note Base and integer decimal point::).  For outputting
integers with additional formatting requirements *note Integer to string
conversion::.

‘.’ ( n -  ) core "dot"
   Display (the signed single number) N in free-format, followed by a
space.

‘dec.’ ( n -  ) gforth-0.2 "dec-dot"
   Display n as a signed decimal number, followed by a space.

‘h.’ ( u -  ) gforth-1.0 "h-dot"
   Display u as an unsigned hex number, prefixed with a "$" and followed
by a space.

‘hex.’ ( u -  ) gforth-0.2 "hex-dot"
   Display u as an unsigned hex number, prefixed with a ‘$’ and followed
by a space.  Another name for this word is ‘h.’, which is present in
several other systems, but not in Gforth before 1.0.

‘u.’ ( u -  ) core "u-dot"
   Display (the unsigned single number) U in free-format, followed by a
space.

‘.r’ ( n1 n2 -  ) core-ext "dot-r"
   Display N1 right-aligned in a field N2 characters wide.  If more than
N2 characters are needed to display the number, all digits and, if
necessary, the sign "-", are displayed.

‘u.r’ ( u n -  ) core-ext "u-dot-r"
   Display U right-aligned in a field N characters wide.  If more than N
characters are needed to display the number, all digits are displayed.

‘dec.r’ ( u n -  ) gforth-0.5 "dec-dot-r"
   Display u as a unsigned decimal number in a field n characters wide.

‘d.’ ( d -  ) double "d-dot"
   Display (the signed double number) D in free-format.  followed by a
space.

‘ud.’ ( ud -  ) gforth-0.2 "u-d-dot"
   Display (the signed double number) UD in free-format, followed by a
space.

‘d.r’ ( d n -  ) double "d-dot-r"
   Display D right-aligned in a field N characters wide.  If more than N
characters are needed to display the number, all digits and, if
necessary, the sign "-", are displayed.

‘ud.r’ ( ud n -  ) gforth-0.2 "u-d-dot-r"
   Display UD right-aligned in a field N characters wide.  If more than
N characters are needed to display the number, all digits are displayed.


File: gforth.info,  Node: Floating-point output,  Next: Miscellaneous output,  Prev: Simple numeric output,  Up: Other I/O

6.24.2 Floating-point output
----------------------------

Floating-point output is always displayed using decimal base (even if
‘BASE’ is different).

‘f.’ ( r -  ) floating-ext "f-dot"
   Display (the floating-point number) r without exponent, followed by a
space.

‘fe.’ ( r -  ) floating-ext "f-e-dot"
   Display r using engineering notation (with exponent dividable by 3),
followed by a space.

‘fs.’ ( r -  ) floating-ext "f-s-dot"
   Display r using scientific notation (with exponent), followed by a
space.

‘fp.’ ( r -  ) floating-ext "f-p-dot"
   Display r using SI prefix notation (with exponent dividable by 3,
converted into SI prefixes if available), followed by a space.

   Examples of printing the number 1234.5678E23 in the different
floating-point output formats are shown below.

     f. 123456780000000000000000000.
     fe. 123.456780000000E24
     fs. 1.23456780000000E26
     fp. 123.456780000000Y

   The length of the output is influenced by:

‘precision’ ( - u  ) floating-ext
   u is the number of significant digits currently used by ‘F.’ ‘FE.’
and ‘FS.’

‘set-precision’ ( u -  ) floating-ext
   Set the number of significant digits currently used by ‘F.’ ‘FE.’ and
‘FS.’ to u.

   You can control the output in more detail with:

‘f.rdp’ ( rf +nr +nd +np -  ) gforth-0.6 "f-dot-rdp"
   Print float rf formatted.  The total width of the output is nr.  For
fixed-point notation, the number of digits after the decimal point is
+nd and the minimum number of significant digits is np.  ‘Set-precision’
has no effect on ‘f.rdp’.  Fixed-point notation is used if the number of
siginicant digits would be at least np and if the number of digits
before the decimal point would fit.  If fixed-point notation is not
used, exponential notation is used, and if that does not fit, asterisks
are printed.  We recommend using nr>=7 to avoid the risk of numbers not
fitting at all.  We recommend nr>=np+5 to avoid cases where ‘f.rdp’
switches to exponential notation because fixed-point notation would have
too few significant digits, yet exponential notation offers fewer
significant digits.  We recommend nr>=nd+2, if you want to have
fixed-point notation for some numbers; the smaller the value of np, the
more cases are shown in fixed-point notation (cases where few or no
significant digits remain in fixed-point notation).  We recommend np>nr,
if you want to have exponential notation for all numbers.

   To give you a better intuition of how they influence the output, here
are some examples of parameter combinations; in each line the same
number is printed, in each column the same parameter combination is used
for printing:

         12 13 0    7 3 4   7 3 0   7 3 1   7 5 1   7 7 1   7 0 2  4 2 1
     |-1.234568E-6|-1.2E-6| -0.000|-1.2E-6|-1.2E-6|-1.2E-6|-1.2E-6|****|
     |-1.234568E-5|-1.2E-5| -0.000|-1.2E-5|-.00001|-1.2E-5|-1.2E-5|****|
     |-1.234568E-4|-1.2E-4| -0.000|-1.2E-4|-.00012|-1.2E-4|-1.2E-4|****|
     |-1.234568E-3|-1.2E-3| -0.001| -0.001|-.00123|-1.2E-3|-1.2E-3|****|
     |-1.234568E-2|-1.2E-2| -0.012| -0.012|-.01235|-1.2E-2|-1.2E-2|-.01|
     |-1.234568E-1|-1.2E-1| -0.123| -0.123|-.12346|-1.2E-1|-1.2E-1|-.12|
     |-1.2345679E0| -1.235| -1.235| -1.235|-1.23E0|-1.23E0|-1.23E0|-1E0|
     |-1.2345679E1|-12.346|-12.346|-12.346|-1.23E1|-1.23E1|   -12.|-1E1|
     |-1.2345679E2|-1.23E2|-1.23E2|-1.23E2|-1.23E2|-1.23E2|  -123.|-1E2|
     |-1.2345679E3|-1.23E3|-1.23E3|-1.23E3|-1.23E3|-1.23E3| -1235.|-1E3|
     |-1.2345679E4|-1.23E4|-1.23E4|-1.23E4|-1.23E4|-1.23E4|-12346.|-1E4|
     |-1.2345679E5|-1.23E5|-1.23E5|-1.23E5|-1.23E5|-1.23E5|-1.23E5|-1E5|


File: gforth.info,  Node: Miscellaneous output,  Next: Displaying characters and strings,  Prev: Floating-point output,  Up: Other I/O

6.24.3 Miscellaneous output
---------------------------

‘cr’ ( -  ) core "c-r"
   Output a newline (of the favourite kind of the host OS). Note that
due to the way the Forth command line interpreter inserts newlines, the
preferred way to use ‘cr’ is at the start of a piece of text; e.g., ‘cr
." hello, world"’.

‘space’ ( -  ) core
   Display one space.

‘spaces’ ( u -  ) core
   Display U spaces.

‘out’ ( - addr  ) gforth-1.0
   Addr contains a number that tries to give the position of the cursor
within the current line on the user output device: It resets to 0 on
‘cr’, increases by the number of characters by ‘type’ and ‘emit’, and
decreases on ‘backspaces’.  Unfortunately, it does not take into account
tabs, multi-byte characters, or the existence of Unicode characters with
width 0 and 2, so it only works for simple cases.

‘.\"’ ( compilation 'ccc"' - ; run-time -  ) gforth-0.6 "dot-backslash-quote"
   Like ‘."’, but translates C-like \-escape-sequences (see ‘S\"’).

‘."’ ( compilation 'ccc"' - ; run-time -  ) core "dot-quote"
   Compilation: Parse a string ccc delimited by a " (double quote).  At
run-time, display the string.  Interpretation semantics for this word
are undefined in standard Forth.  Gforth's interpretation semantics are
to display the string.

‘.(’ ( compilation&interpretation 'ccc<close-paren>' -  ) core-ext "dot-paren"
   Compilation and interpretation semantics: Parse a string ccc
delimited by a ‘)’ (right parenthesis).  Display the string.  This is
often used to display progress information during compilation; see
examples below.

   If you don't want to worry about whether to use ‘.( hello)’ or ‘."
hello"’, you can write ‘"hello" type’, which gives you what you usually
want (but is less portable to other Forth systems).

As an example, consider the following program:

     .( text-1)     \ prints "text-1"
     : my-word
       ." text-2"
       .( text-3)   \ prints "text-3"
       "text-4" type
     ;

     my-word        \ prints "text-2text-4"

     ." text-5"     \ prints "text-5"
     "text-6" type  \ prints "text-6"

   If you want to understand why this code behaves this way, the
explanations for this concrete example are:

   • Messages ‘text-1’ and ‘text-3’ are displayed because ‘.(’ is an
     immediate word; it behaves in the same way whether it is used
     inside or outside a colon definition (*note Interpretation and
     Compilation Semantics::).
   • Message ‘text-2’ is not displayed during the definition of
     ‘my-word’, because the text interpreter performs the compilation
     semantics for ‘."’.  Later the interpretation semantics of
     ‘my-word’ are performed, and they perform the run-time semantics of
     ‘."’.
   • Message ‘text-4’ is not displayed during the definition of
     ‘my-word’, because ‘"text-4"’ (see ‘rec-string’,
     ‘translate-string’) performs the compiling run-time for the string,
     which compiles the interpreting run-time (*note Defining
     recognizers::) into ‘my-word’, and ‘type’ compiles the
     interpretation/execution semantics of ‘type’ into ‘my-word’.  Later
     the interpretation semantics of ‘my-word’ are performed, and they
     perform the compiled interpreting run-time and interpretation
     semantics.
   • Message ‘text-5’ is displayed because of Gforth's added
     interpretation semantics for ‘."’.
   • Message ‘text-6’ is displayed because ‘"text-6" type’ is
     interpreted.


File: gforth.info,  Node: Displaying characters and strings,  Next: Terminal output,  Prev: Miscellaneous output,  Up: Other I/O

6.24.4 Displaying characters and strings
----------------------------------------

‘type’ ( c-addr u -  ) core
   If U>0, display U characters from a string starting with the
character stored at C-ADDR.

‘xemit’ ( xc -  ) xchar "x-emit"
   Display extended char xc.

‘emit’ ( c -  ) core
   Display the byte c; for ASCII characters, ‘emit’ is equivalent to
‘xemit’; for multi-byte characters, additional ‘emit’ or ‘type’ calls
may be needed to display a complete character.

‘typewhite’ ( c-addr u -  ) gforth-0.2
   Like ‘type’, but white space is printed instead of the characters.
For now, only works correctly for strings of ASCII characters.


File: gforth.info,  Node: Terminal output,  Next: Single-key input,  Prev: Displaying characters and strings,  Up: Other I/O

6.24.5 Terminal output
----------------------

If you are outputting to a terminal, you may want to control the
positioning of the cursor:

‘at-xy’ ( x y -  ) facility "at-x-y"
   Put the curser at position x y.  The top left-hand corner of the
display is at 0 0.

‘at-deltaxy’ ( dx dy -  ) gforth-0.7
   With the current position at x y, put the cursor at x+dx y+dy.

   In order to know where to position the cursor, it is often helpful to
know the size of the screen:

‘form’ ( - nlines ncols  ) gforth-0.2

   And sometimes you want to use:

‘page’ ( -  ) facility
   Clear the screen

   Note that on non-terminals you should use ‘#ff emit’, not ‘page’, to
get a form feed.

* Menu:

* Color output::
* Color themes::


File: gforth.info,  Node: Color output,  Next: Color themes,  Prev: Terminal output,  Up: Terminal output

6.24.5.1 Color output
.....................

The following words are used to create (semantic) colorful output;
further output is produced in the color and style given by the word; the
actual color and style depends on the theme (*note Color themes::) and
on your terminal setup.(1)

‘default-color’ ( -  ) gforth-1.0
   Future terminal output will use the system-default color

‘error-color’ ( -  ) gforth-1.0
   Future terminal output will use the error color (red)

‘error-hl-inv’ ( -  ) gforth-1.0
   Future terminal output will be shown in the inverted error color
(background color on red)

‘error-hl-ul’ ( -  ) gforth-1.0
   Future terminal output will be shown in the error color (red) and
underlined.

‘warning-color’ ( -  ) gforth-1.0
   Future terminal output will use the color for warnings (‘light-mode’:
blue, ‘dark-mode’: yellow)

‘info-color’ ( -  ) gforth-1.0
   Future terminal output will use the color for informative output
(‘light-mode’: green, ‘dark-mode’: cyan)

‘success-color’ ( -  ) gforth-1.0
   Future terminal output will use the color for success (green)

‘input-color’ ( -  ) gforth-1.0
   Future terminal output will use the color for user-input
(‘light-mode’: bold black, ‘dark-mode’: bold white, ‘magenta-input’:
magenta)

‘status-color’ ( -  ) gforth-1.0
   Future terminal output will be shown in the color for the
interpret-state status bar (inverted blue)

‘compile-color’ ( -  ) gforth-1.0
   Future terminal output will be shown in the color for the
compile-state status bar (inverted magenta)

‘postpone-color’ ( -  ) gforth-1.0
   Future terminal output will be shown in the color for the
postpone-state status bar (inverted red)

   ---------- Footnotes ----------

   (1) <https://www.complang.tuwien.ac.at/anton/xterm-colors/>


File: gforth.info,  Node: Color themes,  Prev: Color output,  Up: Terminal output

6.24.5.2 Color themes
.....................

Depending on whether you use a light or dark background, some colors
tend to lead to too-low contrast.  Therefore, Gforth supports adjusting
its colors to the background with ‘light-mode’ (for light background)
and ‘dark-mode’ for dark background.

   Gforth tries to select the right mode automatically, but that does
not always work.  In order to avoid having to set the theme every time
you enter Gforth, you can set the environment variable ‘GFORTH_INIT’
before starting Gforth.  Possible values are: ‘light’, ‘dark’,
‘uncolored’, or ‘auto’ (default).

   In addition, you can specify an input theme (separated from the mode
theme by a space in ‘GFORTH_INIT’ if both are present): ‘magenta’ or
‘default’ (default).

‘light-mode’ ( -  ) gforth-1.0
   Color theme for white background: sets the colors for future uses of
color output words (*note Color output::).

‘dark-mode’ ( -  ) gforth-1.0
   Color theme for black background: sets the colors for future uses of
color output words (*note Color output::).

‘uncolored-mode’ ( -  ) gforth-1.0
   "Color theme" that does not set colors: all the color output words
(*note Color output::) just set the default colors or (for status bar
colors) the inverted default colors.  This mode does not set colors, but
uses the default ones.

‘magenta-input’ ( -  ) gforth-1.0
   Future use of ‘input-color’ will result in further output in magenta,
which may be easier to recognize in presentations than just bold.

‘default-input’ ( -  ) gforth-1.0
   Future use of ‘input-color’ will result in further output in bold
foreground color (the default setting).


File: gforth.info,  Node: Single-key input,  Next: String input from the terminal,  Prev: Terminal output,  Up: Other I/O

6.24.6 Single-key input
-----------------------

If you want to get a single byte, you can use ‘key’; to check whether a
character is available for ‘key’, you can use ‘key?’.

‘key’ ( - c  ) core
   Receive (but do not display) one byte c.

‘key-ior’ ( - c|ior  ) gforth-1.0
   Receive (but do not display) one byte c.  In case of an error or
interrupt, return the negative IOR instead.

‘key?’ ( - flag  ) facility "key-question"
   If a byte is available for receiving with ‘key’, return true,
otherwise false.

‘xkey’ ( - xc  ) xchar "x-key"
   Reads an extended character xc xchar from the terminal without
printing it.  This will discard all input events until all bytes of xc
have been received.

‘xkey?’ ( - flag  ) xchar "x-key-query"
   Ideally this word would return true if a complete extended char is
available for input, otherwise false.  Unfortunately, currently also a
partial extended character results in returning true.

   If you want to process a mix of printable and non-printable
characters, you can do that with ‘ekey’ and friends.  ‘Ekey’ produces a
keyboard event that you have to convert into a character with
‘ekey>char’ or into a key identifier with ‘ekey>fkey’.

   Typical code for using EKEY looks like this:

     ekey ekey>xchar if ( xc )
       ... \ do something with the character
     else ekey>fkey if ( key-id )
       case
         k-up                                  of ... endof
         k-f1                                  of ... endof
         k-left k-shift-mask or k-ctrl-mask or of ... endof
         ...
       endcase
     else ( keyboard-event )
       drop \ just ignore an unknown keyboard event type
     then then

‘ekey’ ( - u  ) facility-ext "e-key"
   Receive a keyboard event U (encoding implementation-defined).

‘ekey>xchar’ ( u - u false | xc true  ) xchar-ext "e-key-to-x-char"
   Convert keyboard event u into extended char xc.  If that is possible,
return xt and true, otherise u and false.

‘ekey>char’ ( u - u false | c true  ) facility-ext "e-key-to-char"
   Convert keyboard event u into the ASCII char c.  If that is possible,
return c and true, otherise u and false.  Instead of ‘ekey>char’, use
‘ekey>xchar’ if available.

‘ekey>fkey’ ( u1 - u2 f  ) facility-ext "e-key-to-f-key"
   If u1 is a keyboard event in the special key set, convert keyboard
event U1 into key id U2 and return true; otherwise return U1 and false.

‘ekey?’ ( - flag  ) facility-ext "e-key-question"
   If a keyboard event is available for receiving with ‘ekey’, return
true, otherwise false.

   The key identifiers for cursor keys are:

‘k-left’ ( - u  ) facility-ext

‘k-right’ ( - u  ) facility-ext

‘k-up’ ( - u  ) facility-ext

‘k-down’ ( - u  ) facility-ext

‘k-home’ ( - u  ) facility-ext
   aka Pos1

‘k-end’ ( - u  ) facility-ext

‘k-prior’ ( - u  ) facility-ext
   aka PgUp

‘k-next’ ( - u  ) facility-ext
   aka PgDn

‘k-insert’ ( - u  ) facility-ext

‘k-delete’ ( - u  ) facility-ext
   the <DEL> key on my xterm, not backspace

   The key identifiers for function keys (aka keypad keys) are:

‘k-f1’ ( - u  ) facility-ext "k-f-1"

‘k-f2’ ( - u  ) facility-ext "k-f-2"

‘k-f3’ ( - u  ) facility-ext "k-f-3"

‘k-f4’ ( - u  ) facility-ext "k-f-4"

‘k-f5’ ( - u  ) facility-ext "k-f-5"

‘k-f6’ ( - u  ) facility-ext "k-f-6"

‘k-f7’ ( - u  ) facility-ext "k-f-7"

‘k-f8’ ( - u  ) facility-ext "k-f-8"

‘k-f9’ ( - u  ) facility-ext "k-f-9"

‘k-f10’ ( - u  ) facility-ext "k-f-10"

‘k-f11’ ( - u  ) facility-ext "k-f-11"

‘k-f12’ ( - u  ) facility-ext "k-f-12"

   Note that ‘k-f11’ and ‘k-f12’ are not as widely available.

   You can combine these key identifiers with masks for various shift
keys:

‘k-shift-mask’ ( - u  ) facility-ext

‘k-ctrl-mask’ ( - u  ) facility-ext

‘k-alt-mask’ ( - u  ) facility-ext

   There are a number of keys that have ASCII values, and therefore are
unlikely to be reported as special keys, but the combination of these
keys with shift keys may be reported as a special key:

‘k-enter’ ( - u  ) gforth-1.0

‘k-backspace’ ( - u  ) gforth-1.0

‘k-tab’ ( - u  ) gforth-1.0

   Moreover, there are the following key codes for keys and other
events:

‘k-winch’ ( - u  ) gforth-1.0
   This key code may be generated when the user changes the window size;
if you have cached the value returned by ‘form’, this indicates that you
should update your cache.

‘k-pause’ ( - u  ) gforth-1.0

‘k-mute’ ( - u  ) gforth-1.0

‘k-volup’ ( - u  ) gforth-1.0

‘k-voldown’ ( - u  ) gforth-1.0

‘k-sel’ ( - u  ) gforth-1.0

‘k-eof’ ( - u  ) gforth-1.0

   Note that, even if a Forth system has ‘ekey>fkey’ and the key
identifier words, the keys are not necessarily available or it may not
necessarily be able to report all the keys and all the possible
combinations with shift masks.  Therefore, write your programs in such a
way that they are still useful even if the keys and key combinations
cannot be pressed or are not recognized.

   Examples: Older keyboards often do not have an F11 and F12 key.  If
you run Gforth in an xterm, the xterm catches a number of combinations
(e.g., <Shift-Up>), and never passes it to Gforth.  Finally, Gforth
currently does not recognize and report combinations with multiple shift
keys (so the <shift-ctrl-left> case in the example above would never be
entered).

   Gforth recognizes various keys available on ANSI terminals (in MS-DOS
you need the ANSI.SYS driver to get that behaviour); it works by
recognizing the escape sequences that ANSI terminals send when such a
key is pressed.  If you have a terminal that sends other escape
sequences, you will not get useful results on Gforth.  Other Forth
systems may work in a different way.

   Gforth also provides a few words for outputting names of function
keys:

‘fkey.’ ( u -  ) gforth-1.0 "fkey-dot"
   Print a string representation for the function key u.  U must be a
function key (possibly with modifier masks), otherwise there may be an
exception.

‘simple-fkey-string’ ( u1 - c-addr u  ) gforth-1.0
   c-addr u is the string name of the function key u1.  Only works for
simple function keys without modifier masks.  Any u1 that does not
correspond to a simple function key currently produces an exception.


File: gforth.info,  Node: String input from the terminal,  Next: Pipes,  Prev: Single-key input,  Up: Other I/O

6.24.7 String input from the terminal
-------------------------------------

For ways of storing character strings in memory see *note String
representations::.

   Words for inputting one line from the keyboard:

‘accept’ ( c-addr +n1 - +n2  ) core
   Get a string of up to N1 characters from the user input device and
store it at C-ADDR.  N2 is the length of the received string.  The user
indicates the end by pressing <RET>.  Gforth supports all the editing
functions available on the Forth command line (including history and
word completion) in ‘accept’.

‘edit-line’ ( c-addr n1 n2 - n3  ) gforth-0.6
   edit the string with length N2 in the buffer C-ADDR N1, like
‘accept’.

   Obsolete words:

‘expect’ ( c-addr +n -  ) gforth-obsolete
   Receive a string of at most +n characters, and store it in memory
starting at c-addr.  The string is displayed.  Input terminates when the
<return> key is pressed or +n characters have been received.  The normal
Gforth line editing capabilites are available.  The length of the string
is stored in ‘span’; it does not include the <return> character.
OBSOLETE: This word has been de-standardized in Forth-2012.  Use
‘accept’ instead.

‘span’ ( - addr  ) gforth-obsolete
   The variable at addr contains the length of the last string received
by ‘expect’.  OBSOLETE: This word has been de-standardized in
Forth-2012.  Use ‘accept’ instead.


File: gforth.info,  Node: Pipes,  Next: CSV reading and writing,  Prev: String input from the terminal,  Up: Other I/O

6.24.8 Pipes
------------

In addition to using Gforth in pipes created by other processes (*note
Gforth in pipes::), you can create your own pipe with ‘open-pipe’, and
read from or write to it.

‘open-pipe’ ( c-addr u wfam - wfileid wior ) gforth-0.2 "open-pipe"
   c-addr u is the name/path of an OS-level program.  If wfam is ‘r/o’,
the standard output of the program is piped into the Gforth process and
can be read from wfileid.  If wfam is ‘w/o’, data written to wfileid is
piped as standard input into the program.  wior is 0 if and only if
opening the pipe succeeded.

‘close-pipe’ ( wfileid - wretval wior ) gforth-0.2 "close-pipe"
   Closes a pipe wfileid opened with ‘open-pipe’.  If wior is 0, wretval
is the exit code of the command invoked by ‘open-pipe’.

   If you write to a pipe, Gforth can throw a ‘broken-pipe-error’; if
you don't catch this exception, Gforth will catch it and exit, usually
silently (*note Gforth in pipes::).  Since you probably do not want
this, you should wrap a ‘catch’ or ‘try’ block around the code from
‘open-pipe’ to ‘close-pipe’, so you can deal with the problem yourself,
and then return to regular processing.

‘broken-pipe-error’ ( - n  ) gforth-0.6
   the error number for a broken pipe


File: gforth.info,  Node: CSV reading and writing,  Prev: Pipes,  Up: Other I/O

6.24.9 CSV Reader
-----------------

Comma-separated values (CSV) are a popular text format to interchange
data.  Gforth provides words for reading CSV files (with all features,
including newlines in quoted strings).

‘read-csv’ ( c-addr u xt -  ) gforth-experimental
   Read the CSV file with the name given by c-addr u and execute xt for
every field found.
Xt ‘( c-addr2 u2 field line -- )’ is called once for each field; c-addr2
u2 is the decoded field content, field is the field number (starting
with 0), and line is the line number (starting with 1).

‘csv-separator’ ( - c  ) gforth-experimental
   CSV field separator (default is ',', hence the name
"comma-separated"); this is a value and can be changed with ‘to
csv-separator’.

‘csv-quote’ ( - c  ) gforth-experimental
   CSV quote character (default is ‘"’); this is a value and can be
changed with ‘to csv-quote’.

‘.quoted-csv’ ( c-addr u -  ) gforth-experimental "dot-quoted-csv"
   print a field in CSV format, i.e., with enough quotes that ‘read-csv’
will produce c-addr u when encountering the output of ‘.quoted-csv’.


File: gforth.info,  Node: OS command line arguments,  Next: Locals,  Prev: Other I/O,  Up: Words

6.25 OS command line arguments
==============================

The usual way to pass arguments to Gforth programs on the command line
is via the ‘-e’ option, e.g.

     gforth -e "123 456" foo.fs -e bye

   However, you may want to interpret the command-line arguments
directly.  In that case, you can access the (image-specific)
command-line arguments through ‘next-arg’:

‘next-arg’ ( - addr u  ) gforth-0.7
   get the next argument from the OS command line, consuming it; if
there is no argument left, return ‘0 0’.

   Here's an example program ‘echo.fs’ for ‘next-arg’:

     : echo ( -- )
         begin
             next-arg 2dup 0 0 d<> while
                 type space
         repeat
         2drop ;

     echo cr bye

   This can be invoked with

     gforth echo.fs hello world

   and it will print

     hello world

   The next lower level of dealing with the OS command line are the
following words:

‘arg’ ( u - addr count  ) gforth-0.2
   Return the string for the uth command-line argument; returns ‘0 0’ if
the access is beyond the last argument.  ‘0 arg’ is the program name
with which you started Gforth.  The next unprocessed argument is always
‘1 arg’, the one after that is ‘2 arg’ etc.  All arguments already
processed by the system are deleted.  After you have processed an
argument, you can delete it with ‘shift-args’.

‘shift-args’ ( -  ) gforth-0.7
   ‘1 arg’ is deleted, shifting all following OS command line parameters
to the left by 1, and reducing ‘argc @’.  This word can change ‘argv @’.

   Finally, at the lowest level Gforth provides the following words:

‘argc’ ( - addr  ) gforth-0.2
   ‘Variable’ - the number of command-line arguments (including the
command name).  Changed by ‘next-arg’ and ‘shift-args’.

‘argv’ ( - addr  ) gforth-0.2
   ‘Variable’ - a pointer to a vector of pointers to the command-line
arguments (including the command-name).  Each argument is represented as
a C-style zero-terminated string.  Changed by ‘next-arg’ and
‘shift-args’.


File: gforth.info,  Node: Locals,  Next: Object-oriented Forth,  Prev: OS command line arguments,  Up: Words

6.26 Locals
===========

Local variables can make Forth programming more enjoyable and Forth
programs easier to read.

   Gforth implements an extended version of the standard Forth locals.

* Menu:

* Gforth locals::
* Standard Forth locals::


File: gforth.info,  Node: Gforth locals,  Next: Standard Forth locals,  Prev: Locals,  Up: Locals

6.26.1 Gforth locals
--------------------

Gforth locals are a superset of standard locals.  Locals can be defined
with

     {: local1 local2 ... -- comment :}
   or
     {: local1 local2 ... :}
   or
     {: local1 local2 ... | ulocal0 ulocal1 -- comment :}

   E.g.,
     : max {: n1 n2 -- n3 :}
      n1 n2 > if
        n1
      else
        n2
      endif ;

   The locals definition ‘{: n1 n2 -- n3 :}’ consumes two cells at
run-time, and, as one would expect, puts the top-of-stack in ‘n2’ and
the second stack item in ‘n1’.  The part behind the ‘--’ is just a
comment.  The occurences of the locals ‘n1’ and ‘n2’ push the respective
value on the stack.

   The similarity of locals definitions with stack comments is intended.
A locals definition often replaces the stack comment of a word.  The
order of the locals corresponds to the order in a stack comment and
everything after the ‘--’ is really a comment.

   The name of the local may be preceded by a type specifier, e.g., ‘F:’
for a floating point value:

     : CX* {: F: Ar F: Ai F: Br F: Bi -- Cr Ci :}
     \ complex multiplication
      Ar Br f* Ai Bi f* f-
      Ar Bi f* Ai Br f* f+ ;

   Gforth currently supports cells (‘W:’, ‘W^’), doubles (‘D:’, ‘D^’),
floats (‘F:’, ‘F^’), characters (‘C:’, ‘C^’), and xts (‘xt:’) in several
flavours:

“value-flavoured”
     (*note Values::) You define a value-flavoured local with no type
     specifier (equivalent to ‘W:’), with ‘W:’, ‘D:’, ‘F:’ or ‘C:’.
     When later using the name of a value-flavoured local on its own, it
     pushes the value of the local.  You can also change a
     value-flavoured local ‘x’ with ‘TO x’, ‘->x’, ‘+TO x’ or ‘+>x’.
     Also, if you put ‘addressable:’ in front of the locals definition,
     you can get the address of ‘x’ with ‘ADDR x’ or ‘'>x’ (*note How
     long do locals live?::).

“variable-flavoured”
     (*note Variables::) A variable-flavoured local (defined with ‘W^’,
     ‘D^’, ‘F^’, ‘C^’) produces its address (*note How long do locals
     live?::).  E.g., the standard word ‘emit’ can be defined in terms
     of ‘type’ like this:

          : emit {: C^ char* -- :}
              char* 1 type ;

     In addition, if you define a local whose name ends in a ‘[’, used
     only without type specifier, the result is a variable-flavoured
     local, with the size given between the local name and ‘]’.  The
     size is given by a piece of Forth code that is interpreted and must
     have the stack effect ‘( -- u )’, where u is the size of the local
     in bytes.  If such a local occurs in front of ‘|’, it is
     initialized by copying u bytes from an address given on the stack.
     If such a local occurs behind ‘|’, it is uninitialized.  The square
     bracket ‘[’ is part of the defined name.  E.g., the ‘emit’ example
     above can also be coded as:

          : emit ( c -- )
              {: | char[ 1 chars ] :}
              char[ c! char[ 1 type ;

“defer-flavoured”
     (*note Deferred Words::) You define a defer-flavoured local ‘x’
     with ‘XT: x’, and the stack item that you store there (e.g., when
     the local is initialized from the stack at its definition) must be
     an execution token.  When you later use ‘x’ on its own, the
     execution token stored in the local is ‘execute’d.  You can get the
     xt out of ‘x’ with ‘ACTION-OF x’ or ‘@>x’ and change the execution
     token stored in ‘x’ with ‘IS x’ or ‘=>x’.  If you defined ‘x’ with
     ‘addressable: xt: x’, you can use ‘addr x’ or ‘'>x’ to get the
     address where the xt is stored (*note How long do locals live?::).

     E.g., the standard word ‘execute’ can be defined with a
     defer-flavoured local like this:

          : execute {: xt: x -- :}
            x ;

   A local without type specifier is a ‘W:’ local, unless its name ends
in ‘[’; in that case it's a variable-flavoured local.  You can also
leave away the ‘w:’ if you use ‘addressable:’.

   All flavours of locals are initialized with values from the data or
(for FP locals) FP stack, with the exception being locals defined behind
‘|’: Gforth initializes the locals behind ‘|’ to 0 or ‘0e’, with the
uninitialized ‘[’-ending exception noted above; some Forth systems leave
all locals behind ‘|’ uninitialized.

   Gforth allows defining locals everywhere in a colon definition, but
as a consequence, some locals are not visible (and live) everywhere in
the colon definition (*note Where are locals visible by name?::).

* Menu:

* Locals definition words::
* Where are locals visible by name?::
* How long do locals live?::
* POSTPONEing locals::
* Locals programming style::
* Locals implementation::


File: gforth.info,  Node: Locals definition words,  Next: Where are locals visible by name?,  Prev: Gforth locals,  Up: Gforth locals

6.26.1.1 Locals definitions words
.................................

This section documents the words used for defining locals.  Note that
the run-times for the words (like ‘W:’) that define a local are
performed from the rightmost defined local to the leftmost defined
local, such that the rightmost local gets the top of stack.

‘{:’ ( - hmaddr u wid state 0  ) local-ext "open-brace-colon"
   Start locals definitions.

‘--’ ( hmaddr u wid 0 ... -  ) local-ext "dash-dash"
   During a locals definitions with ‘{:’ everything from ‘--’ to ‘:}’ is
ignored.  This is typically used when you want to make a locals
definition serve double duty as a stack effect description.

‘|’ ( -  ) local-ext "bar"
   Locals defined behind ‘|’ are not initialized from the stack; so the
run-time stack effect of the locals definitions after ‘|’ is ‘( -- )’.

‘:}’ ( hmaddr u wid 0 xt1 ... xtn -  ) gforth-1.0 "colon-close-brace"
   Ends locals definitions.

‘{’ ( - hmaddr u wid 0  ) gforth-0.2 "open-brace"
   Start locals definitions.  The Forth-2012 standard name for this word
is ‘{:’.

‘}’ ( hmaddr u wid state 0 xt1 ... xtn -  ) gforth-0.2 "close-brace"
   Ends locals definitions.  The Forth-2012 standard name for this word
is ‘:}’.

‘locals|’ ( ... "name ..." -  ) local-ext "locals-bar"
   Don't use ‘locals| this read can't you|’!  Use ‘{: you can read this
:}’ instead.!  A portable and free ‘{:’ implementation can be found in
‘compat/xlocals.fs’.

‘W:’ ( compilation "name" - a-addr xt; run-time x -  ) gforth-0.2 "w-colon"
   Define local name with the initial value x.
name execution: ( - x1 ) push the current value of name.
‘to name’ run-time: ( x2 - ) change the value of name to x2.
‘+to name’ run-time: ( n|u - ) increment the value of name by n|u.

‘W^’ ( compilation "name" - a-addr xt; run-time x -  ) gforth-0.2 "w-caret"
   Define local name, reserve a cell at a-addr, and store x there.
name execution: ( - a-addr ).

‘D:’ ( compilation "name" - a-addr xt; run-time x1 x2 -  ) gforth-0.2 "d-colon"
   Define local name with the initial value x1 x2.
name execution: ( - x3 x4 ) push the current value of name.
‘to name’ run-time: ( x5 x6 - ) change the value of name to x5 x6.
‘+to name’ run-time: ( d|ud - ) increment the value of name by d|ud.

‘D^’ ( compilation "name" - a-addr xt; run-time x1 x2 -  ) gforth-0.2 "d-caret"
   Define local name, reserve two cells at a-addr, and store x1 x2
there.
name execution: ( - a-addr ).

‘C:’ ( compilation "name" - a-addr xt; run-time c -  ) gforth-0.2 "c-colon"
   Define local name with the initial value c.
name execution: ( - c1 ) push the current value of name.
‘to name’ run-time: ( c2 - ) change the value of name to c2.
‘+to name’ run-time: ( n|u - ) increment the value of name by n|u.

‘C^’ ( compilation "name" - a-addr xt; run-time c -  ) gforth-0.2 "c-caret"
   Define local name, reserve a cell at c-addr, and store c there.
name execution: ( - c-addr ).

‘F:’ ( compilation "name" - a-addr xt; run-time r -  ) gforth-0.2 "f-colon"
   Define local name with the initial value r.
name execution: ( - r1 ) push the current value of name.
‘to name’ run-time: ( r2 - ) change the value of name to r2.
‘+to name’ run-time: ( r3 - ) increment the value of name by r3.

‘F^’ ( compilation "name" - a-addr xt; run-time r -  ) gforth-0.2 "f-caret"
   Define local name, reserve a float at f-addr, and store r there.
name execution: ( - f-addr ).

‘Z:’ ( compilation "name" - a-addr xt; run-time r1 r2 -  ) gforth-1.0 "z-colon"
   Define local name with the initial value r1 r2.
name execution: ( - r3 r4 ) push the current value of name.
‘to name’ run-time: ( r5 r6 - ) change the value of name to r5 r6.
‘+to name’ run-time: ( r7 r8 - ) increment the value of name by r7+r8i.

‘Z^’ ( compilation "name" - a-addr xt; run-time r1 r2 -  ) gforth-1.0 "z-caret"
   Define local name, reserve two floats at f-addr, and store r1 r2
there.
name execution: ( - f-addr ).

‘XT:’ ( compilation "name" - a-addr xt; run-time xt1 -  ) gforth-1.0 "x-t-colon"
   Define local name; set name to execute xt1.
name execution: execute the xt that name has most recently been set to
execute.
‘Is name’ run-time: ( xt2 - ) set name to execute xt2.
‘Action-of name’ run-time: ( - xt3 ) xt3 is the xt that name has most
recently been set to execute.

   Apart from ‘{:’ and ‘{’, none of these words are normally in the
search order (they are in the vocabulary ‘locals-types’); on other Forth
systems, they may not even be words (the standard documents ‘|’, ‘--’
and ‘:}’ under ‘{:’, not as separate word, and the other words are
non-standard).

