This is Info file gforth.info, produced by Makeinfo version 1.68 from
the input file gforth.texi.

INFO-DIR-SECTION GNU programming tools
START-INFO-DIR-ENTRY
* Gforth: (gforth).             A fast interpreter for the Forth language.
END-INFO-DIR-ENTRY

   This file documents Gforth 0.4.0

   Copyright (C) 1995-1998 Free Software Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
 are preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this      manual under the conditions for verbatim copying, provided
also that the      sections entitled "Distribution" and "General Public
License" are      included exactly as in the original, and provided
that the entire      resulting derived work is distributed under the
terms of a permission      notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual      into another language, under the above conditions for
modified versions,      except that the sections entitled
"Distribution" and "General Public      License" may be included in a
translation approved by the author instead      of in the original
English.


File: gforth.info,  Node: Memory Access,  Next: Address arithmetic,  Prev: Memory,  Up: Memory

Memory Access
-------------

`@'       a-addr - w       core       ``fetch''

`!'       w a-addr -       core       ``store''

`+!'       n a-addr -       core       ``plus-store''

`c@'       c-addr - c       core       ``cfetch''

`c!'       c c-addr -       core       ``cstore''

`2@'       a-addr - w1 w2       core       ``two-fetch''

`2!'       w1 w2 a-addr -       core       ``two-store''

`f@'       f-addr - r       float       ``f-fetch''

`f!'       r f-addr -       float       ``f-store''

`sf@'       sf-addr - r       float-ext       ``s-f-fetch''

`sf!'       r sf-addr -       float-ext       ``s-f-store''

`df@'       df-addr - r       float-ext       ``d-f-fetch''

`df!'       r df-addr -       float-ext       ``d-f-store''


File: gforth.info,  Node: Address arithmetic,  Next: Memory Blocks,  Prev: Memory Access,  Up: Memory

Address arithmetic
------------------

   ANS Forth does not specify the sizes of the data types. Instead, it
offers a number of words for computing sizes and doing address
arithmetic. Basically, address arithmetic is performed in terms of
address units (aus); on most systems the address unit is one byte. Note
that a character may have more than one au, so `chars' is no noop (on
systems where it is a noop, it compiles to nothing).

   ANS Forth also defines words for aligning addresses for specific
types. Many computers require that accesses to specific data types must
only occur at specific addresses; e.g., that cells may only be accessed
at addresses divisible by 4. Even if a machine allows unaligned
accesses, it can usually perform aligned accesses faster.

   For the performance-conscious: alignment operations are usually only
necessary during the definition of a data structure, not during the
(more frequent) accesses to it.

   ANS Forth defines no words for character-aligning addresses. This is
not an oversight, but reflects the fact that addresses that are not
char-aligned have no use in the standard and therefore will not be
created.

   The standard guarantees that addresses returned by `CREATE'd words
are cell-aligned; in addition, Gforth guarantees that these addresses
are aligned for all purposes.

   Note that the standard defines a word `char', which has nothing to
do with address arithmetic.

`chars'       n1 - n2         core       ``chars''

`char+'       c-addr1 - c-addr2       core       ``care-plus''

`cells'       n1 - n2       core       ``cells''

`cell+'       a-addr1 - a-addr2       core       ``cell-plus''

`cell'       - u         gforth       ``cell''

`align'       -         core       ``align''

`aligned'       c-addr - a-addr       core       ``aligned''

`floats'       n1 - n2       float       ``floats''

`float+'       f-addr1 - f-addr2       float       ``float-plus''

`float'       - u         gforth       ``float''

`falign'       -         float       ``falign''

`faligned'       c-addr - f-addr       float       ``f-aligned''

`sfloats'       n1 - n2       float-ext       ``s-floats''

`sfloat+'       sf-addr1 - sf-addr2         float-ext       ``s-float-plus''

`sfalign'       -         float-ext       ``s-f-align''

`sfaligned'       c-addr - sf-addr       float-ext       ``s-f-aligned''

