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

This manual is for Gforth (version 0.7.9_20250524, May 24, 2025), 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, Jend 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 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: 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 "Create"

   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 "Variable"
   Define name and reserve a cell at addr.
name execution: ‘( -- addr )’.

‘AVariable’ ( "name" -  ) gforth-0.2 "AVariable"
   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 "Constant"
   Define name.
name execution: ( - w )

‘AConstant’ ( addr "name" -  ) gforth-0.2 "AConstant"
   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 "Value"
   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 "AValue"
   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 "TO"
   Changes the value of NAME to be equal to value.  The type of value
depends on the type of name (see the defining word for name for the
exact stack effect).  An alternative syntax is to write ‘->name’.

‘+TO’ ( value "name" -  ) gforth-1.0 "+TO"
   Adds value to the value of NAME.  The type of value depends on the
type of name (see the defining word for name for the exact stack
effect).  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:"
   ‘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’ ( "name" - addr  ) gforth-1.0 "addr"
   Addr is the address where the value of name is stored.  Name has to
be defined with any value-flavoured defining word (e.g.  ‘value’)
preceded by ‘addressable:’.

   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 "noname"
   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 "latestxt"
   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 bouded 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 "nextname"
   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>"
   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 repetetive 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.

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

‘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 "set-to"
   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 "set-optimizer"
   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:"
   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.

   Another example is a better-optimized variant of the ‘fvalue’ example