`dfloats'       n1 - n2       float-ext       ``d-floats''

`dfloat+'       df-addr1 - df-addr2         float-ext       ``d-float-plus''

`dfalign'       -         float-ext       ``d-f-align''

`dfaligned'       c-addr - df-addr       float-ext       ``d-f-aligned''

`maxalign'       -         float       ``maxalign''

`maxaligned'       addr - f-addr         float       ``maxaligned''

`cfalign'       -         gforth       ``cfalign''

`cfaligned'       addr1 - addr2         gforth       ``cfaligned''

`ADDRESS-UNIT-BITS'       - n         environment       ``ADDRESS-UNIT-BITS''


File: gforth.info,  Node: Memory Blocks,  Prev: Address arithmetic,  Up: Memory

Memory Blocks
-------------

`move'       c-from c-to ucount -       core       ``move''

`erase'       addr len -         core-ext       ``erase''

   While the previous words work on address units, the rest works on
characters.

`cmove'       c-from c-to u -       string       ``cmove''

`cmove>'       c-from c-to u -       string       ``c-move-up''

`fill'       c-addr u c -       core       ``fill''

`blank'       addr len -         string       ``blank''


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

Control Structures
==================

   Control structures in Forth cannot be used in interpret state, only
in compile state(1), i.e., in a colon definition. We do not like this
limitation, but have not seen a satisfying way around it yet, although
many schemes have been proposed.

* Menu:

* Selection::
* Simple Loops::
* Counted Loops::
* Arbitrary control structures::
* Calls and returns::
* Exception Handling::

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

   (1) More precisely, they have no interpretation semantics (*note
Interpretation and Compilation Semantics::.)


File: gforth.info,  Node: Selection,  Next: Simple Loops,  Prev: Control Structures,  Up: Control Structures

Selection
---------

     FLAG
     IF
       CODE
     ENDIF
   or
     FLAG
     IF
       CODE1
     ELSE
       CODE2
     ENDIF

   You can use `THEN' instead of `ENDIF'. Indeed, `THEN' is standard,
and `ENDIF' is not, although it is quite popular. We recommend using
`ENDIF', because it is less confusing for people who also know other
languages (and is not prone to reinforcing negative prejudices against
Forth in these people). Adding `ENDIF' to a system that only supplies
`THEN' is simple:
     : endif   POSTPONE then ; immediate

   [According to `Webster's New Encyclopedic Dictionary', "then (adv.)"
has the following meanings:
     ... 2b: following next after in order ... 3d: as a necessary
     consequence (if you were there, then you saw them).
   Forth's `THEN' has the meaning 2b, whereas `THEN' in Pascal and many
other programming languages has the meaning 3d.]

   Gforth also provides the words `?dup-if' and `?dup-0=-if', so you
can avoid using `?dup'. Using these alternatives is also more efficient
than using `?dup'. Definitions in plain standard Forth for `ENDIF',
`?DUP-IF' and `?DUP-0=-IF' are provided in `compat/control.fs'.

     N
     CASE
       N1 OF CODE1 ENDOF
       N2 OF CODE2 ENDOF
       ...
     ENDCASE

   Executes the first CODEI, where the NI is equal to N. A default case
can be added by simply writing the code after the last `ENDOF'. It may
use N, which is on top of the stack, but must not consume it.


File: gforth.info,  Node: Simple Loops,  Next: Counted Loops,  Prev: Selection,  Up: Control Structures

Simple Loops
------------

     BEGIN
       CODE1
       FLAG
     WHILE
       CODE2
     REPEAT

   CODE1 is executed and FLAG is computed. If it is true, CODE2 is
executed and the loop is restarted; If FLAG is false, execution
continues after the `REPEAT'.

     BEGIN
       CODE
       FLAG
     UNTIL

   CODE is executed. The loop is restarted if `flag' is false.

     BEGIN
       CODE
     AGAIN

   This is an endless loop.


File: gforth.info,  Node: Counted Loops,  Next: Arbitrary control structures,  Prev: Simple Loops,  Up: Control Structures

Counted Loops
-------------

   The basic counted loop is:
     LIMIT START
     ?DO
       BODY
     LOOP

   This performs one iteration for every integer, starting from START
and up to, but excluding LIMIT. The counter, aka index, can be accessed
with `i'. E.g., the loop
     10 0 ?DO
       i .
     LOOP
   prints
     0 1 2 3 4 5 6 7 8 9
   The index of the innermost loop can be accessed with `i', the index
of the next loop with `j', and the index of the third loop with `k'.

`i'       - n       core       ``i''

`j'       - n       core       ``j''

`k'       - n       gforth       ``k''

   The loop control data are kept on the return stack, so there are some
restrictions on mixing return stack accesses and counted loop words.
E.g., if you put values on the return stack outside the loop, you
cannot read them inside the loop. If you put values on the return stack
within a loop, you have to remove them before the end of the loop and
before accessing the index of the loop.

   There are several variations on the counted loop:

   `LEAVE' leaves the innermost counted loop immediately.

   If START is greater than LIMIT, a `?DO' loop is entered (and `LOOP'
iterates until they become equal by wrap-around arithmetic). This
behaviour is usually not what you want. Therefore, Gforth offers `+DO'
and `U+DO' (as replacements for `?DO'), which do not enter the loop if
START is greater than LIMIT; `+DO' is for signed loop parameters,
`U+DO' for unsigned loop parameters.

   `LOOP' can be replaced with `N +LOOP'; this updates the index by N
instead of by 1. The loop is terminated when the border between LIMIT-1
and LIMIT is crossed. E.g.:

   `4 0 +DO  i .  2 +LOOP'   prints `0 2'

   `4 1 +DO  i .  2 +LOOP'   prints `1 3'

   The behaviour of `N +LOOP' is peculiar when N is negative:

   `-1 0 ?DO  i .  -1 +LOOP'  prints `0 -1'

   ` 0 0 ?DO  i .  -1 +LOOP'  prints nothing

   Therefore we recommend avoiding `N +LOOP' with negative N. One
alternative is `U -LOOP', which reduces the index by U each iteration.
The loop is terminated when the border between LIMIT+1 and LIMIT is
crossed. Gforth also provides `-DO' and `U-DO' for down-counting loops.
E.g.:

   `-2 0 -DO  i .  1 -LOOP'  prints `0 -1'

   `-1 0 -DO  i .  1 -LOOP'  prints `0'

   ` 0 0 -DO  i .  1 -LOOP'  prints nothing

   Unfortunately, `+DO', `U+DO', `-DO', `U-DO' and `-LOOP' are not in
the ANS Forth standard. However, an implementation for these words that
uses only standard words is provided in `compat/loops.fs'.

   `?DO' can also be replaced by `DO'. `DO' always enters the loop,
independent of the loop parameters. Do not use `DO', even if you know
that the loop is entered in any case. Such knowledge tends to become
invalid during maintenance of a program, and then the `DO' will make
trouble.

   `UNLOOP' is used to prepare for an abnormal loop exit, e.g., via
`EXIT'. `UNLOOP' removes the loop control parameters from the return
stack so `EXIT' can get to its return address.

   Another counted loop is
     N
     FOR
       BODY
     NEXT
   This is the preferred loop of native code compiler writers who are
too lazy to optimize `?DO' loops properly. In Gforth, this loop
iterates N+1 times; `i' produces values starting with N and ending with
0. Other Forth systems may behave differently, even if they support
`FOR' loops. To avoid problems, don't use `FOR' loops.


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

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

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

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

`IF'       compilation - orig ; run-time f -         core       ``IF''

`AHEAD'       compilation - orig ; run-time -         tools-ext       ``AHEAD''

`THEN'       compilation orig - ; run-time -         core       ``THEN''