above:

     : compile-fvalue-to ( xt-value-to -- )
       drop ]] >body f! [[ ;

     : fvalue-to ( r xt -- )
       >body f! ;
     ' compile-fvalue-to set-optimizer

     : fvalue ( r "name" -- ; name: -- r )
       create f,
       ['] f@ set-does>
       [: >body ]] literal f@ [[ ;] set-optimizer
       ['] fvalue-to set-to ;

     5e fvalue foo
     : bar foo 1e f+ to foo ;
     see bar

   Compare the code for ‘bar’ with the one for the earlier definition.
Here we see the optimization of both the code for reading the fvalue
(coming from the ‘set-optimizer’ in ‘fvalue’) and for writing the fvalue
(coming from the ‘set-optimizer’ applied to ‘fvalue-to’.  Because an
fvalue can change (unlike a constant), the reading part (inside
‘fvalue’) compiles the address and a ‘f@’ that is performed at run-time.

   For ‘fvalue-to’, the ‘compile,’ implementation basically just
compiles the code executed by ‘fvalue’ inline.  The compilation
semantics of ‘to’ compiles the address as literal and then the ‘(to)’
implementation (i.e., ‘fvalue-to’).  In this process the ‘>body’ is
optimized away.

   In practice Gforth's ‘fvalue’ includes a few additional twists, e.g.,
to support ‘+TO’.

   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.

   As we can see in the ‘fvalue-to’ example, we can also apply
‘set-optimizer’ to individual words rather than inside a defining word
like ‘constant’ or ‘fvalue’.  In this case, the xt of the word passed to
optimizer is usually unnecessary and is ‘drop’ped, as in
‘compile-fvalue-to’.

   The engine ‘gforth-itc’ uses ‘,’ for ‘compile,’ and ‘set-optimizer’
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 ‘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 ‘fvalue’ above, we could instead define it as:

     create fvalue-prototype ( -- r )
     ['] f@ set-does>
     [: >body ]] literal f@ [[ ;] set-optimizer
     ['] fvalue-to set-to

     : fvalue ( r "name" -- ; name: -- r )
       ``fvalue-prototype create-from f, reveal ;

   An advantage of this approach is that creating ‘fvalue’ words is now
faster, because it does not need to first duplicate the header methods
of ‘create’, modify them, and eventually deduplicate them.  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-from"
   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 "reveal"
   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 "noname-from"
   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:

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

     : noname-fvalue ( r -- xt ; xt execution: -- r )
       noname-fvalue-prototype noname-from f,
       latestxt ;


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-latest"
   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.  Gforth supports this use with

‘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>’ 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 (because you could change the data using
     ‘>body’...‘!’); ‘const-does>’ avoids this problem.

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


File: gforth.info,  Node: Deferred Words,  Next: Aliases,  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.

   A deferred word can be used to improve the statistics-gathering
example from *note User-defined Defining Words::; rather than edit the
application's source code to change every ‘:’ to a ‘my:’, do this:

     : real: : ;     \ retain access to the original
     defer :         \ redefine as a deferred word
     ' my: IS :      \ use special version of :
     \
     \ load application here
     \
     ' real: IS :    \ go back to the original

   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

   In situations where ‘IS’ does not fit, use ‘defer!’ instead.

   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

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

‘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).

‘IS’ ( value "name" -  ) core-ext "IS"
   changes the ‘defer’red word NAME to execute VALUE

‘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).

‘action-of’ ( interpretation "name" - xt; compilation "name" - ; run-time - xt  ) core-ext "action-of"
   Xt is the XT that is currently assigned to name.

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

   Definitions of these Forth-2012 words in Forth-94 are provided in
‘compat/defer.fs’.  In addition, Gforth provides:

‘defers’ ( compilation "name" - ; run-time ... - ...  ) gforth-0.2 "defers"
   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.

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

‘preserve’ ( "name" -  ) gforth-1.0 "preserve"
   emit code that reverts a deferred word to the state at compilation


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

6.11.12 Aliases
---------------

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 definition of 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’ are
     synonyms).

‘Synonym’ ( "name" "oldname" -  ) tools-ext "Synonym"
   Define name to behave the same way as oldname: Same interpretation
semantics, same compilation semantics, same ‘to’/‘defer!’ and ‘defer@’
semantics.

   Gforth also offers the non-standard ‘alias’, that does not inherit
the compilation semantics, ‘to _name_’ semantics etc.  from its parent.
You can then change, e.g., the compilation semantics with, e.g.,
‘immediate’.

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

   Example:

     : 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

   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 !!  pxref).

   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"

   In addition to ‘field:’ for cell-aligned and cell-sized fields, you
can define fields sized and aligned for various types with:

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

‘end-structure’ ( struct-sys +n -  ) facility-ext "end-structure"
   end a structure started wioth ‘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:"
   Name is a value-flavoured field; in-memory-size: cell; on-stack: cell

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

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

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

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

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

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

‘2value:’ ( u1 "name" - u2  ) gforth-experimental "2value:"
   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:"
   Name is a value-flavoured field; in-memory-size: float; on-stack:
float

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

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

‘zvalue:’ ( u1 "name" - u2  ) gforth-experimental "zvalue:"
   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 "$value:"
   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[]:"
   Name is a value-flavoured array field; in-memory-size: cell;
on-stack: cell

‘$value[]:’ ( u1 "name" - u2  ) gforth-experimental "$value[]:"
   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:"
   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 "extend-structure"
   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’ example looks 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 "%align"
   Align the data space pointer to the alignment ALIGN.

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

‘%alloc’ ( align size - addr  ) gforth-0.4 "%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 "%allocate"
   Allocate SIZE address units with alignment ALIGN, similar to
‘allocate’.

‘%allot’ ( align size - addr  ) gforth-0.4 "%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%"

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

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

‘double%’ ( - align size  ) gforth-0.4 "double%"

‘end-struct’ ( align size "name" -  ) gforth-0.2 "end-struct"
   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 "field"
   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%"

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

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

‘struct’ ( - align size  ) gforth-0.2 "struct"
   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 stacks is represented on the data stack by a cell.

‘stack’ ( n - stack  ) gforth-experimental "stack"
   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 "+after"
   Insert X1 below every occurence X2 in stack.

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

‘set-stack’ ( x1 .. xn n stack -  ) gforth-experimental "set-stack"
   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 "get-stack"
   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
=============================================

The “interpretation semantics” of a (named) word are what the text
interpreter does when it encounters the word in interpret state.  It
also appears in some other contexts, e.g., the execution token returned
by ‘' word’ identifies the interpretation semantics of word (in other
words, ‘' word execute’ is equivalent to interpret-state text
interpretation of ‘word’).

   The “compilation semantics” of a (named) word are what the text
interpreter does when it encounters the word in compile state.  It also
appears in other contexts, e.g, ‘POSTPONE word’ compiles(1) the
compilation semantics of word.

   Most words have default compilation semantics: compile the execution
semantics (stack effect ‘( -- )’).  But a number of words have other
compilation semantics, documented for the individual word (including its
stack effect).

   The standard also talks about “execution semantics”.  In the standard
it never differs from the interpretation semantics if both are defined,
but one or both of them may not be defined.  Gforth makes no difference
between interpretation and execution semantics, so these terms are used
interchangeably.

   In Gforth (since 1.0) all words have defined interpretation/execution
semantics.  For many words that have no defined interpretation nor
execution semantics in the standard (e.g., ‘if’), the
interpretation/execution semantics in Gforth are to perform the
compilation semantics.

   In the standard, execution semantics are used to define
interpretation and compilation semantics by default: By default, the
interpretation semantics of a word are to ‘execute’ its execution
semantics, and the compilation semantics of a word are to ‘compile,’ its
execution semantics.(2)

   Unnamed words (*note Anonymous Definitions::) cannot be encountered
by the text interpreter, ticked, or ‘postpone’d.  Such a word is
represented by its xt (*note Tokens for Words::), and the behaviour when
this xt is ‘execute’d is called its execution semantics.

   You can change the semantics of the most-recently defined word:

‘immediate’ ( -  ) core "immediate"
   Make the compilation semantics of a word be to ‘execute’ the
execution semantics.

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

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

   By convention, words with non-default compilation semantics (e.g.,
immediate words) often have names surrounded with brackets (e.g., ‘[']’,
*note Execution token::).

   Note that ticking (‘'’) a compile-only word gives a warning ("<word>
is compile-only").

* Menu:

* Combined words::

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

   (1) In standard terminology, "appends to the current definition".

   (2) In standard terminology: The default interpretation semantics are
its execution semantics; the default compilation semantics are to append
its execution semantics to the execution semantics of the current
definition.


File: gforth.info,  Node: Combined words,  Prev: Interpretation and Compilation Semantics,  Up: Interpretation and Compilation Semantics

6.14.1 Combined Words
---------------------

Gforth allows you to define “combined words” - words that have an
arbitrary combination of interpretation and compilation semantics (some
people call them NDCS words, and mean words with non-default and
non-immediate compilation semantics).

‘interpret/compile:’ ( interp-xt comp-xt "name" -  ) gforth-0.2 "interpret/compile:"

   This feature was introduced for implementing ‘TO’ and ‘S"’.  I
recommend that you do not define such words, as cute as they may be:
they make it hard to get at both parts of the word in some contexts.
E.g., assume you want to get an execution token for the compilation
part.  Instead, define two words, one that embodies the interpretation
part, and one that embodies the compilation part.  Once you have done
that, you can define a combined word with ‘interpret/compile:’ for the
convenience of your users.

   A typical usage example is:

     : s"-int ( -- c-addr u )
       '"' parse save-mem ;
     : s"-comp ( -- ; run-time: -- c-addr u )
       '"' parse postpone sliteral ;
     ' s"-int ' s"-comp interpret/compile: s"

   Some people are not happy with the looks of the definition above, so
Gforth also provides additional ways to write this kind of definition:

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

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

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

   Note that there are and should be only few combined words, ideally
none, and their definitions don't need to be pretty (on the contrary,
their uglyness may provide a warning that "here be dragons").  So our
recommendation is to use ‘interpret/compile:’.

   It is a bad idea to try to use combined words for optimization of
words with default compilation semantics: Gforth has a better mechanism
for that (‘set-optimizer’ and ‘opt:’, *note User-defined
compile-comma::), ‘[compile]’ treats combined words as having
non-default compilation semantics, and the intended optimization does
not happen when the combined word is ticked and ‘compile,’d.

   Some people try to use “state-smart” words to emulate combined words
(words are state-smart if they check ‘STATE’ during execution).  E.g.,
they would try to code ‘s"’ like this:

     : foobar
       STATE @ IF ( compilation state )
         comp-s"
       ELSE
         int-s"
       THEN ; immediate

   Although this works if ‘s"’ is only processed by the text
interpreter, it does not work in other contexts (like ‘'’ or
‘POSTPONE’).  E.g., ‘' foobar’ will produce an execution token for a
state-smart word, not for the interpretation semantics of the original
‘foobar’; when you execute this execution token (directly with ‘EXECUTE’
or indirectly through ‘COMPILE,’) in compile state, the result will not
be what you expected (i.e., it will not call ‘int-s"’).  State-smart
words are a bad idea.  Simply don't write them(1)!  Gforth provides
better alternatives: ‘interpret/compile:’ and ‘set->comp’ for
implementing combined words, and ‘set-optimizer’ for implementing
optimizations of words with default compilation semantics.

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

   (1) 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 aka execution semantics.(1)

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

     5 `. ( n xt )
     execute ( )      \ execute the xt (i.e., ".")
     : foo `. execute ;
     5 foo

   However, 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.  Perform ‘-14 throw’
if the word has no interpretation semantics.

‘[']’ ( compilation. "name" - ; run-time. - xt  ) core "bracket-tick"
   xt represents name's interpretation semantics.  Perform ‘-14 throw’
if the word has no 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 ( )      \ execute the xt of .
     \ does not work as intended:
     \ : foo ' . ;
     \ 5 foo execute
     \ instead:
     : foo ['] . ;
     5 foo execute    \ execute the xt of .
     \ Usage of ' in colon definition:
     : bar ' execute ;
     5 bar .          \ execute the xt of .

   ‘'’ parses at run-time, so if you put it 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 put a literal xt in a colon definition without writing
‘`x’, write ‘['] 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 can avoid that warning as well as the portability problems by
defining an immediate variant of the word, e.g.:

     : if postpone if ; immediate
     : test [ ' if execute ] ." test" then ;

   The resulting execution token performs the compilation semantics of
‘if’ when ‘execute’d.

   Another way to get an xt is ‘:noname’ or ‘latestxt’ (*note Anonymous
Definitions::).  For anonymous words this gives an xt for the only
behaviour the word has (the execution semantics), but you can also use
it after defining a named word to get its xt.

     :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 addres (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-exit"
   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 to have a placeholder execution token:

‘noop’ ( - ) gforth-0.2 "noop"

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

   (1) The Forth standard has words with undefined interpretation
semantics (e.g., ‘r@’) and words without defined execution semantics
(e.g., ‘s"’) and words with neither (e.g., ‘if’), but in cases where
both interpretation and execution semantics are defined, they are the
same; so we treat them as being the same.


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

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

Gforth represents named words by the “name token”, (nt).  The name token
is a cell-sized abstract data type that occurs as argument or result of
the words below.

   Since Gforth 1.0, for most words the concrete implementation of their
nt is the same address as its xt (this is the primary nt for the xt).
However, synonyms, aliases, and words defined with ‘interpret/compile:’
get their xt from another word, but still have an nt of their own (that
is different from the xt).  Therefore, you cannot use xts and nts
interchangeably, even if you are prepared to write code specific to
Gforth 1.0.  You do not get these alternate nts for the xt with ‘>name’.

   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-name"
   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-name-in"
   search the word list identified by wid for the definition named by
the string at c-addr u.  Return its nt, if found, otherwise 0.

‘latest’ ( - nt  ) gforth-0.6 "latest"
   NT is the name token of the last word defined in the current section;
it is 0 if the last word has no name.

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

‘>name’ ( xt - nt|0  ) gforth-0.2 "to-name"
   The primary name token nt of the word represented by 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 if the primary nt is of an unnamed
word.  As of Gforth 1.0, every xt has a primary nt, but other named
words may have the same interpretation sematics xt.

‘xt>name’ ( xt - nt  ) gforth-1.0 "xt-to-name"
   Produces the primary nt for an xt.  If xt is not an xt, nt is not
guaranteed to be an nt.

   You can get all the nts in a wordlist with

‘traverse-wordlist’ ( ... xt wid - ...  ) tools-ext "traverse-wordlist"
   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 - w xt  ) tools-ext "name-to-compile"
   w xt is the compilation token for the word nt.

‘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.’.

‘obsolete?’ ( nt - flag  ) gforth-1.0 "obsolete?"
   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.

   A nameless word usually has no interpretation nor compilation
semantics, no name, and it's not in a wordlist.  But in Gforth (since
1.0) all words are equal, so even nameless words have an nt (but they
are in no wordlist).  You can get that nt with ‘latestnt’, and the words
above that consume nts do something reasonable for these nts.

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

     : 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,’.

   The closest thing to the nt in older Forth systems is the name field
address (NFA), but there are significant differences: in older Forth
systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
LFA, NFA, CFA, PFA) and there were words for getting from one to the
next.  In contrast, in Gforth several nts can get the same xt from
‘name>interpret’ xt; there is a link field in the structure identified
by the name token, but searching usually uses a hash table external to
these structures; the name in Gforth has a cell-wide count-and-flags
field, and the nt is not implemented as the address of that count field.


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

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

The compilation semantics of a named word is represented by a
“compilation token” consisting of two cells: w xt.  The top cell xt is
an execution token.  The compilation semantics represented by the
compilation token can be performed with ‘execute’, which consumes the
whole compilation token, with an additional stack effect determined by
the represented compilation semantics.

   At present, the w part of a compilation token is an execution token,
and the xt part represents either ‘execute’ or ‘compile,’(1).  However,
don't rely on that knowledge, unless necessary; future versions of
Gforth may introduce unusual compilation tokens (e.g., a compilation
token that represents the compilation semantics of a literal).

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

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

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

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

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

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

   (1) Depending upon the compilation semantics of the word.  If the
word has default compilation semantics, the xt will represent
‘compile,’.  Otherwise (e.g., for immediate words), the xt 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 ‘[’...‘]’  (see below) allow running
arbitrary code while compiling a colon definition (exception: you must
not allot dictionary space).

* 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's, this computes ‘2 cells’
on every loop iteration.  You can compute this value once and for all 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.

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

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

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

‘Literal’ ( compilation n - ; run-time - n  ) core "Literal"
   Compilation semantics: compile the run-time semantics.
Run-time Semantics: push n.
Interpretation semantics: undefined.

‘ALiteral’ ( compilation addr - ; run-time - addr  ) gforth-0.2 "ALiteral"
   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 "]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"
   Compile appropriate code such that, at run-time, w1 w2 are placed on
the stack.  Interpretation semantics are undefined.

‘FLiteral’ ( compilation r - ; run-time - r  ) floating "f-literal"
   Compile appropriate code such that, at run-time, r is placed on the
(floating-point) stack.  Interpretation semantics are undefined.

‘SLiteral’ ( Compilation c-addr1 u ; run-time - c-addr2 u  ) string "SLiteral"
   Compilation: compile the string specified by c-addr1, u into the
current definition.  Run-time: return c-addr2 u describing the address
and length of the string.

   You might be tempted to pass data from outside a colon definition to
the inside on the data stack.  This does not work, because ‘:’ puhes 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
a variable:

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


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’.(1)

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

   Compiling words like ‘compile-+’ are usually immediate (or similar)
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 occassionally 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

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

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

   • When ‘compile-map-array’ is run, ‘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 for the parsing word ‘[']’ and the
recognizer notation starting with ‘`’.

   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" ]] 2literal ... [[

   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 happens 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 to shoot yourself in the foot with text-interpreted
     macros like

          : [compile-+] s" +" evaluate ; immediate

     Apart from binding the name at macro use time, using ‘evaluate’
     also makes your definition ‘state’-smart (*note state-smartness::).

   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 .

   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:

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

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

‘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.

‘2compile,’ ( xt1 xt2 -  ) gforth-experimental "two-compile-comma"
   equivalent to ‘xt1 compile, xt2 compile,’, but also applies peephole
optimization.

   An alternative available in Gforth, 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:

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

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

   In the example above ‘2>r’ and ‘2r>’ ensure that ‘twice’ 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.

   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.

‘[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?"
   allows to check if there currently is an active colon definition
where you can append code to.

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

   (1) A recent RFI answer requires that compiling words should only be
executed in compile state, so this example is not guaranteed to work on
all standard systems, but on any decent system it will work.


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

6.17 The Text Interpreter
=========================

The text interpreter(1) is an endless loop that processes input from the
current input device.  It is also called the outer interpreter, in
contrast to the inner interpreter (*note Engine::) which executes the
compiled Forth code on interpretive implementations.

   The text interpreter operates in one of two states: “interpret state”
and “compile state”.  The current state is defined by the aptly-named
variable ‘state’.

   This section starts by describing how the text interpreter behaves
when it is in interpret state, processing input from the user input
device - the keyboard.  This is the mode that a Forth system is in after
it starts up.

   The text interpreter works from an area of memory called the “input
buffer”(2), which stores your keyboard input when you press the <RET>
key.  Starting at the beginning of the input buffer, it skips leading
spaces (called “delimiters”) then parses a string (a sequence of
non-space characters) until it reaches either a space character or the
end of the buffer.  Having parsed a string, it makes two attempts to
process it:

   • It looks for the string in a “dictionary” of definitions.  If the
     string is found, the string names a “definition” (also known as a
     “word”) and the dictionary search returns information that allows
     the text interpreter to perform the word's “interpretation
     semantics”.  In most cases, this simply means that the word will be
     executed.
   • If the string is not found in the dictionary, the text interpreter
     attempts to treat it as a number, using the rules described in
     *note Number Conversion::.  If the string represents a legal number
     in the current radix, the number is pushed onto a parameter stack
     (the data stack for integers, the floating-point stack for
     floating-point numbers).

   If both attempts fail, the text interpreter discards the remainder of
the input buffer, issues an error message and waits for more input.  If
one of the attempts succeeds, the text interpreter repeats the parsing
process until the whole of the input buffer has been processed, at which
point it prints the status message "‘ ok’" and waits for more input.

   The text interpreter keeps track of its position in the input buffer
by updating a variable called ‘>IN’ (pronounced "to-in").  The value of
‘>IN’ starts out as 0, indicating an offset of 0 from the start of the
input buffer.  The region from offset ‘>IN @’ to the end of the input
buffer is called the “parse area”(3).  This example shows how ‘>IN’
changes as the text interpreter parses the input buffer:

     : remaining source >in @ /string
       cr ." ->" type ." <-" ; immediate

     1 2 3 remaining + remaining .

     : foo 1 2 3 remaining swap remaining ;

The result is:

     ->+ remaining .<-
     ->.<-5  ok

     ->SWAP remaining ;-<
     ->;<-  ok

   The value of ‘>IN’ can also be modified by a word in the input buffer
that is executed by the text interpreter.  This means that a word can
"trick" the text interpreter into either skipping a section of the input
buffer(4) or into parsing a section twice.  For example:

     : lat ." <<foo>>" ;
     : flat ." <<bar>>" >IN DUP @ 3 - SWAP ! ;

When ‘flat’ is executed, this output is produced(5):

     <<bar>><<foo>>

   This technique can be used to work around some of the
interoperability problems of parsing words.  Of course, it's better to
avoid parsing words where possible.

Two important notes about the behaviour of the text interpreter:

   • It processes each input string to completion before parsing
     additional characters from the input buffer.
   • It treats the input buffer as a read-only region (and so must your
     code).

When the text interpreter is in compile state, its behaviour changes in
these ways:

   • If a parsed string is found in the dictionary, the text interpreter
     will perform the word's “compilation semantics”.  In most cases,
     this simply means that the execution semantics of the word will be
     appended to the current definition.
   • When a number is encountered, it is compiled into the current
     definition (as a literal) rather than being pushed onto a parameter
     stack.
   • If an error occurs, ‘state’ is modified to put the text interpreter
     back into interpret state.
   • Each time a line is entered from the keyboard, Gforth prints "‘
     compiled’" rather than " ‘ok’".

   When the text interpreter is using an input device other than the
keyboard, its behaviour changes in these ways:

   • When the parse area is empty, the text interpreter attempts to
     refill the input buffer from the input source.  When the input
     source is exhausted, the input source is set back to the previous
     input source.
   • It doesn't print out "‘ ok’" or "‘ compiled’" messages each time
     the parse area is emptied.
   • If an error occurs, the input source is set back to the user input
     device.

   You can read about this in more detail in *note Input Sources::.

‘>in’ ( - addr  ) core "to-in"
   ‘uvar’ variable - a-addr is the address of a cell containing the char
offset from the start of the input buffer to the start of the parse
area.

‘source’ ( - addr u  ) core "source"
   Return address addr and length u of the current input buffer

‘tib’ ( - addr  ) core-ext-obsolescent "t-i-b"

‘#tib’ ( - addr  ) core-ext-obsolescent "number-t-i-b"
   ‘uvar’ variable - a-addr is the address of a cell containing the
number of characters in the terminal input buffer.  OBSOLESCENT:
‘source’ superceeds the function of this word.

‘interpret’ ( ... - ...  ) gforth-0.2 "interpret"

* Menu:

* Input Sources::
* Number Conversion::
* Interpret/Compile states::
* Interpreter Directives::
* Recognizers::
* Text Interpreter Hooks::

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

   (1) This is an expanded version of the material in *note Introducing
the Text Interpreter::.

   (2) When the text interpreter is processing input from the keyboard,
this area of memory is called the “terminal input buffer” (TIB) and is
addressed by the (obsolescent) words ‘TIB’ and ‘#TIB’.

   (3) In other words, the text interpreter processes the contents of
the input buffer by parsing strings from the parse area until the parse
area is empty.

   (4) This is how parsing words work.

   (5) Exercise for the reader: what would happen if the ‘3’ were
replaced with ‘4’?


File: gforth.info,  Node: Input Sources,  Next: Number Conversion,  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 block, using the words described in *note Blocks::.
   • A text string, using ‘evaluate’.

   A program can identify the current input device from the values of
‘source-id’ and ‘blk’.

‘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"
   ‘uvar’ variable - This cell contains the current block number (or 0
if the current input source is not a block).

‘save-input’ ( - x1 .. xn n  ) core-ext "save-input"
   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 "restore-input"
   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 with the new input code, it fails only with a flag that can be
used to throw again; it is also 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 in
between everything is allowed.

‘evaluate’ ( ... addr u - ...  ) core,block "evaluate"
   Save the current input source specification.  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.  Interpret.  When the parse
area is empty, restore the input source specification.

‘query’ ( -  ) core-ext-obsolescent "query"
   Make the user input device the input source.  Receive input into the
Terminal Input Buffer.  Set ‘>IN’ to zero.  OBSOLESCENT: superceeded by
‘accept’.


File: gforth.info,  Node: Number Conversion,  Next: Interpret/Compile states,  Prev: Input Sources,  Up: The Text Interpreter

6.17.2 Number Conversion
------------------------

You get an overview of how the text interpreter converts its numeric
input in *note Literals in source code::.  This section describes some
related words.

   By default, the number base used for integer number conversion is
given by the contents of the variable ‘base’.  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, and using the prefixes
described in *note Literals in source code:: for the popular non-decimal
bases.

‘base-execute’ ( i*x xt u - j*x  ) gforth-0.7 "base-execute"
   execute xt with the content of ‘BASE’ being u, and restoring the
original ‘BASE’ afterwards.

‘base’ ( - a-addr  ) core "base"
   ‘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 "hex"
   Set ‘base’ to $10 (hexadecimal).  In many cases ‘base-execute’ is a
better alternative.

‘decimal’ ( -  ) core "decimal"
   Set ‘base’ to #10 (decimal).  In many cases ‘base-execute’ is a
better alternative.

‘dpl’ ( - a-addr  ) gforth-0.2 "Decimal-PLace"
   ‘User’ variable - a-addr is the address of a cell that stores the
position of the decimal point in the most recent numeric conversion.
Initialised to -1.  After the conversion of a number containing no
decimal point, ‘dpl’ is -1.  After the conversion of ‘2.’ 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:

   • 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 number conversion process does not check for overflow.

   You can read numbers into your programs with the words described in
*note Line input and conversion::.


File: gforth.info,  Node: Interpret/Compile states,  Next: Interpreter Directives,  Prev: Number Conversion,  Up: The Text Interpreter

6.17.3 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::).


File: gforth.info,  Node: Interpreter Directives,  Next: Recognizers,  Prev: Interpret/Compile states,  Up: The Text Interpreter

6.17.4 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 Standard 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 ... ; immediate
     [endif]

   So if the system does not define ‘\G’, compile some replacement code
(with possibly 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

‘[undefined]’ ( "<spaces>name" - flag  ) tools-ext "bracket-undefined"
   returns false if name is found in current search order

‘[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 interpretation time, interpret ‘[I]’ interpretevely, or use
‘INT-[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 "#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.5 Recognizers
------------------

When the text interpreter processes source code, it divides the code
into blank-delimited strings, and then calls recognizers to identify
them as words, numbers, etc., until one recognizer identifies
(recognizes) the string; if the string is not recognized, the text
interpreter reports an error (‘undefined word’).

   The usual way to deal with recognizers is to just write code that one
of them identifies (*note Default Recognizers::); however, you can also
manipulate them (*note Dealing with existing Recognizers::) or even
define new ones (*note Defining Recognizers::).

* Menu:

* Default Recognizers::
* Dealing with existing Recognizers::
* Defining Recognizers::


File: gforth.info,  Node: Default Recognizers,  Next: Dealing with existing Recognizers,  Prev: Recognizers,  Up: Recognizers

6.17.5.1 Default Recognizers
............................

The Standard Forth text interpreter recognizes words in the search order
(‘rec-nt’), integer numbers (‘rec-num’), and floating point numbers
(‘rec-float’).  By default Gforth also recognizes syntaxes for

   • strings, e.g., ‘"mystring"’, with ‘rec-string’

   • complex numbers, e.g., ‘0e+1ei’, with ‘rec-complex’

   • storing a value or changing a defered word, e.g., ‘->myvalue’, with
     ‘rec-to’

   • the xt representing the interpretation semantics of a word, e.g.,
     ‘`dup’, with ‘rec-tick’

   • the nt of a word, e.g., ‘``mysynonym’, with ‘rec-dtick’

   • an address in the body of a word, e.g., ‘<myarray+8>’, with
     ‘rec-body’

   • an access to an environment variable of the operating system, e.g.,
     ‘${HOME}’, with ‘rec-env’

   • a word in a vocabulary, e.g., ‘myvoc1:myvoc2:myword’, with
     ‘rec-scope’

   • using a specific recognizer to recognize something, e.g.,
     ‘float?1.’, , with ‘rec-meta’

   You can use ‘locate’ (*note Locating source code definitions::) to
determine which recognizer recognizes a piece of source code.  E.g.:

     defer mydefer
     locate ->mydefer

   will show that ‘rec-to’ recognizes ‘->mydefer’.  However, if the
recognizer recognizes a dictionary word (e.g., the scope recognizer),
locate will show that word.

   You can see which recognizers are used and the order of recognizers
with

‘.recognizers’ ( -  ) gforth-experimental "dot-recognizers"
   Print the current recognizer order, with the first-searched
recognizer leftmost (unlike .order).  The inverted ‘~’ is displayed
instead of ‘rec-’, which is the common prefix of all recognizers.

   Recognizers are typically 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 for input strings like ‘$ADD’.  There are a few exceptions to
this policy, however:

   • Word names can be anything, so they can conflict with any other
     recognizer (and the search order is searched before other
     recognizers).

     However, they tend not to start with ‘0’ (and if they do, they
     contain special characters), so if your base is ‘hex’, it is a good
     practice to let your numbers start 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-num’ and the floating-point
     recognizer ‘rec-float’ recognize, e.g., ‘1.’.  Because ‘rec-num’ is
     (by default) first, ‘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’).


File: gforth.info,  Node: Dealing with existing Recognizers,  Next: Defining Recognizers,  Prev: Default Recognizers,  Up: Recognizers

6.17.5.2 Dealing with existing Recognizers
..........................................

A recognizer is a word to which you pass a string.  If the recognizer
recognizes the string, it typically returns some data and the xt of a
word for processing the data; this word is called the translator.  If
the recognizer does not recognize the string, it returns 0.

   All recognizers have the stack effect ( c-addr u - i*x xt | 0 ).

   Recognizers take a string and on success return some data and a
translator for interpreting that data.  Gforth implements that
translator as xt (executing it will perform the appropriate action to
handle the token in the current state), but other Forth systems may
implement it as actual table, with three xts inside.  The first xt is
the interpretation/run-time xt, it performs the interpretation semantics
on the data (usually, this means it just leaves the data on the stack).
The second xt performs the compilation semantics, it gets the data and
the run-time semantics xt.  The third xt perfoms the postpone semantics,
it also gets the data and the run-time semantics xt.  You can use
‘postponing’ to postpone the run-time xt.

   Recognizers are organized as stack, so you can arrange the sequence
of recognizers in the same way as the vocabulary stack.  Recognizer
stacks are themselves recognizers, i.e.  they are executable, take a
string and return a translator.

‘rec-nt’ ( addr u - nt translate-nt | 0  ) gforth-experimental "rec-nt"
   recognize a name token

‘rec-num’ ( addr u - n/d table | 0  ) gforth-experimental "rec-num"
   converts a number to a single/double integer

‘rec-float’ ( addr u - r translate-float | 0  ) gforth-experimental "rec-float"
   recognize floating point numbers

‘rec-complex’ ( addr u - z translate-complex | 0  ) gforth-1.0 "rec-complex"
   Complex numbers are always in the format a+bi, where a and b are
floating point numbers including their signs

‘rec-string’ ( addr u - addr u' scan-translate-string | 0  ) gforth-experimental "rec-string"
   Convert strings enclosed in double quotes into string literals,
escapes are treated as in ‘S\"’.

‘rec-to’ ( addr u - xt n translate-to | 0  ) gforth-experimental "rec-to"
   words prefixed with ‘->’ are treated as if preceeded by ‘TO’, with
‘+>’ as ‘+TO’, with ‘'>’ as ‘ADDR’, with ‘@>’ as ‘ACTION-OF’, and with
‘=>’ as ‘IS’.

‘rec-tick’ ( addr u - xt translate-num | 0  ) gforth-experimental "rec-tick"
   words prefixed with ‘`’ return their xt.  Example: ‘`dup’ gives the
xt of dup

‘rec-dtick’ ( addr u - nt translate-num | 0  ) gforth-experimental "rec-dtick"
   words prefixed with ‘``’ return their nt.  Example: ‘``S"’ gives the
nt of ‘S"’

‘rec-body’ ( addr u - xt translate-num | 0  ) gforth-experimental "rec-body"
   words bracketed with ‘'<'’ ‘'>'’ return their body.  Example: ‘<dup>’
gives the body of dup

‘rec-env’ ( addr u - addr u translate-env | 0  ) gforth-1.0 "rec-env"
   words enclosed by ‘${’ and ‘}’ are passed to ‘getenv’ to get the
OS-environment variable as string.  Example: ‘${HOME}’ gives the home
directory.

‘rec-scope’ ( addr u - nt rectype-nt | 0  ) gforth-experimental "rec-scope"
   Recognizes strings of the form (simplified) ‘wordlist:word’, where
wordlist is found in the search order.  The result is the same as for
‘rec-nt’ for word (the ordinary word recognizer) if the search order
consists only of wordlist.  The general form can have several wordlists
preceding word, separated by ‘:’; the first (leftmost) wordlist is found
in the search order, the second in the first, etc.  word is the looked
up in the last (rightmost) wordlist.

‘rec-meta’ ( addr u - xt translate-to | 0  ) gforth-1.0 "rec-meta"
   words prefixed with RECOGNIZER‘?’ are processed by ‘rec-’RECOGNIZER
to disambiguate recognizers.  Example: ‘hex num?cafe num?add’ will be
parsed as number only Example: ‘float?123.’ will be parsed as float

‘get-recognizers’ ( - xt1 .. xtn n  ) gforth-obsolete "get-recognizers"
   push the content on the recognizer stack

‘set-recognizers’ ( xt1 .. xtn n -  ) gforth-obsolete "set-recognizers"
   set the recognizer stack from content on the stack

‘recognize’ ( addr u rec-addr - ... rectype  ) gforth-experimental "recognize"
   apply a recognizer stack to a string, delivering a token

‘recognizer-sequence:’ ( xt1 .. xtn n "name" -  ) gforth-experimental "recognizer-sequence:"
   concatenate a stack of recognizers to one recognizer with the name
"name".  xtn is tried first, xt1 last, just like on the recognizer stack

‘forth-recognize’ ( c-addr u - ... translate-xt  ) recognizer "forth-recognize"
   The system recognizer

‘forth-recognizer’ ( - xt  ) gforth-obsolete "forth-recognizer"
   backward compatible to Matthias Trute recognizer API. This construct
turns a deferred word into a value-like word.

‘set-forth-recognize’ ( xt -  ) gforth-obsolete "set-forth-recognize"
   Change the system recognizer

‘?found’ ( token|0 - token|never  ) gforth-experimental "?found"
   performs an undefined word ‘throw’ if the TOKEN is 0.

‘translate:’ ( int-xt comp-xt post-xt "name" -  ) gforth-experimental "translate:"
   create a new recognizer table.  Items are in order of STATE value,
which are 0 or negative.  Up to 7 slots are available for extensions.

‘translate-nt’ ( i*x nt - j*x  ) gforth-experimental "translate-nt"
   translate a name token

‘translate-num’ ( x - | x  ) gforth-experimental "translate-num"
   translate a number

‘translate-dnum’ ( dx - | dx  ) gforth-experimental "translate-dnum"
   translate a double number

‘translate-float’ ( r - | r  ) gforth-experimental "translate-float"
   A translator for a float number.

‘try-recognize’ ( addr u xt - results | false  ) gforth-experimental "try-recognize"
   For nested recognizers: try to recognize ADDR U, and execute XT to
check if the result is desired.  If XT returns false, clean up all side
effects of the recognizer, and return false.  Otherwise return the
results of the call to XT, of which the topmost is non-zero.

‘interpreting’ ( translator -  ) gforth-experimental "interpreting"
   perform interpreter action of translator

‘compiling’ ( translator -  ) gforth-experimental "compiling"
   perform compile action of translator

‘postponing’ ( translator -  ) gforth-experimental "postponing"
   perform postpone action of translator

‘translate-method:’ ( "name" -  ) gforth-experimental "translate-method:"
   create a new translate method, extending the translator table.  You
can assign an xt to an existing rectype by using XT RECTYPE ‘to’
TRANSLATOR.

‘set-state’ ( xt -  ) gforth-experimental "set-state"
   change the current state of the system so that executing a translator
matches the translate-method passed as XT

‘get-state’ ( - xt  ) gforth-experimental "get-state"
   return the currently used translate-method XT


File: gforth.info,  Node: Defining Recognizers,  Prev: Dealing with existing Recognizers,  Up: Recognizers

6.17.5.3 Defining Recognizers
.............................


File: gforth.info,  Node: Text Interpreter Hooks,  Prev: Recognizers,  Up: The Text Interpreter

6.17.6 Text Interpreter Hooks
-----------------------------

‘before-line’ ( -  ) gforth-1.0 "before-line"
   Deferred word called before the text interpreter parses the next line

‘before-word’ ( -  ) gforth-0.7 "before-word"
   Deferred word called before the text interpreter parses the next word

‘line-end-hook’ ( -  ) gforth-0.7 "line-end-hook"
   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"
   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 "string-parse"
   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 "parse-name"
   Get the next word from the input buffer

‘parse-word’ ( - c-addr u  ) gforth-obsolete "parse-word"
   old name for ‘parse-name’; this word has a conflicting behaviour in
some other systems.

‘name’ ( - c-addr u  ) gforth-obsolete "name"
   old name for ‘parse-name’

‘word’ ( char "<chars>ccc<char>- c-addr  ) core "word"
   We recommend to use ‘parse-name’ 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.  If the parse area was empty or contained 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 "refill"
   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, make the result the 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.
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.  A successful
result includes receipt of a line containing 0 characters.

   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 "execute-parsing"
   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 "execute-parsing-file"
   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: Environmental Queries,  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), 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 "forth-wordlist"
   ‘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 "definitions"
   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 "get-current"
   wid is the identifier of the current compilation word list.

‘set-current’ ( wid -  ) search "set-current"
   Set the compilation word list to the word list identified by wid.

‘in-wordlist’ ( wordlist "defining-word" -  ) gforth-experimental "in-wordlist"
   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 "in"
   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 "get-order"
   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 "set-order"
   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 "wordlist"
   Create a new, empty word list represented by wid.

‘table’ ( - wid  ) gforth-0.2 "table"
   Create a lookup table (case-sensitive, no warnings).

‘cs-wordlist’ ( - wid  ) gforth-1.0 "cs-wordlist"
   Create a case-sensitive wordlist.

‘cs-vocabulary’ ( "name" -  ) gforth-1.0 "cs-vocabulary"
   Create a case-sensitive vocabulary

‘>order’ ( wid -  ) gforth-0.5 "to-order"
   Push WID on the search order.

‘previous’ ( -  ) search-ext "previous"
   Drop the wordlist at the top of the search order.

‘also’ ( -  ) search-ext "also"
   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 "Forth"
   Replace the wid at the top of the search order with the wid
associated with the word list ‘forth-wordlist’.

‘Only’ ( -  ) search-ext "Only"
   Set the search order to the implementation-defined minimum search
order (for Gforth, this is the word list ‘Root’).

‘order’ ( -  ) search-ext "order"
   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 "find"
   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 "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 is immediate) or
-1 (if the definition is not immediate) together with the xt.  In
Gforth, the xt returned represents the interpretation semantics.
Forth-2012 does not specify clearly what xt represents.

‘words’ ( -  ) tools "words"
   Display a list of all of the definitions in the word list at the top
of the search order.

‘vlist’ ( -  ) gforth-0.2 "vlist"
   Old (pre-Forth-83) name for ‘WORDS’.

‘wordlist-words’ ( wid -  ) gforth-0.6 "wordlist-words"
   Display the contents of the wordlist wid.

‘mwords’ ( ["pattern"] -  ) gforth-1.0 "mwords"
   list all words matching the optional parameter PATTERN; if none, all
words match.  Words are listed old to new.  Pattern match like ‘search’
(default), you can switch to globbing with ‘' mword-filename-match is
mword-match’.

‘Root’ ( -  ) gforth-0.2 "Root"
   Add the root wordlist to the search order stack.  This vocabulary
makes up the minimum search order and contains only a search-order
words.

‘Vocabulary’ ( "name" -  ) gforth-0.2 "Vocabulary"
   Create a definition "name" and associate a new word list with it.
The run-time effect of "name" is to replace the wid at the top of the
search order with the wid associated with the new word list.

‘seal’ ( -  ) gforth-0.2 "seal"
   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 "vocs"
   List vocabularies and wordlists defined in the system.

‘current’ ( - addr  ) gforth-0.2 "current"
   ‘Variable’ - holds the wid of the compilation word list.

‘context’ ( - addr  ) gforth-0.2 "context"
   ‘context’ ‘@’ is the wid of the word list at the top of the search
order.

‘map-vocs’ ( ... xt - ...  ) gforth-1.0 "map-vocs"
   Perform xt ( ...  wid - ...  )  for all wordlists (including tables
and cs-wordlists) in the system.

* Menu:

* Vocabularies::
* Why use word lists?::
* Word list example::


File: gforth.info,  Node: Vocabularies,  Next: Why use word lists?,  Prev: Word Lists,  Up: Word Lists

6.19.1 Vocabularies
-------------------

Here is an example of creating and using a new wordlist using Standard
Forth words:

     wordlist constant my-new-words-wordlist
     : my-new-words get-order nip my-new-words-wordlist swap set-order ;

     \ add it to the search order
     also my-new-words

     \ alternatively, add it to the search order and make it
     \ the compilation word list
     also my-new-words definitions
     \ type "order" to see the problem

   The problem with this example is that ‘order’ has no way to associate
the name ‘my-new-words’ with the wid of the word list (in Gforth,
‘order’ and ‘vocs’ will display ‘???’ for a wid that has no associated
name).  There is no Standard way of associating a name with a wid.

   In Gforth, this example can be re-coded using ‘vocabulary’, which
associates a name with a wid:

     vocabulary my-new-words

     \ add it to the search order
     also my-new-words

     \ alternatively, add it to the search order and make it
     \ the compilation word list
     my-new-words definitions
     \ type "order" to see that the problem is solved


File: gforth.info,  Node: Why use word lists?,  Next: Word list example,  Prev: Vocabularies,  Up: Word Lists

6.19.2 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.

   • 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.

   • You have to explicitly undo any changes to the search order.  In
     many cases it would be more convenient if this happened implicitly.
     Gforth currently does not provide such a feature, but it may do so
     in the future.


File: gforth.info,  Node: Word list example,  Prev: Why use word lists?,  Up: Word Lists

6.19.3 Word list example
------------------------

The following example is from the garbage collector
(https://www.complang.tuwien.ac.at/forth/garbage-collection.zip) and
uses wordlists to separate public words from helper words:

     get-current ( wid )
     vocabulary garbage-collector also garbage-collector definitions
     ... \ define helper words
     ( wid ) set-current \ restore original (i.e., public) compilation wordlist
     ... \ define the public (i.e., API) words
         \ they can refer to the helper words
     previous \ restore original search order (helper words become invisible)


File: gforth.info,  Node: Environmental Queries,  Next: Files,  Prev: Word Lists,  Up: Words

6.20 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, whilst the documentation for (e.g.)  ‘ADDRESS-UNIT-BITS’
shows it returning 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?’ is ‘( c-addr u --
n true )’.

   Several environmental queries deal with the system's limits:

‘ADDRESS-UNIT-BITS’ ( - n  ) environment "ADDRESS-UNIT-BITS"
   Size of one address unit, in bits.

‘MAX-CHAR’ ( - u  ) environment "MAX-CHAR"
   Maximum value of any character in the character set

‘/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 "CORE"
   True if the complete core word set is present.  Always true for
Gforth.

‘CORE-EXT’ ( - f  ) environment "CORE-EXT"
   True if the complete core extension word set is present.  Always true
for Gforth.

‘FLOORED’ ( - f  ) environment "FLOORED"
   True if ‘/’ etc.  perform floored division

‘MAX-N’ ( - n  ) environment "MAX-N"
   Largest usable signed integer.

‘MAX-U’ ( - u  ) environment "MAX-U"
   Largest usable unsigned integer.

‘MAX-D’ ( - d  ) environment "MAX-D"
   Largest usable signed double.

‘MAX-UD’ ( - ud  ) environment "MAX-UD"
   Largest usable unsigned double.

‘return-stack-cells’ ( - n  ) environment "return-stack-cells"
   Maximum size of the return stack, in cells.

‘stack-cells’ ( - n  ) environment "stack-cells"
   Maximum size of the data stack, in cells.

‘floating-stack’ ( - n  ) environment "floating-stack"
   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 "wordlists"
   the maximum number of wordlists usable in the search order

‘max-float’ ( - r  ) environment "max-float"
   The largest usable floating-point number (implemented as largest
finite number in Gforth)

‘XCHAR-ENCODING’ ( - addr u  ) environment "XCHAR-ENCODING"
   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 "MAX-XCHAR"
   Maximal value for xchar.  This depends on the encoding.

‘XCHAR-MAXMEM’ ( - u  ) environment "XCHAR-MAXMEM"
   Maximal memory consumed by an xchar in address units

   Several environemtal 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::) 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 "gforth"
   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 "os-class"
   Counted string representing a description of the host operating
system.

‘os-type’ ( - c-addr u  ) gforth-environment "os-type"
   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 "environment-wordlist"
   wid identifies the word list that is searched by environmental
queries (present in SwiftForth and VFX).

‘environment’ ( -  ) gforth-0.6 "environment"
   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.21 Files
==========

Gforth provides facilities for accessing files that are stored in the
host operating system's file-system.  Files that are processed by Gforth
can be divided into two categories:

   • Files that are processed by the Text Interpreter (“Forth source
     files”).
   • Files that are processed by some other program (“general files”).

* 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.21.1 Forth source files
-------------------------

The simplest way to interpret the contents of a file is to use one of
these two formats:

     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 use one of these
three formats:

     require mysource.fs
     needs 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:

     1024 require foo.fs drop

   Here you want to pass the argument 1024 (e.g., a buffer size) to
‘foo.fs’.  Interpreting ‘foo.fs’ has the stack effect ( n - n ), which
allows its use with ‘require’.  Of course with such parameters to
required files, you have to ensure that the first ‘require’ fits for all
uses (i.e., ‘require’ it early in the master load file).

‘include-file’ ( i*x wfileid - j*x  ) file "include-file"
   Interpret (process using the text interpreter) the contents of the
file WFILEID.

‘included’ ( i*x c-addr u - j*x  ) file "included"
   ‘include-file’ the file whose name is given by the string C-ADDR U.

‘included?’ ( c-addr u - f  ) gforth-0.2 "included?"
   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"
   ‘include-file’ the file FILE.

‘required’ ( i*x addr u - i*x  ) file-ext "required"
   ‘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 "require"
   ‘include-file’ FILE only if it is not included already.

‘needs’ ( ... "name" - ...  ) gforth-0.2 "needs"
   An alias for ‘require’; exists on other systems (e.g., Win32Forth).

‘\\\’ ( -  ) gforth-1.0 "\\\"
   skip remaining source file

‘.included’ ( -  ) gforth-0.5 ".included"
   List the names of the files that have been ‘included’.

‘sourcefilename’ ( - c-addr u  ) gforth-0.2 "sourcefilename"
   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 undefined.  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 undefined.

   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.21.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 "bin"

‘+fmode’ ( fam1 rwxrwxrwx - fam2  ) gforth-1.0 "plus-f-mode"
   add file access mode to fam - for create-file only

   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 "read-line"
   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, the u1 chars of
the buffer have been filled with chars from the line, and the next slice
of the line with 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 "key-file"
   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 "write-line"

‘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 "slurp-file"
   C-ADDR1 U1 is the filename, C-ADDR2 U2 is the file's contents

‘slurp-fid’ ( fid - addr u  ) gforth-0.6 "slurp-fid"
   ADDR U is the content of the file FID

‘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.21.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 "outfile-execute"
   execute xt with the output of ‘type’ etc.  redirected to file-id.

‘outfile-id’ ( - file-id  ) gforth-0.2 "outfile-id"
   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 "infile-execute"
   execute xt with the input of ‘key’ etc.  redirected to file-id.

‘infile-id’ ( - file-id  ) gforth-0.4 "infile-id"
   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.21.4 Directories
------------------

You can split a file name into a directory and base component:

‘basename’ ( c-addr1 u1 - c-addr2 u2  ) gforth-0.7 "basename"
   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 "dirname"
   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 dir-id 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 dir-id
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 in the buffer specified by c-addr1, u1.
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.

‘mkdir-parents’ ( c-addr u mode - ior  ) gforth-0.7 "mkdir-parents"
   create the directory c-addr u and all its parents with mode mode
(modified by umask)


File: gforth.info,  Node: Search Paths,  Prev: Directories,  Up: Files

6.21.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?"
   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.21.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"

‘.fpath’ ( -  ) gforth-0.4 ".fpath"
   Display the contents of the Forth search path.

‘file>fpath’ ( addr1 u1 - addr2 u2  ) gforth-1.0 "file>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.21.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 "open-path-file"
   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>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 "clear-path"
   Set the path path-addr to empty.

‘also-path’ ( c-addr len path-addr -  ) gforth-0.4 "also-path"
   add the directory c-addr len to path-addr.

‘.path’ ( path-addr -  ) gforth-0.4 ".path"
   Display the contents of the search path PATH-ADDR.

‘path+’ ( path-addr  "dir" -  ) gforth-0.4 "path+"
   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.22 Blocks
===========

When you run Gforth on a modern desk-top computer, it runs under the
control of an operating system which provides certain services.  One of
these services is FILE SERVICES, which allows Forth source code and data
to be stored in files and read into Gforth (*note Files::).

   Traditionally, Forth has been an important programming language on
systems where it has interfaced directly to the underlying hardware with
no intervening operating 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 read and write blocks under program control, Gforth uses a
number of “block buffers” as intermediate storage.  These buffers are
not used when you use ‘load’ to interpret the contents of a block.

   The behaviour of the block buffers is analagous 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’ when you don't care about the existing
contents of the block(1).

   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’.

   In Gforth, ‘block’ and ‘buffer’ use a direct-mapped algorithm to
assign a block buffer to a block.  That means that any particular block
can only be assigned to one specific block buffer, called (for the
particular operation) the victim buffer.  If the victim buffer is
unassigned or assigned-clean it is allocated to the new block
immediately.  If it is assigned-dirty its current contents are written
back to the blocks file on disk before it is allocated to the new block.

   Although no structure is imposed on the contents of a block, it is
traditional to display the contents as 16 lines each of 64 characters.
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 wraps straight into the first
     character of the following line
   • 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 "open-blocks"
   Use the file, whose name is given by c-addr u, as the blocks file.

‘use’ ( "file" -  ) gforth-0.2 "use"
   Use file as the blocks file.

‘block-offset’ ( - addr  ) gforth-0.5 "block-offset"
   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.

‘get-block-fid’ ( - wfileid  ) gforth-0.2 "get-block-fid"
   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-position’ ( u -  ) block "block-position"
   Position the block file to the start of block u.

‘list’ ( u -  ) block-ext "list"
   Display block u.  In Gforth, the block is displayed 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’.

‘block’ ( u - a-addr  ) block "block"
   If a block buffer is assigned for block u, return its start address,
a-addr.  Otherwise, assign a block buffer for block u (if the assigned
block buffer has been ‘update’d, transfer the contents to mass storage),
read the block into the block buffer and return its start address,
a-addr.

‘buffer’ ( u - a-addr  ) block "buffer"
   If a block buffer is assigned for block u, return its start address,
a-addr.  Otherwise, assign a block buffer for block u (if the assigned
block buffer has been ‘update’d, transfer the contents to mass storage)
and return its start address, a-addr.  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.  In Gforth, this simply
calls ‘block’.

‘empty-buffers’ ( -  ) block-ext "empty-buffers"
   Mark all block buffers as unassigned; if any had been marked as
assigned-dirty (by ‘update’), the changes to those blocks will be lost.

‘empty-buffer’ ( buffer -  ) gforth-0.2 "empty-buffer"

‘update’ ( -  ) block "update"
   Mark the state of the current block buffer as assigned-dirty.

‘updated?’ ( n - f  ) gforth-0.2 "updated?"
   Return true if ‘updated’ has been used to mark block n as
assigned-dirty.

‘save-buffers’ ( -  ) block "save-buffers"
   Transfer the contents of each ‘update’d block buffer to mass storage,
then mark all block buffers as assigned-clean.

‘save-buffer’ ( buffer -  ) gforth-0.2 "save-buffer"

‘flush’ ( -  ) block "flush"
   Perform the functions of ‘save-buffers’ then ‘empty-buffers’.

‘load’ ( i*x u - j*x  ) block "load"
   Text-interpret block u.  Block 0 cannot be ‘load’ed.

‘thru’ ( i*x n1 n2 - j*x  ) block-ext "thru"
   ‘load’ the blocks n1 through n2 in sequence.

‘+load’ ( i*x n - j*x  ) gforth-0.2 "+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 "+thru"
   Used within a block to load the range of blocks specified as the
current block + n1 thru the current block + n2.

‘-->’ ( -  ) gforth-0.2 "chain"
   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 "block-included"
   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) The Standard Forth definition of ‘buffer’ is intended not to
cause disk I/O; if the data associated with the particular block is
already stored in a block buffer due to an earlier ‘block’ command,
‘buffer’ will return that block buffer and the existing contents of the
block will be available.  Otherwise, ‘buffer’ will simply assign a new,
empty block buffer for the block.


File: gforth.info,  Node: Other I/O,  Next: OS command line arguments,  Prev: Blocks,  Up: Words

6.23 Other I/O
==============

* Menu:

* Simple numeric output::       Predefined formats
* Formatted numeric output::    Formatted (pictured) output
* Floating-point output::
* Miscellaneous output::
* Displaying characters and strings::  Other stuff
* Terminal output::             Cursor positioning etc.
* Single-key input::
* Line input and conversion::
* Pipes::                       How to create your own pipes
* Xchars and Unicode::          Non-ASCII characters
* i18n and l10n::               Internationalization and Localization
* Substitute::                  Text macro substitution
* CSV reading and writing::


File: gforth.info,  Node: Simple numeric output,  Next: Formatted numeric output,  Prev: Other I/O,  Up: Other I/O

6.23.1 Simple numeric output
----------------------------

The simplest output functions are those that display numbers from the
data stack.  Numbers are displayed in the base (aka radix) stored in
‘base’ (*note Number Conversion::).

‘.’ ( n -  ) core "dot"
   Display (the signed single number) N in free-format, followed by a
space.

‘dec.’ ( n -  ) gforth-0.2 "dec."
   Display n as a signed decimal number, followed by a space.

‘h.’ ( u -  ) gforth-1.0 "h."
   Display u as an unsigned hex number, prefixed with a "$" and followed
by a space.

‘hex.’ ( u -  ) gforth-0.2 "hex."
   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 are
displayed.  If appropriate, N2 must include a character for a leading
"-".

‘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.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 are displayed.
If appropriate, N must include a character for a leading "-".

‘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: Formatted numeric output,  Next: Floating-point output,  Prev: Simple numeric output,  Up: Other I/O

6.23.2 Formatted numeric output
-------------------------------

Forth traditionally 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 Number Conversion::), converted to ASCII codes and
prepended to a string that is built in a scratch-pad area of memory
(*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 "hold"
   Used between ‘<<#’ and ‘#>’.  Prepend the character CHAR to the
pictured numeric output string.

‘holds’ ( addr u -  ) core-ext "holds"
   Used between ‘<<#’ and ‘#>’.  Prepend the string ‘addr u’ to the
pictured numeric output string.

‘sign’ ( n -  ) core "sign"
   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 output,  Next: Miscellaneous output,  Prev: Formatted numeric output,  Up: Other I/O

6.23.3 Floating-point output
----------------------------

Floating-point output is always displayed using base 10.

‘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-e-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 "precision"
   u is the number of significant digits currently used by ‘F.’ ‘FE.’
and ‘FS.’

‘set-precision’ ( u -  ) floating-ext "set-precision"
   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.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|

   You can generate a string instead of displaying the number with:

‘f>str-rdp’ ( rf +nr +nd +np - c-addr nr  ) gforth-0.6 "f>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’.  The result in in the
pictured numeric output buffer and will be destroyed by anything
destroying that buffer.

‘f>buf-rdp’ ( rf c-addr +nr +nd +np -  ) gforth-0.6 "f>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’.

   There is also a primitive used for implementing higher-level
FP-to-string 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: Miscellaneous output,  Next: Displaying characters and strings,  Prev: Floating-point output,  Up: Other I/O

6.23.4 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 "space"
   Display one space.

‘spaces’ ( u -  ) core "spaces"
   Display U spaces.

‘out’ ( - addr  ) gforth-1.0 "out"
   ‘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 wether 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 text, stored in a file ‘test.fs’:

     .( text-1)
     : my-word
       ." text-2" cr
       .( text-3)
       "text-4" type
     ;

     ." text-5"
     "text-6" type

   When you load this code into Gforth, the following output is
generated:

     include test.fs <RET> text-1text-3text-5text-6 ok

   • 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.
   • Message ‘text-5’ is displayed because of Gforth's added
     interpretation semantics for ‘."’.
   • Message ‘text-6’ is displayed because ‘"text-6" type’ is
     interpreted.
   • Message ‘text-2’ is not displayed, because the text interpreter
     performs the compilation semantics for ‘."’ within the definition
     of ‘my-word’.
   • Message ‘text-4’ is not displayed, because ‘"text-4" type’ is
     compiled into ‘my-word’.


File: gforth.info,  Node: Displaying characters and strings,  Next: Terminal output,  Prev: Miscellaneous output,  Up: Other I/O

6.23.5 Displaying characters and strings
----------------------------------------

‘type’ ( c-addr u -  ) core "type"
   If U>0, display U characters from a string starting with the
character stored at C-ADDR.

‘xemit’ ( xc -  ) xchar "x-emit"
   Prints an xchar on the terminal.

‘emit’ ( c -  ) core "emit"
   Send the byte c to the current output; for ASCII characters, ‘emit’
is equivalent to ‘xemit’.

‘typewhite’ ( addr n -  ) gforth-0.2 "typewhite"
   Like type, but white space is printed instead of the characters.


File: gforth.info,  Node: Terminal output,  Next: Single-key input,  Prev: Displaying characters and strings,  Up: Other I/O

6.23.6 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 "at-deltaxy"
   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 "form"

   And sometimes you want to use:

‘page’ ( -  ) facility "page"
   Clear the screen

   Note that on non-terminals you should use ‘12 emit’, not ‘page’, to
get a form feed.

6.23.6.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 (see below).

‘default-color’ ( -  ) gforth-1.0 "default-color"
   use system-default color

‘error-color’ ( -  ) gforth-1.0 "error-color"
   error color: red

‘error-hl-inv’ ( -  ) gforth-1.0 "error-hl-inv"
   color mod for error highlight inverse

‘error-hl-ul’ ( -  ) gforth-1.0 "error-hl-ul"
   color mod for error highlight underline

‘warning-color’ ( -  ) gforth-1.0 "warning-color"
   color for warnings: blue/yellow on black terminals

‘info-color’ ( -  ) gforth-1.0 "info-color"
   color for info: green/cyan on black terminals

‘success-color’ ( -  ) gforth-1.0 "success-color"
   color for success: green

‘input-color’ ( -  ) gforth-1.0 "input-color"
   color for user-input: black/white (both bold)

‘status-color’ ( -  ) gforth-1.0 "status-color"
   color mod for status bar

‘compile-color’ ( -  ) gforth-1.0 "compile-color"
   color mod for status bar in compile mode

6.23.6.2 Color themes
.....................

Depending on wether you prefer bright or dark background the foreground
colors-theme can be changed by:

‘light-mode’ ( -  ) gforth-1.0 "light-mode"
   color theme for white background

‘dark-mode’ ( -  ) gforth-1.0 "dark-mode"
   color theme for black background

‘uncolored-mode’ ( -  ) gforth-1.0 "uncolored-mode"
   This mode does not set colors, but uses the default ones.

‘magenta-input’ ( -  ) gforth-1.0 "magenta-input"
   make input color easily recognizable (useful in presentations)

   Gforth tries to select the best mode automatically.  You can set the
environment variable ‘GFORTH_COLOR’ to ‘light’, ‘dark’, ‘uncolored’, or
‘auto’ (same effect if not setting it at all), to tell Gforth your
preference.


File: gforth.info,  Node: Single-key input,  Next: Line input and conversion,  Prev: Terminal output,  Up: Other I/O

6.23.7 Single-key input
-----------------------

If you want to get a single printable character, you can use ‘key’; to
check whether a character is available for ‘key’, you can use ‘key?’.

‘key’ ( - char  ) core "key"
   Receive (but do not display) one character, CHAR.

‘key-ior’ ( - char|ior  ) gforth-1.0 "key-ior"
   Receive (but do not display) one character, CHAR, in case of an error
or interrupt, return the negative IOR instead.

‘key?’ ( - flag  ) facility "key-question"
   Determine whether a character is available.  If a character is
available, FLAG is true; the next call to ‘key’ will yield the
character.  Once ‘key?’ returns true, subsequent calls to ‘key?’ before
calling ‘key’ or ‘ekey’ will also return true.

‘xkey?’ ( - flag  ) xchar "x-key-query"

   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 xchar ‘xc’ if possible.

‘ekey>char’ ( u - u false | c true  ) facility-ext "e-key-to-char"
   Convert keyboard event U into character ‘c’ if possible.  Note that
non-ASCII characters produce ‘false’ from both ‘ekey>char’ and
‘ekey>fkey’.  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"
   True if a keyboard event is available.

   The key identifiers for cursor keys are:

‘k-left’ ( - u  ) facility-ext "k-left"

‘k-right’ ( - u  ) facility-ext "k-right"

‘k-up’ ( - u  ) facility-ext "k-up"

‘k-down’ ( - u  ) facility-ext "k-down"

‘k-home’ ( - u  ) facility-ext "k-home"
   aka Pos1

‘k-end’ ( - u  ) facility-ext "k-end"

‘k-prior’ ( - u  ) facility-ext "k-prior"
   aka PgUp

‘k-next’ ( - u  ) facility-ext "k-next"
   aka PgDn

‘k-insert’ ( - u  ) facility-ext "k-insert"

‘k-delete’ ( - u  ) facility-ext "k-delete"
   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-shift-mask"

‘k-ctrl-mask’ ( - u  ) facility-ext "k-ctrl-mask"

‘k-alt-mask’ ( - u  ) facility-ext "k-alt-mask"

   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-enter"

‘k-backspace’ ( - u  ) gforth-1.0 "k-backspace"

‘k-tab’ ( - u  ) gforth-1.0 "k-tab"

   Moreover, there the following key codes for keys and other events:

‘k-winch’ ( - u  ) gforth-1.0 "k-winch"
   A key code that may be generated when the user changes the window
size.

‘k-pause’ ( - u  ) gforth-1.0 "k-pause"

‘k-mute’ ( - u  ) gforth-1.0 "k-mute"

‘k-volup’ ( - u  ) gforth-1.0 "k-volup"

‘k-voldown’ ( - u  ) gforth-1.0 "k-voldown"

‘k-sel’ ( - u  ) gforth-1.0 "k-sel"

‘k-eof’ ( - u  ) gforth-1.0 "k-eof"

   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 "simple-fkey-string"
   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: Line input and conversion,  Next: Pipes,  Prev: Single-key input,  Up: Other I/O

6.23.8 Line input and conversion
--------------------------------

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 "accept"
   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-line"
   edit the string with length N2 in the buffer C-ADDR N1, like
‘accept’.

   Conversion words:

‘s>number?’ ( addr u - d f  ) gforth-0.5 "s>number?"
   converts string addr u into d, flag indicates success

‘s>unumber?’ ( c-addr u - ud flag  ) gforth-0.5 "s>unumber?"
   converts string c-addr u into ud, flag indicates success

‘>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.

‘>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.

‘>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.

   Obsolescent input and conversion words:

‘convert’ ( ud1 c-addr1 - ud2 c-addr2  ) core-ext-obsolescent "convert"
   Obsolescent: superseded by ‘>number’.

‘expect’ ( c-addr +n -  ) core-ext-obsolescent "expect"
   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.
OBSOLESCENT: superceeded by ‘accept’.

‘span’ ( - c-addr  ) core-ext-obsolescent "span"
   ‘Variable’ - c-addr is the address of a cell that stores the length
of the last string received by ‘expect’.  OBSOLESCENT.


File: gforth.info,  Node: Pipes,  Next: Xchars and Unicode,  Prev: Line input and conversion,  Up: Other I/O

6.23.9 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"

‘close-pipe’ ( wfileid - wretval wior ) gforth-0.2 "close-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 "broken-pipe-error"
   the error number for a broken pipe


File: gforth.info,  Node: Xchars and Unicode,  Next: i18n and l10n,  Prev: Pipes,  Up: Other I/O

6.23.10 Xchars and Unicode
--------------------------

ASCII is only appropriate for the English language.  Most western
languages however fit somewhat into the Forth frame, since a byte is
sufficient to encode the few special characters in each (though not
always the same encoding can be used; latin-1 is most widely used,
though).  For other languages, different char-sets have to be used,
several of them variable-width.  To deal with this problem, characters
are often represented as Unicode codepoints on the stack, and as UTF-8
byte strings in memory.  An Unicode codepoint often represents one
application-level character, but Unicode also supports decomposed
characters that consist of several code points, e.g., a base letter and
a combining diacritical mark.

   An Unicode codepoint can consume more than one byte in memory, so we
adjust our terminology: A char is a raw byte in memory or a value in the
range 0-255 on the stack.  An xchar (for extended char) stands for one
codepoint; it is represented by one or more bytes in memory and may have
larger values on the stack.  ASCII characters are the same as chars and
as xchars: values in the range 0-127, and a single byte with that value
in memory.

   When using UTF-8 encoding, all other codepoints take more than one
byte/char.  In most cases, you can just treat such characters as strings
in memory and don't need to use the following words, but if you want to
deal with individual codepoints, the following words are useful.  We
currently have no words for dealing with decomposed characters.

   The xchar words add a few data types:

   • XC is an extended char (xchar) on the stack.  It occupies one cell,
     and is a subset of unsigned cell.  On 16 bit systems, only the BMP
     subset of the Unicode character set (i.e., codepoints <65536) can
     be represented on the stack.  If you represent your application
     characters as strings at all times, you can avoid this limitation.

   • XC-ADDR is the address of an xchar in memory.  Alignment
     requirements are the same as C-ADDR.  The memory representation of
     an xchar differs from the stack representation, and depends on the
     encoding used.  An xchar may use a variable number of chars in
     memory.

   • XC-ADDR U is a buffer of xchars in memory, starting at XC-ADDR, U
     chars (i.e., bytes, not xchars) long.

‘xc-size’ ( xc - u  ) xchar "x-c-size"
   Computes the memory size of the xchar XC in chars.

‘x-size’ ( xc-addr u1 - u2  ) xchar "x-size"
   Computes the memory size of the first xchar stored at XC-ADDR in
chars.

‘xc@’ ( xc-addr - xc  ) xchar-ext "xc-fetch"
   Fetchs the xchar XC at XC-ADDR1.

‘xc@+’ ( xc-addr1 - xc-addr2 xc  ) xchar "x-c-fetch-plus"
   Fetchs the xchar XC at XC-ADDR1.  XC-ADDR2 points to the first memory
location after XC.

‘xc@+?’ ( xc-addr1 u1 - xc-addr2 u2 xc  ) gforth-experimental "x-c-fetch-plus-query"
   Fetchs the first xchar XC of the string XC-ADDR1 U1.  XC-ADDR2 U2 is
the remaining string after XC.

‘xc!+?’ ( xc xc-addr1 u1 - xc-addr2 u2 f  ) xchar "x-c-store-plus-query"
   Stores the xchar XC into the buffer starting at address XC-ADDR1, U1
chars large.  XC-ADDR2 points to the first memory location after XC, U2
is the remaining size of the buffer.  If the xchar XC did fit into the
buffer, F is true, otherwise F is false, and XC-ADDR2 U2 equal XC-ADDR1
U1.  XC!+?  is safe for buffer overflows, and therefore preferred over
XC!+.

‘xc!+’ ( xc xc-addr1 - xc-addr2  ) xchar "x-c-store"
   Stores the xchar XC at XC-ADDR1.  XC-ADDR2 is the next unused address
in the buffer.  Note that this writes up to 4 bytes, so you need at
least 3 bytes of padding after the end of the buffer to avoid
overwriting useful data if you only check the address against the end of
the buffer.

‘xchar+’ ( xc-addr1 - xc-addr2  ) xchar "x-char-plus"
   Adds the size of the xchar stored at XC-ADDR1 to this address, giving
XC-ADDR2.

‘xchar-’ ( xc-addr1 - xc-addr2  ) xchar-ext "x-char-minus"
   Goes backward from XC_ADDR1 until it finds an xchar so that the size
of this xchar added to XC_ADDR2 gives XC_ADDR1.

‘+x/string’ ( xc-addr1 u1 - xc-addr2 u2  ) xchar-ext "plus-x-slash-string"
   Step forward by one xchar in the buffer defined by address XC-ADDR1,
size U1 chars.  XC-ADDR2 is the address and u2 the size in chars of the
remaining buffer after stepping over the first xchar in the buffer.

‘x\string-’ ( xc-addr u1 - xc-addr u2  ) xchar-ext "x-backslash-string-minus"
   Step backward by one xchar in the buffer defined by address XC-ADDR
and size U1 in chars, starting at the end of the buffer.  XC-ADDR is the
address and U2 the size in chars of the remaining buffer after stepping
backward over the last xchar in the buffer.

‘-trailing-garbage’ ( xc-addr u1 - xc-addr u2  ) xchar-ext "minus-trailing-garbage"
   Examine the last XCHAR in the buffer XC-ADDR U1--if the encoding is
correct and it repesents a full char, U2 equals U1, otherwise, U2
represents the string without the last (garbled) xchar.

‘x-width’ ( xc-addr u - n  ) xchar-ext "x-width"
   N is the number of monospace ASCII chars that take the same space to
display as the the xchar string starting at XC-ADDR, using U chars;
assuming a monospaced display font, i.e.  char width is always an
integer multiple of the width of an ASCII char.

‘xkey’ ( - xc  ) xchar "x-key"
   Reads an xchar from the terminal.  This will discard all input events
up to the completion of the xchar.

‘xc-width’ ( xc - n  ) xchar-ext "x-c-width"
   XC has a width of N times the width of a normal fixed-width glyph.

‘xhold’ ( xc -  ) xchar-ext "x-hold"
   Used between ‘<<#’ and ‘#>’.  Prepend XC to the pictured numeric
output string.  Alternatively, use ‘holds’.

‘xc,’ ( xchar -  ) xchar "x-c-comma"


File: gforth.info,  Node: i18n and l10n,  Next: Substitute,  Prev: Xchars and Unicode,  Up: Other I/O

6.23.11 Internationalization and Localization
---------------------------------------------

Programs for end users require to address those in their native
language.  There is a decades old proposal for such a facility that has
been split from other proposals for international character sets like
Xchars (*note Xchars and Unicode::) and Substitute (*note Substitute::).
Messages displayed on the screen need to be translated from the native
language of the developers to the local languages of the user.

   Strings subject to translation are declared with ‘L" ’STRING‘"’.
This returns a locale string identifier (LSID). LSIDs are opaque types,
taking a cell on the stack.  LSIDs can be translated into a locale;
locales are languages and country-specific variants of that language.

‘L"’ ( "lsid<">" - lsid  ) gforth-experimental "l-quote"
   Parse a string and define a new lsid, if the string is uniquely new.
Identical strings result in identical lsids, which allows to refer to
the same lsid from multiple locations using the same string.

‘LU"’ ( "lsid<">" - lsid  ) gforth-experimental "l-unique-quote"
   Parse a string and always define a new lsid, even if the string is
not unique.

‘native@’ ( lsid - addr u  ) gforth-experimental "native-fetch"
   fetch native string from an LSID

‘locale@’ ( lsid - addr u  ) gforth-experimental "locale-fetch"
   fetch the localized string in the current language and country

‘locale!’ ( addr u lsid -  ) gforth-experimental "locale-store"
   Store localized string ADDR U for the current locale and country in
LSID.

‘Language’ ( "name" -  ) gforth-experimental "Language"
   define a locale.  Executing that locale makes it the current locale.

‘Country’ ( <lang> "name" -  ) gforth-experimental "Country"
   define a variant (typical: country) for the current locale.
Executing that locale makes it the current locale.  You can create
variants of variants (a country may have variants within, e.g.  think of
how many words for rolls/buns there are in many languages).

‘locale-file’ ( fid -  ) gforth-experimental "locale-file"
   read lines from FID into the current locale.

‘included-locale’ ( addr u -  ) gforth-experimental "included-locale"
   read lines from the file ADDR U into the current locale.

‘include-locale’ ( "name" -  ) gforth-experimental "include-locale"
   read lines from the file "NAME" into the current locale.

‘locale-csv’ ( "name" -  ) gforth-experimental "locale-csv"
   import comma-separated value table into locales.  first line contains
locale names, “program” and “default” are special entries; generic
languages must preceed translations for specific countries.  Entries
under “program” (must be leftmost) are used to search for the lsid; if
empty, the line number-1 is the lsid index.

‘.locale-csv’ ( -  ) gforth-experimental "dot-locale-csv"
   write the locale database in CSV format to the terminal output.

‘locale-csv-out’ ( "name" -  ) gforth-experimental "locale-csv"
   Create file "NAME" and write the locale database out to the file
"NAME" in CSV format.


File: gforth.info,  Node: Substitute,  Next: CSV reading and writing,  Prev: i18n and l10n,  Up: Other I/O

6.23.12 Substitute
------------------

This is a simple text macro replacement facility.  Texts in the form
‘"text %macro% text"’ are processed, and the macro variables enclosed in
‘'%'’ are replaced with their associated strings.  Two consecutive ‘%’
are replaced by one ‘%’.  Macros are defined in a specific wordlist, and
return a string upon execution; the standard defines only one way to
declare macros, ‘replaces’, which creates a macro that just returns a
string.

‘macros-wordlist’ ( - wid  ) gforth-experimental "macros-wordlist"
   wordlist for string replacement macros

‘replaces’ ( addr1 len1 addr2 len2 -  ) string-ext "replaces"
   create a macro with name ADDR2 LEN2 and content ADDR1 LEN1.  If the
macro already exists, just change the content.

‘replacer:’ ( "name" -  ) gforth-experimental "replacer:"
   Start a colon definition name in ‘macros-wordlist’, i.e.  this colon
definition is a macro.  It must have the stack effect ( - ADDR U ).

‘.substitute’ ( addr1 len1 - n / ior  ) gforth-experimental "dot-substitute"
   substitute all macros in text ADDR1 LEN1 and print the result.  N is
the number of substitutions or, if negative, a throwable IOR.

‘$substitute’ ( addr1 len1 - addr2 len2 n/ior  ) gforth-experimental "string-substitute"
   substitute all macros in text ADDR1 LEN1.  N is the number of
substitutions, if negative, it's a throwable IOR, ADDR2 LEN2 the result.

‘substitute’ ( addr1 len1 addr2 len2 - addr2 len3 n/ior  ) string-ext "substitute"
   substitute all macros in text ADDR1 LEN1, and copy the result to
ADDR2 LEN2.  N is the number of substitutions or, if negative, a
throwable IOR, ADDR2 LEN3 the result.

‘unescape’ ( addr1 u1 dest - dest u2  ) string-ext "unescape"
   double all delimiters in ADDR1 U1, so that substitute will result in
the original text.  Note that the buffer DEST does not have a size, as
in worst case, it will need just twice as many characters as U1.  DEST
U2 is the resulting string.

‘$unescape’ ( addr1 u1 - addr2 u2  ) gforth-experimental "string-unescape"
   same as ‘unescape’, but creates a temporary destination string with
‘$tmp’.


File: gforth.info,  Node: CSV reading and writing,  Prev: Substitute,  Up: Other I/O

6.23.13 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’ ( addr u xt -  ) gforth-experimental "read-csv"
   Read CVS file ADDR U and execute XT for every field found.  XT has
the stack effect ‘( addr u field line -- )’, i.e.  the field string (in
de-quoted form), the current field number (starting with 0), and the
current line (starting with 1).

‘csv-separator’ ( - c  ) gforth-experimental "csv-separator"
   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"
   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.24 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 "next-arg"
   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 "arg"
   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 "shift-args"
   ‘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 "argc"
   ‘Variable’ - the number of command-line arguments (including the
command name).  Changed by ‘next-arg’ and ‘shift-args’.

‘argv’ ( - addr  ) gforth-0.2 "argv"
   ‘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.25 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.25.1 Gforth 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 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::) A value-flavoured local (defined with ‘W:’, ‘D:’
     etc.)  produces its value and can be changed with ‘TO’ and ‘+TO’.
     Also, if you put ‘addressable:’ in front of the locals definition,
     you can get its address with ‘ADDR’ (*note How long do locals
     live?::).

“variable-flavoured”
     (*note Variables::) A variable-flavoured local (defined with ‘W^’
     etc.)  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 ;

“defer-flavoured”
     (*note Deferred Words::) A defer-flavoured local (defined with
     ‘XT:’) ‘execute’s the xt; you can use ‘action-of’ (*note Deferred
     Words::) to get the xt out of a defer-flavoured local.  If the
     local is defined with ‘addressable: xt:’, you can use ‘addr’ 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.  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 them to 0; some Forth systems leave them
uninitialized.

   Gforth supports the square bracket notation for local buffers and
data structures.  These locals are similar to variable-flavored locals,
the size is specified as a constant expression.  A declaration looks
‘name[ size ]’.  The Forth expression ‘size’ is evaluated during
declaration, it must have the stack effect ‘( -- +n )’, giving the size
in bytes.  The square bracket ‘[’ is part of the defined name.

   Local data structures are initialized by copying size bytes from an
address passed on the stack; uninitialized local data structures (after
‘|’ in the declaration) are not erased, they just contain whatever data
there was on the locals stack before.

   Example:

     begin-structure test-struct
       field: a1
       field: a2
     end-structure

     : test-local {: foo[ test-struct ] :}
         foo[ a1 !  foo[ a2 !
         foo[ test-struct dump ;

   Gforth allows defining locals everywhere in a colon definition.  This
poses the following questions:

* Menu:

* Locals definition words::
* Where are locals visible by name?::
* How long do locals live?::
* 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.25.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 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 0 xt1 ... xtn -  ) gforth-0.2 "close-brace"
   Ends locals definitions.  The Forth-2012 standard name for this word
is ‘:}’.

‘W:’ ( compilation "name" - a-addr xt; run-time x -  ) gforth-0.2 "w-colon"
   Define value-flavoured cell local name ‘( -- x1 )’

‘W^’ ( compilation "name" - a-addr xt; run-time x -  ) gforth-0.2 "w-caret"
   Define variable-flavoured cell local name ‘( -- a-addr )’

‘D:’ ( compilation "name" - a-addr xt; run-time x1 x2 -  ) gforth-0.2 "d-colon"
   Define value-flavoured double local name ‘( -- x3 x4 )’

‘D^’ ( compilation "name" - a-addr xt; run-time x1 x2 -  ) gforth-0.2 "d-caret"
   Define variable-flavoured double local name ‘( -- a-addr )’

‘C:’ ( compilation "name" - a-addr xt; run-time c -  ) gforth-0.2 "c-colon"
   Define value-flavoured char local name ‘( -- c1 )’

‘C^’ ( compilation "name" - a-addr xt; run-time c -  ) gforth-0.2 "c-caret"
   Define variable-flavoured char local name ‘( -- c-addr )’

‘F:’ ( compilation "name" - a-addr xt; run-time r -  ) gforth-0.2 "f-colon"
   Define value-flavoured float local name ‘( -- r1 )’

‘F^’ ( compilation "name" - a-addr xt; run-time r -  ) gforth-0.2 "f-caret"
   Define variable-flavoured float local name ‘( -- f-addr )’

‘z:’ ( compilation "name" - a-addr xt; run-time z -  ) gforth-1.0 "w-colon"
   Define value-flavoured complex local name ‘( -- z1 )’

‘XT:’ ( compilation "name" - a-addr xt; run-time xt1 -  ) gforth-1.0 "x-t-colon"
   Define defer-flavoured cell local name ‘( ... -- ... )’

   Note that ‘|’, ‘--’ and ‘:}’ are not normally in the search order
(they are in the vocabulary ‘locals-types’), and on some Forth systems
they may not even be words (and the standard documents them under ‘{:’,
not as separate word).  ‘}’ is also in ‘locals-types’.


File: gforth.info,  Node: Where are locals visible by name?,  Next: How long do locals live?,  Prev: Locals definition words,  Up: Gforth locals

6.25.1.2 Where are locals visible by name?
..........................................

Basically, the answer is that locals are visible where you would expect
it in block-structured languages, and sometimes a little longer.  If you
want to restrict the scope of a local, enclose its definition in
‘SCOPE’...‘ENDSCOPE’.

‘scope’ ( compilation  - scope ; run-time  -  ) gforth-0.2 "scope"

‘endscope’ ( compilation scope - ; run-time  -  ) gforth-0.2 "endscope"

   These words behave like control structure words, so you can use them
with ‘CS-PICK’ and ‘CS-ROLL’ to restrict the scope in arbitrary ways.

   If you want a more exact answer to the visibility question, here's
the basic principle: A local is visible in all places that can only be
reached through the definition of the local(1).  In other words, it is
not visible in places that can be reached without going through the
definition of the local.  E.g., locals defined in ‘IF’...‘THEN’ are
visible until the ‘THEN’, locals defined in ‘BEGIN’...‘UNTIL’ are
visible after the ‘UNTIL’ (until, e.g., a subsequent ‘ENDSCOPE’).

   The reasoning behind this solution is: We want to have the locals
visible as long as it is meaningful.  The user can always make the
visibility shorter by using explicit scoping.  In a place that can only
be reached through the definition of a local, the meaning of a local
name is clear.  In other places it is not: How is the local initialized
at the control flow path that does not contain the definition?  Which
local is meant, if the same name is defined twice in two independent
control flow paths?

   This should be enough detail for nearly all users, so you can skip
the rest of this section.  If you really must know all the gory details
and options, read on.

   In order to implement this rule, the compiler has to know which
places are unreachable.  It knows this automatically after ‘AHEAD’,
‘AGAIN’, ‘EXIT’ and ‘LEAVE’; in other cases (e.g., after most ‘THROW’s),
you can use the word ‘UNREACHABLE’ to tell the compiler that the control
flow never reaches that place.  If ‘UNREACHABLE’ is not used where it
could, the only consequence is that the visibility of some locals is
more limited than the rule above says.  If ‘UNREACHABLE’ is used where
it should not (i.e., if you lie to the compiler), you can produce code
whose behaviour is best determined by looking at the implementation
(which may change).

‘UNREACHABLE’ ( -  ) gforth-0.2 "UNREACHABLE"

   Another problem with this rule is that at ‘BEGIN’, the compiler does
not know which locals will be visible on the incoming back-edge.  All
problems discussed in the following are due to this ignorance of the
compiler (we discuss the problems using ‘BEGIN’ loops as examples; the
discussion also applies to ‘?DO’ and other loops).  Perhaps the most
insidious example is:
     AHEAD
     BEGIN
       x
     [ 1 CS-ROLL ] THEN
       {: x :}
       ...
     UNTIL

   This should be legal according to the visibility rule.  The use of
‘x’ can only be reached through the definition; but that appears
textually below the use.

   From this example it is clear that the visibility rules cannot be
fully implemented without major headaches.  Our implementation treats
common cases as advertised and the exceptions are treated in a safe way:
The compiler makes a reasonable guess about the locals visible after a
‘BEGIN’; if it is too pessimistic, the user will get a spurious error
about the local not being defined; if the compiler is too optimistic, it
will notice this later and issue a warning.  In the case above the
compiler would complain about ‘x’ being undefined at its use.  You can
see from the obscure examples in this section that it takes quite
unusual control structures to get the compiler into trouble, and even
then it will often do fine.

   If the ‘BEGIN’ is reachable from above, the most optimistic guess is
that all locals visible before the ‘BEGIN’ will also be visible after
the ‘BEGIN’.  This guess is valid for all loops that are entered only
through the ‘BEGIN’, in particular, for normal
‘BEGIN’...‘WHILE’...‘REPEAT’ and ‘BEGIN’...‘UNTIL’ loops and it is
implemented in our compiler.  When the branch to the ‘BEGIN’ is finally
generated by ‘AGAIN’ or ‘UNTIL’, the compiler checks the guess and warns
the user if it was too optimistic:
     IF
       {: x :}
     BEGIN
       \ x ?
     [ 1 cs-roll ] THEN
       ...
     UNTIL

   Here, ‘x’ lives only until the ‘BEGIN’, but the compiler
optimistically assumes that it lives until the ‘THEN’.  It notices this
difference when it compiles the ‘UNTIL’ and issues a warning.  The user
can avoid the warning, and make sure that ‘x’ is not used in the wrong
area by using explicit scoping:
     IF
       SCOPE
       {: x :}
       ENDSCOPE
     BEGIN
     [ 1 cs-roll ] THEN
       ...
     UNTIL

   Since the guess is optimistic, there will be no spurious error
messages about undefined locals.

   If the ‘BEGIN’ is not reachable from above (e.g., after ‘AHEAD’ or
‘EXIT’), the compiler cannot even make an optimistic guess, as the
locals visible after the ‘BEGIN’ may be defined later.

   It pessimistically assumes that all locals are visible that were
visible at the latest place outside any control structure (i.e., where
nothing is on the control-flow stack).  This means that in:

     : foo
       IF {: z :} THEN
       {: x :}
       AHEAD
         BEGIN
           ( * )
         [ 1 CS-ROLL ] THEN
         {: y :}
         ...
       UNTIL ;

   At the place marked with ‘( * )’, ‘x’ is visible, but ‘y’ is not
(although, according to the reachability rule it should); ‘z’ is not and
should not be visible there.

   However, you can use ‘ASSUME-LIVE’ to make the compiler assume that
the same locals are visible at the BEGIN as at the point where the top
control-flow stack item was created.

‘ASSUME-LIVE’ ( orig - orig  ) gforth-0.2 "ASSUME-LIVE"

E.g.,
     IF
       {: x :}
       AHEAD
         ASSUME-LIVE
         BEGIN
           x
         [ 1 CS-ROLL ] THEN
         ...
       UNTIL
     THEN

   Here ‘x’ would not be visible at the use of ‘x’, because its
definition is inside a control structure, but by using ASSUME-LIVE the
programmer tells the compiler that the locals visible at the ‘AHEAD’
should be visible at the ‘BEGIN’.

   Other cases where the locals are defined before the ‘BEGIN’ can be
handled by inserting an appropriate ‘CS-ROLL’ before the ‘ASSUME-LIVE’
(and changing the control-flow stack manipulation behind the
‘ASSUME-LIVE’).

   Cases where locals are defined in a ‘BEGIN’ loop and should be
visible in that loop before the definition can only be handled by
rearranging the loop.  E.g., the "most insidious" example above can be
arranged into:
     BEGIN
       {: x :}
       ... 0=
     WHILE
       x
     REPEAT

   The ideas in this section have also been published in M. Anton Ertl,
‘Automatic Scoping of Local Variables
(https://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz)’, EuroForth
'94.

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

   (1) In compiler construction terminology, all places dominated by the
definition of the local.


File: gforth.info,  Node: How long do locals live?,  Next: Locals programming style,  Prev: Where are locals visible by name?,  Up: Gforth locals

6.25.1.3 How long do locals live?
.................................

The right answer for the lifetime question would be: A local lives at
least as long as it can be accessed.  For a regular value-flavoured
local this means: until the end of its visibility.  However, an
addressable value-flavoured or variable-flavoured local could be
accessed through its address far beyond its visibility scope.
Ultimately, this would mean that such locals would have to be garbage
collected.  Since this entails un-Forth-like implementation
complexities, we adopted the same cowardly solution as some other
languages (e.g., C): The local lives only as long as it is visible;
afterwards its address is invalid (and programs that access it
afterwards are erroneous).


File: gforth.info,  Node: Locals programming style,  Next: Locals implementation,  Prev: How long do locals live?,  Up: Gforth locals

6.25.1.4 Locals programming style
.................................

The freedom to define locals anywhere has the potential to change
programming styles dramatically.  In particular, the need to use the
return stack for intermediate storage vanishes.  Moreover, all stack
manipulations (except ‘PICK’s and ‘ROLL’s with run-time determined
arguments) can be eliminated: If the stack items are in the wrong order,
just write a locals definition for all of them; then write the items in
the order you want.

   This seems a little far-fetched and eliminating stack manipulations
is unlikely to become a conscious programming objective.  Still, the
number of stack manipulations will be reduced dramatically if local
variables are used liberally (e.g., compare ‘max’ (*note Gforth
locals::) with a traditional implementation of ‘max’).

   This shows one potential benefit of locals: making Forth programs
more readable.  Of course, this benefit will only be realized if the
programmers continue to honour the principle of factoring instead of
using the added latitude to make the words longer.

   Using ‘TO’ can and should be avoided.  Without ‘TO’, every
value-flavoured local has only a single assignment and many advantages
of functional languages apply to Forth.  I.e., programs are easier to
analyse, to optimize and to read: It is clear from the definition what
the local stands for, it does not turn into something different later.

   E.g., a definition using ‘TO’ might look like this:
     : strcmp {: addr1 u1 addr2 u2 -- n :}
      u1 u2 min 0
      ?do
        addr1 c@ addr2 c@ -
        ?dup-if
          unloop exit
        then
        addr1 char+ TO addr1
        addr2 char+ TO addr2
      loop
      u1 u2 - ;
   Here, ‘TO’ is used to update ‘addr1’ and ‘addr2’ at every loop
iteration.  ‘strcmp’ is a typical example of the readability problems of
using ‘TO’.  When you start reading ‘strcmp’, you think that ‘addr1’
refers to the start of the string.  Only near the end of the loop you
realize that it is something else.

   This can be avoided by defining two locals at the start of the loop
that are initialized with the right value for the current iteration.
     : strcmp {: addr1 u1 addr2 u2 -- n :}
      addr1 addr2
      u1 u2 min 0
      ?do {: s1 s2 :}
        s1 c@ s2 c@ -
        ?dup-if
          unloop exit
        then
        s1 char+ s2 char+
      loop
      2drop
      u1 u2 - ;
   Here it is clear from the start that ‘s1’ has a different value in
every loop iteration.


File: gforth.info,  Node: Locals implementation,  Prev: Locals programming style,  Up: Gforth locals

6.25.1.5 Locals implementation
..............................

Gforth uses an extra locals stack.  The most compelling reason for this
is that the return stack is not float-aligned; using an extra stack also
eliminates the problems and restrictions of using the return stack as
locals stack.  Like the other stacks, the locals stack grows toward
lower addresses.  A few primitives allow an efficient implementation;
you should not use them directly, but they appear in the output of
‘see’, so they are documented here:

‘@localn’ ( noffset - w ) gforth-internal "fetch-local-n"

‘f@localn’ ( noffset - r ) gforth-1.0 "f-fetch-local-n"

‘!localn’ ( w noffset - ) gforth-internal "store-local-n"

‘lp+n’ ( noffset - c-addr ) gforth-internal "lp-plus-n"

‘lp+!’ ( noffset - ) gforth-1.0 "lp-plus-store"
   When used with negative noffset allocates memory on the local stack;
when used with a positive noffset drops memory from the local stack

‘lp!’ ( c-addr - ) gforth-internal "lp-store"

‘>l’ ( w - ) gforth-0.2 "to-l"

‘f>l’ ( r - ) gforth-0.2 "f-to-l"

   See also ‘lp@’ (*note Stack pointer manipulation::).

   In addition to these primitives, some specializations of these
primitives for commonly occurring inline arguments are provided for
efficiency reasons, e.g., ‘@local0’ as specialization of ‘0 @localn’.

   Combinations of conditional branches and ‘lp+!#’ like ‘?branch-lp+!#’
(the locals pointer is only changed if the branch is taken) are provided
for efficiency and correctness in loops.

   A special area in the dictionary space is reserved for keeping the
local variable names.  ‘{:’ switches the dictionary pointer to this area
and ‘:}’ switches it back and generates the locals initializing code.
‘W:’ etc. are normal defining words.  This special area is cleared at
the start of every colon definition.

   A special feature of Gforth's dictionary is used to implement the
definition of locals without type specifiers: every word list (aka
vocabulary) has its own methods for searching etc.  (*note Word
Lists::).  For the present purpose we defined a word list with a special
search method: When it is searched for a word, it actually creates that
word using ‘W:’.  ‘{:’ changes the search order to first search the word
list containing ‘:}’, ‘W:’ etc., and then the word list for defining
locals without type specifiers.  This implementation was designed before
Gforth acquired recognizers; for a reimplementation we would use
recognizers.

   The lifetime rules support a stack discipline within a colon
definition: The lifetime of a local is either nested with other locals
lifetimes or it does not overlap them.

   At ‘BEGIN’, ‘IF’, and ‘AHEAD’ no code for locals stack pointer
manipulation is generated.  Between control structure words locals
definitions can push locals onto the locals stack.  ‘AGAIN’ is the
simplest of the other three control flow words.  It has to restore the
locals stack depth of the corresponding ‘BEGIN’ before branching.  The
code looks like this:
current-locals-size dest-locals-size - ‘lp+!’
‘branch’ <begin>

   ‘UNTIL’ is a little more complicated: If it branches back, it must
adjust the stack just like ‘AGAIN’.  But if it falls through, the locals
stack must not be changed.  The compiler generates the following code:
‘?branch-lp+!#’ <begin> current-locals-size − dest-locals-size
   The locals stack pointer is only adjusted if the branch is taken.

   ‘THEN’ can produce somewhat inefficient code:
current-locals-size dest-locals-size - ‘lp+!’
<orig target>:
orig-locals-size new-locals-size - ‘lp+!’
   The second ‘lp+!#’ adjusts the locals stack pointer from the level at
the orig point to the level after the ‘THEN’.  The first ‘lp+!#’ adjusts
the locals stack pointer from the current level to the level at the orig
point, so the complete effect is an adjustment from the current level to
the right level after the ‘THEN’.  This effect happens e.g., if there is
an ‘ELSE’ and the code before the ‘ELSE’ defines locals, and they have a
different size than those after the ‘ELSE’.  In general we recommend not
to work around this shortcoming (except in performance-critical code).
We intend to eliminate this shortcoming at some point.

   In a conventional Forth implementation a dest control-flow stack
entry is just the target address and an orig entry is just the address
to be patched.  Our locals implementation adds a word list to every orig
or dest item.  It is the list of locals visible (or assumed visible) at
the point described by the entry.  Our implementation also adds a tag to
identify the kind of entry, in particular to differentiate between live
and dead (reachable and unreachable) orig entries.

   A few unusual operations have to be performed on locals word lists:

‘common-list’ ( list1 list2 - list3  ) gforth-internal "common-list"

‘sub-list?’ ( list1 list2 - f  ) gforth-internal "sub-list?"

‘list-size’ ( list - u  ) gforth-internal "list-size"

   Several features of our locals word list implementation make these
operations easy to implement: The locals word lists are organised as
linked lists; the tails of these lists are shared, if the lists contain
some of the same locals; and the address of a name is greater than the
address of the names behind it in the list.

   Another important implementation detail is the variable ‘dead-code’.
It is used by ‘BEGIN’ and ‘THEN’ to determine if they can be reached
directly or only through the branch that they resolve.  ‘dead-code’ is
set by ‘UNREACHABLE’, ‘AHEAD’, ‘EXIT’ etc., and cleared at the start of
a colon definition, by ‘BEGIN’ and usually by ‘THEN’.

   Counted loops are similar to other loops in most respects, but
‘LEAVE’ requires special attention: It performs basically the same
service as ‘AHEAD’, but it does not create a control-flow stack entry.
Therefore the information has to be stored elsewhere; traditionally, the
information was stored in the target fields of the branches created by
the ‘LEAVE’s, by organizing these fields into a linked list.
Unfortunately, this clever trick does not provide enough space for
storing our extended control flow information.  Therefore, we introduce
another stack, the leave stack.  It contains the control-flow stack
entries for all unresolved ‘LEAVE’s.

   Local names are kept until the end of the colon definition, even if
they are no longer visible in any control-flow path.  In a few cases
this may lead to increased space needs for the locals name area, but
usually less than reclaiming this space would cost in code size.


File: gforth.info,  Node: Standard Forth locals,  Prev: Gforth locals,  Up: Locals

6.25.2 Standard Forth locals
----------------------------

The Forth-2012 standard defines a syntax for locals is restricted
version of Gforth's locals:

   • Locals can only be cell-sized values (no type specifiers are
     allowed).
   • Locals can be defined only outside control structures.
   • Only one locals definition is allowed per colon definition.
   • Locals can interfere with explicit usage of the return stack.  For
     the exact (and long) rules, see the standard.  If you don't use
     return stack accessing words in a definition using locals, you will
     be all right.  The purpose of this rule is to make locals
     implementation on the return stack easier.
   • The whole locals definition must be in one line.

   The Standard Forth locals wordset itself consists of two words: ‘{:’
and:

‘(local)’ ( addr u -  ) local "paren-local-paren"

   The Forth-2012 locals extension wordset also defines a syntax using
‘locals|’, but it is so awful that we strongly recommend not to use it
and another, better syntax (the one using ‘{:’ was standardized).  We
have implemented this syntax to make porting to Gforth easy, but do not
document it here.  The problem with this syntax is that the locals are
defined in an order reversed with respect to the standard stack comment
notation, making programs harder to read, and easier to misread and
miswrite.


File: gforth.info,  Node: Object-oriented Forth,  Next: Closures,  Prev: Locals,  Up: Words

6.26 Object-oriented Forth
==========================

Gforth comes with three packages for object-oriented programming:
‘objects.fs’, ‘oof.fs’, and ‘mini-oof.fs’; none of them is preloaded, so
you have to ‘include’ them before use.  The most important differences
between these packages (and others) are discussed in *note Comparison
with other object models::.  All packages are written in Standard Forth
and can be used with any other Standard Forth.

* Menu:

* Why object-oriented programming?::
* Object-Oriented Terminology::
* Objects::
* OOF::
* Mini-OOF::
* Mini-OOF2::
* Comparison with other object models::


File: gforth.info,  Node: Why object-oriented programming?,  Next: Object-Oriented Terminology,  Prev: Object-oriented Forth,  Up: Object-oriented Forth

6.26.1 Why object-oriented programming?
---------------------------------------

Often we have to deal with several data structures (_objects_), that
have to be treated similarly in some respects, but differently in
others.  Graphical objects are the textbook example: circles, triangles,
dinosaurs, icons, and others, and we may want to add more during program
development.  We want to apply some operations to any graphical object,
e.g., ‘draw’ for displaying it on the screen.  However, ‘draw’ has to do
something different for every kind of object.

   We could implement ‘draw’ as a big ‘CASE’ control structure that
executes the appropriate code depending on the kind of object to be
drawn.  This would be not be very elegant, and, moreover, we would have
to change ‘draw’ every time we add a new kind of graphical object (say,
a spaceship).

   What we would rather do is: When defining spaceships, we would tell
the system: "Here's how you ‘draw’ a spaceship; you figure out the
rest".

   This is the problem that all systems solve that (rightfully) call
themselves object-oriented; the object-oriented packages presented here
solve this problem (and not much else).


File: gforth.info,  Node: Object-Oriented Terminology,  Next: Objects,  Prev: Why object-oriented programming?,  Up: Object-oriented Forth

6.26.2 Object-Oriented Terminology
----------------------------------

This section is mainly for reference, so you don't have to understand
all of it right away.  The terminology is mainly Smalltalk-inspired.  In
short:

_class_
     a data structure definition with some extras.

_object_
     an instance of the data structure described by the class
     definition.

_instance variables_
     fields of the data structure.

_selector_
     (or _method selector_) a word (e.g., ‘draw’) that performs an
     operation on a variety of data structures (classes).  A selector
     describes _what_ operation to perform.  In C++ terminology: a
     (pure) virtual function.

_method_
     the concrete definition that performs the operation described by
     the selector for a specific class.  A method specifies _how_ the
     operation is performed for a specific class.

_selector invocation_
     a call of a selector.  One argument of the call (the TOS
     (top-of-stack)) is used for determining which method is used.  In
     Smalltalk terminology: a message (consisting of the selector and
     the other arguments) is sent to the object.

_receiving object_
     the object used for determining the method executed by a selector
     invocation.  In the ‘objects.fs’ model, it is the object that is on
     the TOS when the selector is invoked.  (_Receiving_ comes from the
     Smalltalk _message_ terminology.)

_child class_
     a class that has (_inherits_) all properties (instance variables,
     selectors, methods) from a _parent class_.  In Smalltalk
     terminology: The subclass inherits from the superclass.  In C++
     terminology: The derived class inherits from the base class.


File: gforth.info,  Node: Objects,  Next: OOF,  Prev: Object-Oriented Terminology,  Up: Object-oriented Forth

6.26.3 The ‘objects.fs’ model
-----------------------------

This section describes the ‘objects.fs’ package.  This material also has
been published in M. Anton Ertl, ‘Yet Another Forth Objects Package
(https://www.complang.tuwien.ac.at/forth/objects/objects.html)’, Forth
Dimensions 19(2), pages 37-43.

   This section assumes that you have read *note Structures::.

   The techniques on which this model is based have been used to
implement the parser generator, Gray, and have also been used in Gforth
for implementing the various flavours of word lists (hashed or not,
case-sensitive or not, special-purpose word lists for locals etc.).

* Menu:

* Properties of the Objects model::
* Basic Objects Usage::
* The Objects base class::
* Creating objects::
* Object-Oriented Programming Style::
* Class Binding::
* Method conveniences::
* Classes and Scoping::
* Dividing classes::
* Object Interfaces::
* Objects Implementation::
* Objects Glossary::

   Marcel Hendrix provided helpful comments on this section.


File: gforth.info,  Node: Properties of the Objects model,  Next: Basic Objects Usage,  Prev: Objects,  Up: Objects

6.26.3.1 Properties of the ‘objects.fs’ model
.............................................

   • It is straightforward to pass objects on the stack.  Passing
     selectors on the stack is a little less convenient, but possible.

   • Objects are just data structures in memory, and are referenced by
     their address.  You can create words for objects with normal
     defining words like ‘constant’.  Likewise, there is no difference
     between instance variables that contain objects and those that
     contain other data.

   • Late binding is efficient and easy to use.

   • It avoids parsing, and thus avoids problems with state-smartness
     and reduced extensibility; for convenience there are a few parsing
     words, but they have non-parsing counterparts.  There are also a
     few defining words that parse.  This is hard to avoid, because all
     standard defining words parse (except ‘:noname’); however, such
     words are not as bad as many other parsing words, because they are
     not state-smart.

   • It does not try to incorporate everything.  It does a few things
     and does them well (IMO). In particular, this model was not
     designed to support information hiding (although it has features
     that may help); you can use a separate package for achieving this.

   • It is layered; you don't have to learn and use all features to use
     this model.  Only a few features are necessary (*note Basic Objects
     Usage::, *note The Objects base class::, *note Creating
     objects::.), the others are optional and independent of each other.

   • An implementation in Standard Forth is available.


File: gforth.info,  Node: Basic Objects Usage,  Next: The Objects base class,  Prev: Properties of the Objects model,  Up: Objects

6.26.3.2 Basic ‘objects.fs’ Usage
.................................

You can define a class for graphical objects like this:

     object class \ "object" is the parent class
       selector draw ( x y graphical -- )
     end-class graphical

   This code defines a class ‘graphical’ with an operation ‘draw’.  We
can perform the operation ‘draw’ on any ‘graphical’ object, e.g.:

     100 100 t-rex draw

where ‘t-rex’ is a word (say, a constant) that produces a graphical
object.

   How do we create a graphical object?  With the present definitions,
we cannot create a useful graphical object.  The class ‘graphical’
describes graphical objects in general, but not any concrete graphical
object type (C++ users would call it an _abstract class_); e.g., there
is no method for the selector ‘draw’ in the class ‘graphical’.

   For concrete graphical objects, we define child classes of the class
‘graphical’, e.g.:

     graphical class \ "graphical" is the parent class
       cell% field circle-radius

     :noname ( x y circle -- )
       circle-radius @ draw-circle ;
     overrides draw

     :noname ( n-radius circle -- )
       circle-radius ! ;
     overrides construct

     end-class circle

   Here we define a class ‘circle’ as a child of ‘graphical’, with field
‘circle-radius’ (which behaves just like a field (*note Structures::);
it defines (using ‘overrides’) new methods for the selectors ‘draw’ and
‘construct’ (‘construct’ is defined in ‘object’, the parent class of
‘graphical’).

   Now we can create a circle on the heap (i.e., ‘allocate’d memory)
with:

     50 circle heap-new constant my-circle

‘heap-new’ invokes ‘construct’, thus initializing the field
‘circle-radius’ with 50.  We can draw this new circle at (100,100) with:

     100 100 my-circle draw

   Note: You can only invoke a selector if the object on the TOS (the
receiving object) belongs to the class where the selector was defined or
one of its descendents; e.g., you can invoke ‘draw’ only for objects
belonging to ‘graphical’ or its descendents (e.g., ‘circle’).
Immediately before ‘end-class’, the search order has to be the same as
immediately after ‘class’.


File: gforth.info,  Node: The Objects base class,  Next: Creating objects,  Prev: Basic Objects Usage,  Up: Objects

6.26.3.3 The ‘object.fs’ base class
...................................

When you define a class, you have to specify a parent class.  So how do
you start defining classes?  There is one class available from the
start: ‘object’.  It is ancestor for all classes and so is the only
class that has no parent.  It has two selectors: ‘construct’ and
‘print’.


File: gforth.info,  Node: Creating objects,  Next: Object-Oriented Programming Style,  Prev: The Objects base class,  Up: Objects

6.26.3.4 Creating objects
.........................

You can create and initialize an object of a class on the heap with
‘heap-new’ ( ...  class - object ) and in the dictionary (allocation
with ‘allot’) with ‘dict-new’ ( ...  class - object ).  Both words
invoke ‘construct’, which consumes the stack items indicated by "..."
above.

   If you want to allocate memory for an object yourself, you can get
its alignment and size with ‘class-inst-size 2@’ ( class - align size ).
Once you have memory for an object, you can initialize it with
‘init-object’ ( ...  class object - ); ‘construct’ does only a part of
the necessary work.


File: gforth.info,  Node: Object-Oriented Programming Style,  Next: Class Binding,  Prev: Creating objects,  Up: Objects

6.26.3.5 Object-Oriented Programming Style
..........................................

This section is not exhaustive.

   In general, it is a good idea to ensure that all methods for the same
selector have the same stack effect: when you invoke a selector, you
often have no idea which method will be invoked, so, unless all methods
have the same stack effect, you will not know the stack effect of the
selector invocation.

   One exception to this rule is methods for the selector ‘construct’.
We know which method is invoked, because we specify the class to be
constructed at the same place.  Actually, I defined ‘construct’ as a
selector only to give the users a convenient way to specify
initialization.  The way it is used, a mechanism different from selector
invocation would be more natural (but probably would take more code and
more space to explain).


File: gforth.info,  Node: Class Binding,  Next: Method conveniences,  Prev: Object-Oriented Programming Style,  Up: Objects

6.26.3.6 Class Binding
......................

Normal selector invocations determine the method at run-time depending
on the class of the receiving object.  This run-time selection is called
late binding.

   Sometimes it's preferable to invoke a different method.  For example,
you might want to use the simple method for ‘print’ing ‘object’s instead
of the possibly long-winded ‘print’ method of the receiver class.  You
can achieve this by replacing the invocation of ‘print’ with:

     [bind] object print

in compiled code or:

     bind object print

in interpreted code.  Alternatively, you can define the method with a
name (e.g., ‘print-object’), and then invoke it through the name.  Class
binding is just a (often more convenient) way to achieve the same
effect; it avoids name clutter and allows you to invoke methods directly
without naming them first.

   A frequent use of class binding is this: When we define a method for
a selector, we often want the method to do what the selector does in the
parent class, and a little more.  There is a special word for this
purpose: ‘[parent]’; ‘[parent] _selector_’ is equivalent to ‘[bind]
_parent selector_’, where ‘_parent_’ is the parent class of the current
class.  E.g., a method definition might look like:

     :noname
       dup [parent] foo \ do parent's foo on the receiving object
       ... \ do some more
     ; overrides foo

   In ‘Object-oriented programming in ANS Forth’ (Forth Dimensions,
March 1997), Andrew McKewan presents class binding as an optimization
technique.  I recommend not using it for this purpose unless you are in
an emergency.  Late binding is pretty fast with this model anyway, so
the benefit of using class binding is small; the cost of using class
binding where it is not appropriate is reduced maintainability.

   While we are at programming style questions: You should bind
selectors only to ancestor classes of the receiving object.  E.g., say,
you know that the receiving object is of class ‘foo’ or its descendents;
then you should bind only to ‘foo’ and its ancestors.


File: gforth.info,  Node: Method conveniences,  Next: Classes and Scoping,  Prev: Class Binding,  Up: Objects

6.26.3.7 Method conveniences
............................

In a method you usually access the receiving object pretty often.  If
you define the method as a plain colon definition (e.g., with
‘:noname’), you may have to do a lot of stack gymnastics.  To avoid
this, you can define the method with ‘m: ... ;m’.  E.g., you could
define the method for ‘draw’ing a ‘circle’ with

     m: ( x y circle -- )
       ( x y ) this circle-radius @ draw-circle ;m

   When this method is executed, the receiver object is removed from the
stack; you can access it with ‘this’ (admittedly, in this example the
use of ‘m: ... ;m’ offers no advantage).  Note that I specify the stack
effect for the whole method (i.e.  including the receiver object), not
just for the code between ‘m:’ and ‘;m’.  You cannot use ‘exit’ in
‘m:...;m’; instead, use ‘exitm’.(1)

   You will frequently use sequences of the form ‘this _field_’ (in the
example above: ‘this circle-radius’).  If you use the field only in this
way, you can define it with ‘inst-var’ and eliminate the ‘this’ before
the field name.  E.g., the ‘circle’ class above could also be defined
with:

     graphical class
       cell% inst-var radius

     m: ( x y circle -- )
       radius @ draw-circle ;m
     overrides draw

     m: ( n-radius circle -- )
       radius ! ;m
     overrides construct

     end-class circle

   ‘radius’ can only be used in ‘circle’ and its descendent classes and
inside ‘m:...;m’.

   You can also define fields with ‘inst-value’, which is to ‘inst-var’
what ‘value’ is to ‘variable’.  You can change the value of such a field
with ‘[to-inst]’.  E.g., we could also define the class ‘circle’ like
this:

     graphical class
       inst-value radius

     m: ( x y circle -- )
       radius draw-circle ;m
     overrides draw

     m: ( n-radius circle -- )
       [to-inst] radius ;m
     overrides construct

     end-class circle

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

   (1) Moreover, for any word that calls ‘catch’ and was defined before
loading ‘objects.fs’, you have to redefine it like I redefined ‘catch’:
‘: catch this >r catch r> to-this ;’


File: gforth.info,  Node: Classes and Scoping,  Next: Dividing classes,  Prev: Method conveniences,  Up: Objects

6.26.3.8 Classes and Scoping
............................

Inheritance is frequent, unlike structure extension.  This exacerbates
the problem with the field name convention (*note Standard
Structures::): One always has to remember in which class the field was
originally defined; changing a part of the class structure would require
changes for renaming in otherwise unaffected code.

   To solve this problem, I added a scoping mechanism (which was not in
my original charter): A field defined with ‘inst-var’ (or ‘inst-value’)
is visible only in the class where it is defined and in the descendent
classes of this class.  Using such fields only makes sense in
‘m:’-defined methods in these classes anyway.

   This scoping mechanism allows us to use the unadorned field name,
because name clashes with unrelated words become much less likely.

   Once we have this mechanism, we can also use it for controlling the
visibility of other words: All words defined after ‘protected’ are
visible only in the current class and its descendents.  ‘public’
restores the compilation (i.e.  ‘current’) word list that was in effect
before.  If you have several ‘protected’s without an intervening
‘public’ or ‘set-current’, ‘public’ will restore the compilation word
list in effect before the first of these ‘protected’s.


File: gforth.info,  Node: Dividing classes,  Next: Object Interfaces,  Prev: Classes and Scoping,  Up: Objects

6.26.3.9 Dividing classes
.........................

You may want to do the definition of methods separate from the
definition of the class, its selectors, fields, and instance variables,
i.e., separate the implementation from the definition.  You can do this
in the following way:

     graphical class
       inst-value radius
     end-class circle

     ... \ do some other stuff

     circle methods \ now we are ready

     m: ( x y circle -- )
       radius draw-circle ;m
     overrides draw

     m: ( n-radius circle -- )
       [to-inst] radius ;m
     overrides construct

     end-methods

   You can use several ‘methods’...‘end-methods’ sections.  The only
things you can do to the class in these sections are: defining methods,
and overriding the class's selectors.  You must not define new selectors
or fields.

   Note that you often have to override a selector before using it.  In
particular, you usually have to override ‘construct’ with a new method
before you can invoke ‘heap-new’ and friends.  E.g., you must not create
a circle before the ‘overrides construct’ sequence in the example above.


File: gforth.info,  Node: Object Interfaces,  Next: Objects Implementation,  Prev: Dividing classes,  Up: Objects

6.26.3.10 Object Interfaces
...........................

In this model you can only call selectors defined in the class of the
receiving objects or in one of its ancestors.  If you call a selector
with a receiving object that is not in one of these classes, the result
is undefined; if you are lucky, the program crashes immediately.

   Now consider the case when you want to have a selector (or several)
available in two classes: You would have to add the selector to a common
ancestor class, in the worst case to ‘object’.  You may not want to do
this, e.g., because someone else is responsible for this ancestor class.

   The solution for this problem is interfaces.  An interface is a
collection of selectors.  If a class implements an interface, the
selectors become available to the class and its descendents.  A class
can implement an unlimited number of interfaces.  For the problem
discussed above, we would define an interface for the selector(s), and
both classes would implement the interface.

   As an example, consider an interface ‘storage’ for writing objects to
disk and getting them back, and a class ‘foo’ that implements it.  The
code would look like this:

     interface
       selector write ( file object -- )
       selector read1 ( file object -- )
     end-interface storage

     bar class
       storage implementation

     ... overrides write
     ... overrides read1
     ...
     end-class foo

(I would add a word ‘read’ ( file - object ) that uses ‘read1’
internally, but that's beyond the point illustrated here.)

   Note that you cannot use ‘protected’ in an interface; and of course
you cannot define fields.

   In the Neon model, all selectors are available for all classes;
therefore it does not need interfaces.  The price you pay in this model
is slower late binding, and therefore, added complexity to avoid late
binding.


File: gforth.info,  Node: Objects Implementation,  Next: Objects Glossary,  Prev: Object Interfaces,  Up: Objects

6.26.3.11 ‘objects.fs’ Implementation
.....................................

An object is a piece of memory, like one of the data structures
described with ‘struct...end-struct’.  It has a field ‘object-map’ that
points to the method map for the object's class.

   The _method map_(1) is an array that contains the execution tokens
(xts) of the methods for the object's class.  Each selector contains an
offset into a method map.

   ‘selector’ is a defining word that uses ‘CREATE’ and ‘DOES>’.  The
body of the selector contains the offset; the ‘DOES>’ action for a class
selector is, basically:

     ( object addr ) @ over object-map @ + @ execute

   Since ‘object-map’ is the first field of the object, it does not
generate any code.  As you can see, calling a selector has a small,
constant cost.

   A class is basically a ‘struct’ combined with a method map.  During
the class definition the alignment and size of the class are passed on
the stack, just as with ‘struct’s, so ‘field’ can also be used for
defining class fields.  However, passing more items on the stack would
be inconvenient, so ‘class’ builds a data structure in memory, which is
accessed through the variable ‘current-interface’.  After its definition
is complete, the class is represented on the stack by a pointer (e.g.,
as parameter for a child class definition).

   A new class starts off with the alignment and size of its parent, and
a copy of the parent's method map.  Defining new fields extends the size
and alignment; likewise, defining new selectors extends the method map.
‘overrides’ just stores a new xt in the method map at the offset given
by the selector.

   Class binding just gets the xt at the offset given by the selector
from the class's method map and ‘compile,’s (in the case of ‘[bind]’)
it.

   I implemented ‘this’ as a ‘value’.  At the start of an ‘m:...;m’
method the old ‘this’ is stored to the return stack and restored at the
end; and the object on the TOS is stored ‘TO this’.  This technique has
one disadvantage: If the user does not leave the method via ‘;m’, but
via ‘throw’ or ‘exit’, ‘this’ is not restored (and ‘exit’ may crash).
To deal with the ‘throw’ problem, I have redefined ‘catch’ to save and
restore ‘this’; the same should be done with any word that can catch an
exception.  As for ‘exit’, I simply forbid it (as a replacement, there
is ‘exitm’).

   ‘inst-var’ is just the same as ‘field’, with a different ‘DOES>’
action:
     @ this +
   Similar for ‘inst-value’.

   Each class also has a word list that contains the words defined with
‘inst-var’ and ‘inst-value’, and its protected words.  It also has a
pointer to its parent.  ‘class’ pushes the word lists of the class and
all its ancestors onto the search order stack, and ‘end-class’ drops
them.

   An interface is like a class without fields, parent and protected
words; i.e., it just has a method map.  If a class implements an
interface, its method map contains a pointer to the method map of the
interface.  The positive offsets in the map are reserved for class
methods, therefore interface map pointers have negative offsets.
Interfaces have offsets that are unique throughout the system, unlike
class selectors, whose offsets are only unique for the classes where the
selector is available (invokable).

   This structure means that interface selectors have to perform one
indirection more than class selectors to find their method.  Their body
contains the interface map pointer offset in the class method map, and
the method offset in the interface method map.  The ‘does>’ action for
an interface selector is, basically:

     ( object selector-body )
     2dup selector-interface @ ( object selector-body object interface-offset )
     swap object-map @ + @ ( object selector-body map )
     swap selector-offset @ + @ execute

   where ‘object-map’ and ‘selector-offset’ are first fields and
generate no code.

   As a concrete example, consider the following code:

     interface
       selector if1sel1
       selector if1sel2
     end-interface if1

     object class
       if1 implementation
       selector cl1sel1
       cell% inst-var cl1iv1

     ' m1 overrides construct
     ' m2 overrides if1sel1
     ' m3 overrides if1sel2
     ' m4 overrides cl1sel2
     end-class cl1

     create obj1 object dict-new drop
     create obj2 cl1    dict-new drop

   The data structure created by this code (including the data structure
for ‘object’) is shown in the figure (objects-implementation.eps),
assuming a cell size of 4.

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

   (1) This is Self terminology; in C++ terminology: virtual function
table.


File: gforth.info,  Node: Objects Glossary,  Prev: Objects Implementation,  Up: Objects

6.26.3.12 ‘objects.fs’ Glossary
...............................

‘bind’ ( ... "class" "selector" - ...  ) objects "bind"
   Execute the method for SELECTOR in CLASS.

‘<bind>’ ( class selector-xt - xt  ) objects "<bind>"
   XT is the method for the selector SELECTOR-XT in CLASS.

‘bind'’ ( "class" "selector" - xt  ) objects "bind"'
   XT is the method for SELECTOR in CLASS.

‘[bind]’ ( compile-time: "class" "selector" - ; run-time: ... object - ...  ) objects "[bind]"
   Compile the method for SELECTOR in CLASS.

‘class’ ( parent-class - align offset  ) objects "class"
   Start a new class definition as a child of PARENT-CLASS.  ALIGN
OFFSET are for use by FIELD etc.

‘class->map’ ( class - map  ) objects "class->map"
   MAP is the pointer to CLASS's method map; it points to the place in
the map to which the selector offsets refer (i.e., where OBJECT-MAPs
point to).

‘class-inst-size’ ( class - addr  ) objects "class-inst-size"
   Give the size specification for an instance (i.e.  an object) of
CLASS; used as ‘class-inst-size 2 ( class -- align size )’.

‘class-override!’ ( xt sel-xt class-map -  ) objects "class-override!"
   XT is the new method for the selector SEL-XT in CLASS-MAP.

‘class-previous’ ( class -  ) objects "class-previous"
   Drop CLASS's wordlists from the search order.  No checking is made
whether CLASS's wordlists are actually on the search order.

‘class>order’ ( class -  ) objects "class>order"
   Add CLASS's wordlists to the head of the search-order.

‘construct’ ( ... object -  ) objects "construct"
   Initialize the data fields of OBJECT.  The method for the class
OBJECT just does nothing: ‘( object -- )’.

‘current'’ ( "selector" - xt  ) objects "current"'
   XT is the method for SELECTOR in the current class.

‘[current]’ ( compile-time: "selector" - ; run-time: ... object - ...  ) objects "[current]"
   Compile the method for SELECTOR in the current class.

‘current-interface’ ( - addr  ) objects "current-interface"
   Variable: contains the class or interface currently being defined.

‘dict-new’ ( ... class - object  ) objects "dict-new"
   ‘allot’ and initialize an object of class CLASS in the dictionary.

‘end-class’ ( align offset "name" -  ) objects "end-class"
   NAME execution: ‘-- class’
End a class definition.  The resulting class is CLASS.

‘end-class-noname’ ( align offset - class  ) objects "end-class-noname"
   End a class definition.  The resulting class is CLASS.

‘end-interface’ ( "name" -  ) objects "end-interface"
   ‘name’ execution: ‘-- interface’
End an interface definition.  The resulting interface is INTERFACE.

‘end-interface-noname’ ( - interface  ) objects "end-interface-noname"
   End an interface definition.  The resulting interface is INTERFACE.

‘end-methods’ ( -  ) objects "end-methods"
   Switch back from defining methods of a class to normal mode
(currently this just restores the old search order).

‘exitm’ ( -  ) objects "exitm"
   ‘exit’ from a method; restore old ‘this’.

‘heap-new’ ( ... class - object  ) objects "heap-new"
   ‘allocate’ and initialize an object of class CLASS.

‘implementation’ ( interface -  ) objects "implementation"
   The current class implements INTERFACE.  I.e., you can use all
selectors of the interface in the current class and its descendents.

‘init-object’ ( ... class object -  ) objects "init-object"
   Initialize a chunk of memory (OBJECT) to an object of class CLASS;
then performs ‘construct’.

‘inst-value’ ( align1 offset1 "name" - align2 offset2  ) objects "inst-value"
   NAME execution: ‘-- w’
W is the value of the field NAME in ‘this’ object.

‘inst-var’ ( align1 offset1 align size "name" - align2 offset2  ) objects "inst-var"
   NAME execution: ‘-- addr’
ADDR is the address of the field NAME in ‘this’ object.

‘interface’ ( -  ) objects "interface"
   Start an interface definition.

‘m:’ ( - xt colon-sys; run-time: object -  ) objects "m:"
   Start a method definition; OBJECT becomes new ‘this’.

‘:m’ ( "name" - xt; run-time: object -  ) objects ":m"
   Start a named method definition; OBJECT becomes new ‘this’.  Has to
be ended with ‘;m’.

‘;m’ ( colon-sys -; run-time: -  ) objects ";m"
   End a method definition; restore old ‘this’.

‘method’ ( xt "name" -  ) objects "method"
   ‘name’ execution: ‘... object -- ...’
Create selector NAME and makes XT its method in the current class.

‘methods’ ( class -  ) objects "methods"
   Makes CLASS the current class.  This is intended to be used for
defining methods to override selectors; you cannot define new fields or
selectors.

‘object’ ( - class  ) objects "object"
   the ancestor of all classes.

‘overrides’ ( xt "selector" -  ) objects "overrides"
   replace default method for SELECTOR in the current class with XT.
‘overrides’ must not be used during an interface definition.

‘[parent]’ ( compile-time: "selector" - ; run-time: ... object - ...  ) objects "[parent]"
   Compile the method for SELECTOR in the parent of the current class.

‘print’ ( object -  ) objects "print"
   Print the object.  The method for the class OBJECT prints the address
of the object and the address of its class.

‘protected’ ( -  ) objects "protected"
   Set the compilation wordlist to the current class's wordlist

‘public’ ( -  ) objects "public"
   Restore the compilation wordlist that was in effect before the last
‘protected’ that actually changed the compilation wordlist.

‘selector’ ( "name" -  ) objects "selector"
   NAME execution: ‘... object -- ...’
Create selector NAME for the current class and its descendents; you can
set a method for the selector in the current class with ‘overrides’.

‘this’ ( - object  ) objects "this"
   the receiving object of the current method (aka active object).

‘<to-inst>’ ( w xt -  ) objects "<to-inst>"
   store W into the field XT in ‘this’ object.

‘[to-inst]’ ( compile-time: "name" - ; run-time: w -  ) objects "[to-inst]"
   store W into field NAME in ‘this’ object.

‘to-this’ ( object -  ) objects "to-this"
   Set ‘this’ (used internally, but useful when debugging).

‘xt-new’ ( ... class xt - object  ) objects "xt-new"
   Make a new object, using ‘xt ( align size -- addr )’ to get memory.


File: gforth.info,  Node: OOF,  Next: Mini-OOF,  Prev: Objects,  Up: Object-oriented Forth

6.26.4 The ‘oof.fs’ model
-------------------------

This section describes the ‘oof.fs’ package.

   The package described in this section has been used in bigFORTH since
1991, and used for two large applications: a chromatographic system used
to create new medicaments, and a graphic user interface library (MINOS).

   You can find a description (in German) of ‘oof.fs’ in ‘Object
oriented bigFORTH’ by Bernd Paysan, published in ‘Vierte Dimension’
10(2), 1994.

* Menu:

* Properties of the OOF model::
* Basic OOF Usage::
* The OOF base class::
* Class Declaration::