`BEGIN'       compilation - dest ; run-time -         core       ``BEGIN''

`UNTIL'       compilation dest - ; run-time f -         core       ``UNTIL''

`AGAIN'       compilation dest - ; run-time -         core-ext       ``AGAIN''

`CS-PICK'       ... u - ... destu         tools-ext       ``CS-PICK''

`CS-ROLL'       destu/origu .. dest0/orig0 u - .. dest0/orig0 destu/origu         tools-ext       ``CS-ROLL''

   On many systems control-flow stack items take one word, in Gforth
they currently take three (this may change in the future). Therefore it
is a really good idea to manipulate the control flow stack with
`cs-pick' and `cs-roll', not with data stack manipulation words.

   Some standard control structure words are built from these words:

`ELSE'       compilation orig1 - orig2 ; run-time f -         core       ``ELSE''

`WHILE'       compilation dest - orig dest ; run-time f -         core       ``WHILE''

`REPEAT'       compilation orig dest - ; run-time -         core       ``REPEAT''

   Gforth adds some more control-structure words:

`ENDIF'       compilation orig - ; run-time -         gforth       ``ENDIF''

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

`?DUP-0=-IF'       compilation - orig ; run-time n - n|         gforth       ``question-dupe-zero-equals-if''

   Counted loop words constitute a separate group of words:

`?DO'       compilation - do-sys ; run-time w1 w2 - | loop-sys         core-ext       ``question-do''

`+DO'       compilation - do-sys ; run-time n1 n2 - | loop-sys         gforth       ``plus-do''

`U+DO'       compilation - do-sys ; run-time u1 u2 - | loop-sys         gforth       ``u-plus-do''

`-DO'       compilation - do-sys ; run-time n1 n2 - | loop-sys         gforth       ``minus-do''

`U-DO'       compilation - do-sys ; run-time u1 u2 - | loop-sys         gforth       ``u-minus-do''

`DO'       compilation - do-sys ; run-time w1 w2 - loop-sys         core       ``DO''

`FOR'       compilation - do-sys ; run-time u - loop-sys         gforth       ``FOR''

`LOOP'       compilation do-sys - ; run-time loop-sys1 - | loop-sys2         core       ``LOOP''

`+LOOP'       compilation do-sys - ; run-time loop-sys1 n - | loop-sys2         core       ``plus-loop''

`-LOOP'       compilation do-sys - ; run-time loop-sys1 u - | loop-sys2         gforth       ``minus-loop''

`NEXT'       compilation do-sys - ; run-time loop-sys1 - | loop-sys2         gforth       ``NEXT''

`LEAVE'       compilation - ; run-time loop-sys -         core       ``LEAVE''

`?LEAVE'       compilation - ; run-time f | f loop-sys -         gforth       ``question-leave''

`unloop'       -       core       ``unloop''

`DONE'       compilation orig - ; run-time -         gforth       ``DONE''

   The standard does not allow using `cs-pick' and `cs-roll' on do-sys.
Our system allows it, but it's your job to ensure that for every `?DO'
etc. there is exactly one `UNLOOP' on any path through the definition
(`LOOP' etc. compile an `UNLOOP' on the fall-through path). Also, you
have to ensure that all `LEAVE's are resolved (by using one of the
loop-ending words or `DONE').

   Another group of control structure words are

`case'       compilation  - case-sys ; run-time  -         core-ext       ``case''

`endcase'       compilation case-sys - ; run-time x -         core-ext       ``end-case''

`of'       compilation  - of-sys ; run-time x1 x2 - |x1         core-ext       ``of''

`endof'       compilation case-sys1 of-sys - case-sys2 ; run-time  -         core-ext       ``end-of''

   case-sys and of-sys cannot be processed using `cs-pick' and
`cs-roll'.

Programming Style
.................

   In order to ensure readability we recommend that you do not create
arbitrary control structures directly, but define new control structure
words for the control structure you want and use these words in your
program.

   E.g., instead of writing

     begin
       ...
     if [ 1 cs-roll ]
       ...
     again then

   we recommend defining control structure words, e.g.,

     : while ( dest -- orig dest )
      POSTPONE if
      1 cs-roll ; immediate
     
     : repeat ( orig dest -- )
      POSTPONE again
      POSTPONE then ; immediate

   and then using these to create the control structure:

     begin
       ...
     while
       ...
     repeat

   That's much easier to read, isn't it? Of course, `REPEAT' and
`WHILE' are predefined, so in this example it would not be necessary to
define them.


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

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

   A definition can be called simply be writing the name of the
definition to be called. Note that normally a definition is invisible
during its definition. If you want to write a directly recursive
definition, you can use `recursive' to make the current definition
visible.

`recursive'       compilation - ; run-time -         gforth       ``recursive''
   makes the current definition visible, enabling it to call itself
recursively.

   Another way to perform a recursive call is

`recurse'       compilation - ; run-time ?? - ??         core       ``recurse''
   calls the current definition.

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

   For mutual recursion, use `defer'red words, like this:

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

   When the end of the definition is reached, it returns. An earlier
return can be forced using

`EXIT'       compilation - ; run-time nest-sys -         core       ``EXIT''

   Don't forget to clean up the return stack and `UNLOOP' any
outstanding `?DO'...`LOOP's before `EXIT'ing. The primitive compiled by
`EXIT' is

`;s'       -       gforth       ``semis''


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

Exception Handling
------------------

`catch'       ... xt - ... n         exception       ``catch''

`throw'       y1 .. ym error/0 - y1 .. ym / z1 .. zn error         exception       ``throw''


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

Locals
======

   Local variables can make Forth programming more enjoyable and Forth
programs easier to read. Unfortunately, the locals of ANS Forth are
laden with restrictions. Therefore, we provide not only the ANS Forth
locals wordset, but also our own, more powerful locals wordset (we
implemented the ANS Forth locals wordset through our locals wordset).

   The ideas in this section have also been published in the paper
`Automatic Scoping of Local Variables' by M. Anton Ertl, presented at
EuroForth '94; it is available at
`http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz'.

* Menu:

* Gforth locals::
* ANS Forth locals::


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

Gforth locals
-------------

   Locals can be defined with

     { local1 local2 ... -- comment }
   or
     { local1 local2 ... }

   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.

   This similarity has one disadvantage: It is too easy to confuse
locals declarations with stack comments, causing bugs and making them
hard to find. However, this problem can be avoided by appropriate coding
conventions: Do not use both notations in the same program. If you do,
they should be distinguished using additional means, e.g. by position.

   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^') and characters (`C:', `C^') in two flavours: a
value-flavoured local (defined with `W:', `D:' etc.) produces its value
and can be changed with `TO'. A variable-flavoured local (defined with
`W^' etc.)  produces its address (which becomes invalid when the
variable's scope is left). E.g., the standard word `emit' can be
defined in terms of `type' like this:

     : emit { C^ char* -- }
         char* 1 type ;

   A local without type specifier is a `W:' local. Both flavours of
locals are initialized with values from the data or FP stack.

   Currently there is no way to define locals with user-defined data
structures, but we are working on it.

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

* Menu:

* Where are locals visible by name?::
* How long do locals live?::
* Programming Style::
* Implementation::


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

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       ``scope''

`endscope'       compilation scope - ; run-time  -         gforth       ``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'...`ENDIF' are
visible until the `ENDIF', 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), buggy code
will be produced.

`UNREACHABLE'       -         gforth       ``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. Therefore, the
compiler assumes that no locals are visible after the `BEGIN'. However,
the user 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       ``ASSUME-LIVE''

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

   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 after the `BEGIN' (but should be
visible immediately after the `BEGIN') 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

   ---------- 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: Programming Style,  Prev: Where are locals visible by name?,  Up: Gforth locals

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 value-flavoured local this
means: until the end of its visibility. However, a 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, I 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: Programming Style,  Next: Implementation,  Prev: How long do locals live?,  Up: Gforth 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' in *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: Implementation,  Prev: Programming Style,  Up: Gforth 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:

`@local#'       - w       gforth       ``fetch-local-number''

`f@local#'       - r       gforth       ``f-fetch-local-number''

`laddr#'       - c-addr       gforth       ``laddr-number''

`lp+!#'       -       gforth       ``lp-plus-store-number''
   used with negative immediate values it allocates memory on the local
stack, a positive immediate argument drops memory from the local stack

`lp!'       c-addr -       gforth       ``lp-store''

`>l'       w -       gforth       ``to-l''

`f>l'       r -       gforth       ``f-to-l''

   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 `@local#' for
the inline argument 0. The following compiling words compile the right
specialized version, or the general version, as appropriate:

`compile-@local'       n -         gforth       ``compile-fetch-local''

`compile-f@local'       n -         gforth       ``compile-f-fetch-local''

`compile-lp+!'       n -         gforth       ``compile-l-p-plus-store''

   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 wordlist (aka
vocabulary) has its own methods for searching etc. (*note
Wordlists::.). For the present purpose we defined a wordlist 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 wordlist containing `}', `W:' etc., and then the wordlist
for defining locals without type specifiers.

   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:
`lp+!#' current-locals-size - dest-locals-size
`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:
`lp+!#' current-locals-size - orig-locals-size
<orig target>:
`lp+!#' orig-locals-size - new-locals-size
   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'.

   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 wordlist 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 wordlists:

`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 wordlist implementation make these
operations easy to implement: The locals wordlists 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: ANS Forth locals,  Prev: Gforth locals,  Up: Locals

ANS Forth locals
----------------

   The ANS Forth locals wordset does not define a syntax for locals, but
words that make it possible to define various syntaxes. One of the
possible syntaxes is a subset of the syntax we used in the Gforth locals
wordset, i.e.:

     { local1 local2 ... -- comment }
   or
     { local1 local2 ... }

   The order of the locals corresponds to the order in a stack comment.
The restrictions are:

   * Locals can only be cell-sized values (no type specifiers are
     allowed).

   * Locals can be defined only outside control structures.

   * 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 definition must be in one line.

   Locals defined in this way behave like `VALUE's (*Note Simple
Defining Words::). I.e., they are initialized from the stack. Using
their name produces their value. Their value can be changed using `TO'.

   Since this syntax is supported by Gforth directly, you need not do
anything to use it. If you want to port a program using this syntax to
another ANS Forth system, use `compat/anslocal.fs' to implement the
syntax on the other system.

   Note that a syntax shown in the standard, section A.13 looks
similar, but is quite different in having the order of locals reversed.
Beware!

   The ANS Forth locals wordset itself consists of the following word

`(local)'       addr u -         local       ``paren-local-paren''

   The ANS Forth locals extension wordset defines a syntax, but it is so
awful that we strongly recommend not to use it. 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. The only
merit of this syntax is that it is easy to implement using the ANS Forth
locals wordset.


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

Defining Words
==============

* Menu:

* Simple Defining Words::
* Colon Definitions::
* User-defined Defining Words::
* Supplying names::
* Interpretation and Compilation Semantics::


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

Simple Defining Words
---------------------

`Constant'       w "name" -         core       ``Constant''
   Defines constant NAME

   NAME execution: - W

`2Constant'       w1 w2 "name" -         double       ``2Constant''

`fconstant'       r "name" -         float       ``fconstant''

`Variable'       "name" -         core       ``Variable''

`2Variable'       "name" -         double       ``2Variable''

`fvariable'       "name" -         float       ``fvariable''

`Create'       "name" -         core       ``Create''

`User'       "name" -         gforth       ``User''

`Value'       w "name" -         core-ext       ``Value''

`TO'       addr "name" -         core-ext       ``TO''

`Defer'       "name" -         gforth       ``Defer''

`IS'       addr "name" -         gforth       ``IS''


File: gforth.info,  Node: Colon Definitions,  Next: User-defined Defining Words,  Prev: Simple Defining Words,  Up: Defining Words

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. *Note Interpretation
and Compilation Semantics:: for an in-depth discussion of some of the
issues involved.

`:'       "name" - colon-sys         core       ``colon''

`;'       compilation colon-sys - ; run-time nest-sys         core       ``semicolon''


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

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

   You can create new defining words simply by wrapping defining-time
code around existing defining words and putting the sequence in a colon
definition.

   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

   Technically, this fragment defines a defining word `def-word', and a
word `name'; when you execute `name', the address of the body of `name'
is put on the data stack and CODE2 is executed (the address of the body
of `name' is the address `HERE' returns immediately after the `CREATE').

   In other words, if you make the following definitions:

     : def-word1 ( "name" -- )
         Create CODE1 ;
     
     : action1 ( ... -- ... )
         CODE2 ;
     
     def-word name1

   Using `name1 action1' is equivalent to using `name'.

   E.g., you can implement `Constant' in this way:

     : constant ( w "name" -- )
         create ,
     DOES> ( -- w )
         @ ;

   When you create a constant with `5 constant five', first a new word
`five' is created, then the value 5 is laid down in the body of `five'
with `,'. When `five' is invoked, the address of the body is put on the
stack, and `@' retrieves the value 5.

   In the example above the stack comment after the `DOES>' specifies
the stack effect of the defined words, not the stack effect of the
following code (the following code expects the address of the body on
the top of stack, which is not reflected in the stack comment). This is
the convention that I use and recommend (it clashes a bit with using
locals declarations for stack effect specification, though).

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 -- )
         create ,
     DOES> ( n2 -- n1+n2 )
         @ + ;
     
      3 curry+ 3+
     -2 curry+ 2-

The gory details of `CREATE..DOES>'
...................................

`DOES>'       compilation colon-sys1 - colon-sys2 ; run-time nest-sys -         core       ``does''

   This means that you need not use `CREATE' and `DOES>' in the same
definition; E.g., you can put the `DOES>'-part in a separate
definition. This allows us to, e.g., select among different DOES>-parts:
     : does1
     DOES> ( ... -- ... )
         ... ;
     
     : does2
     DOES> ( ... -- ... )
         ... ;
     
     : def-word ( ... -- ... )
         create ...
         IF
            does1
         ELSE
            does2
         ENDIF ;

   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:
     CREATE name ( ... -- ... )
       INITIALIZATION
     DOES>
       CODE ;
   This is equivalent to the standard
     :noname
     DOES>
         CODE ;
     CREATE name EXECUTE ( ... -- ... )
         INITIALIZATION

   You can get the address of the body of a word with

`>body'       xt - a-addr       core       ``to-body''


File: gforth.info,  Node: Supplying names,  Next: Interpretation and Compilation Semantics,  Prev: User-defined Defining Words,  Up: Defining Words

Supplying names for the defined words
-------------------------------------

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

`nextname'       c-addr u -         gforth       ``nextname''

   E.g.,

     s" foo" nextname create
   is equivalent to
     create foo

   Sometimes you want to define a word without a name. You can do this
with

`noname'       -         gforth       ``noname''

   To make any use of the newly defined word, you need its execution
token. You can get it with

`lastxt'       - xt         gforth       ``lastxt''

   E.g., you can initialize a deferred word with an anonymous colon
definition:
     Defer deferred
     noname : ( ... -- ... )
       ... ;
     lastxt IS deferred

   `lastxt' also works when the last word was not defined as `noname'.

   The standard has also recognized the need for anonymous words and
provides

`:noname'       - xt colon-sys         core-ext       ``colon-no-name''

   This leaves the execution token for the word on the stack after the
closing `;'. You can rewrite the last example with `:noname':
     Defer deferred
     :noname ( ... -- ... )
       ... ;
     IS deferred

