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

This manual is for Gforth (version 0.7.3, June 14, 2014), a fast and
portable implementation of the ANS Forth language.  It serves as
reference manual, but it also contains an introduction to Forth and a
Forth tutorial.

   Copyright (C) 1995, 1996, 1997, 1998, 2000, 2003,
2004,2005,2006,2007,2008 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: Redirection,  Next: Search Paths,  Prev: General files,  Up: Files

5.17.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       "outfile-execute"
   execute xt with the output of `type' etc. redirected to file-id.

`infile-execute'       ... xt file-id - ...         gforth       "infile-execute"
   execute xt with the input of `key' etc. redirected to file-id.

   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: Search Paths,  Prev: Redirection,  Up: Files

5.17.4 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').

* Menu:

* Source Search Paths::
* General Search Paths::


File: gforth.info,  Node: Source Search Paths,  Next: General Search Paths,  Prev: Search Paths,  Up: Search Paths

5.17.4.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       "fpath"

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

5.17.4.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       "open-path-file"
   Look in path PATH-ADDR for the file specified by ADDR1 U1.  If
found, the resulting path and and (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).

`path-allot'       umax -         gforth       "path-allot"
   `Allot' a path with umax characters capacity, initially empty.

`clear-path'       path-addr -         gforth       "clear-path"
   Set the path path-addr to empty.

`also-path'       c-addr len path-addr -         gforth       "also-path"
   add the directory c-addr len to path-addr.

`.path'       path-addr -         gforth       ".path"
   Display the contents of the search path PATH-ADDR.

`path+'       path-addr  "dir" -         gforth       "path+"
   Add the directory DIR to the search path PATH-ADDR.

`path='       path-addr "dir1|dir2|dir3"         gforth       "path="
   Make a complete new search path; the path separator is |.

   Here's an example of creating an empty search path:
     create mypath 500 path-allot \ maximum length 500 chars (is checked)


File: gforth.info,  Node: Blocks,  Next: Other I/O,  Prev: Files,  Up: Words

5.18 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'.

   word `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 - ANS Forth requires blocks to
be available when files are.

   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       "open-blocks"
   Use the file, whose name is given by c-addr u, as the blocks file.

`use'       "file" -         gforth       "use"
   Use file as the blocks file.

`block-offset'       - addr         gforth       "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       "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 - a-addr is the address of a cell 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       "empty-buffer"

`update'       -         block       "update"
   Mark the state of the current block buffer as assigned-dirty.

`updated?'       n - f         gforth       "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       "save-buffer"

`flush'       -         block       "flush"
   Perform the functions of `save-buffers' then `empty-buffers'.

`load'       i*x n - j*x         block       "load"
   Save the current input source specification. Store n in `BLK', set
`>IN' to 0 and interpret. When the parse area is exhausted, restore the
input source specification.

`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       "+load"
   Used within a block to load the block specified as the current block
+ n.

`+thru'       i*x n1 n2 - j*x         gforth       "+thru"
   Used within a block to load the range of blocks specified as the
current block + n1 thru the current block + n2.

`-->'       -         gforth       "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       "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 ANS 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

5.19 Other I/O
==============

* Menu:

* Simple numeric output::       Predefined formats
* Formatted numeric output::    Formatted (pictured) output
* String Formats::              How Forth stores strings in memory
* 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


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

5.19.1 Simple numeric output
----------------------------

The simplest output functions are those that display numbers from the
data or floating-point stacks. Floating-point output is always displayed
using base 10. Numbers displayed from the data stack use the value
stored in `base'.

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

`dec.'       n -         gforth       "dec."
   Display n as a signed decimal number, followed by a space.

`hex.'       u -         gforth       "hex."
   Display u as an unsigned hex number, prefixed with a "$" and
followed by a space.

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

`d.'       d -         double       "d-dot"
   Display (the signed double number) D in free-format. followed by a
space.

`ud.'       ud -         gforth       "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       "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.

`f.'       r -         float-ext       "f-dot"
   Display (the floating-point number) r without exponent, followed by
a space.

`fe.'       r -         float-ext       "f-e-dot"
   Display r using engineering notation (with exponent dividable by 3),
followed by a space.

`fs.'       r -         float-ext       "f-s-dot"
   Display r using scientific notation (with exponent), followed by a
space.

`f.rdp'       rf +nr +nd +np -         gforth       "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.  We recommend
np>nr, if you want to have exponential notation for all numbers.

   Examples of printing the number 1234.5678E23 in the different
floating-point output formats are shown below:

     f. 123456779999999000000000000.
     fe. 123.456779999999E24
     fs. 1.23456779999999E26


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

5.19.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'), converted to ASCII codes and appended to a string that is
built in a scratch-pad area of memory (*note Implementation-defined
options: core-idef.). Arbitrary characters can be appended 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.

`<#'       -         core       "less-number-sign"
   Initialise/clear the pictured numeric output string.

`<<#'       -         gforth       "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 within `<#' and `#>'. Add the next least-significant digit to
the pictured numeric output string. This is achieved by dividing UD1 by
the number in `base' to leave quotient UD2 and remainder N; N is
converted to the appropriate display code (eg ASCII code) and appended
to the string. If the number has been fully converted, UD1 will be 0
and `#' will append a "0" to the string.

`#s'       ud - 0 0         core       "number-sign-s"
   Used within `<#' and `#>'. Convert all remaining digits using the
same algorithm as for `#'. `#s' will convert at least one digit.
Therefore, if UD is 0, `#s' will append a "0" to the pictured numeric
output string.

`hold'       char -         core       "hold"
   Used within `<#' and `#>'. Append the character CHAR to the pictured
numeric output string.

`sign'       n -         core       "sign"
   Used within `<#' and `#>'. If N (a SINGLE number) is negative,
append the display code for a minus sign to the pictured numeric output
string. Since the string is built up "backwards" this is usually used
immediately prior to `#>', as shown in the examples below.

`#>'       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.

`#>>'       -         gforth       "number-sign-greater-greater"
   Release the hold area started with `<<#'.

`represent'       r c-addr u - n f1 f2        float       "represent"

`f>str-rdp'       rf +nr +nd +np - c-addr nr         gforth       "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       "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'.

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
       [char] . hold  \ insert decimal point
       #s             \ convert remaining digits
       [char] $ 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 [char] ) hold THEN \ right-most character of output
       #s             \ convert all digits
       rot            \ get at sign byte
       0< IF [char] ( 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: String Formats,  Next: Displaying characters and strings,  Prev: Formatted numeric output,  Up: Other I/O

5.19.3 String Formats
---------------------

Forth commonly uses two different methods for representing character
strings:

   * As a "counted string", represented by a c-addr. The char addressed
     by c-addr contains a character-count, n, of the string and the
     string occupies the subsequent n char addresses in memory.

   * As cell pair on the stack; c-addr u, where u is the length of the
     string in characters, and c-addr is the address of the first byte
     of the string.

   ANS Forth encourages the use of the second format when representing
strings.

`count'       c-addr1 - c-addr2 u        core       "count"
   c-addr2 is the first character and u the length of the counted
string at c-addr1.

   For words that move, copy and search for strings see *note Memory
Blocks::. For words that display characters and strings see *note
Displaying characters and strings::.


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

5.19.4 Displaying characters and strings
----------------------------------------

This section starts with a glossary of Forth words and ends with a set
of examples.

`bl'       - c-char         core       "b-l"
   c-char is the character value for a space.

`space'       -         core       "space"
   Display one space.

`spaces'       u -         core       "spaces"
   Display N spaces.

`emit'       c -         core       "emit"
   Display the character associated with character value c.

`toupper'       c1 - c2        gforth       "toupper"
   If c1 is a lower-case character (in the current locale), c2 is the
equivalent upper-case character. All other characters are unchanged.

`."'       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 ANS Forth. Gforth's interpretation semantics are to
display the string. This is the simplest way to display a string from
within a definition; see examples below.

`.('       compilation&interpretation "ccc<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.

`.\"'       compilation 'ccc"' - ; run-time -         gforth       "dot-backslash-quote"
   Like `."', but translates C-like \-escape-sequences (see `S\"').

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

`typewhite'       addr n -         gforth       "typewhite"
   Like type, but white space is printed instead of the characters.

`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"'.

`S"'       compilation 'ccc"' - ; run-time - c-addr u         core,file       "s-quote"
   Compilation: Parse a string ccc delimited by a `"' (double quote).
At run-time, return the length, u, and the start address, c-addr of the
string. Interpretation: parse the string as before, and return c-addr,
u. Gforth `allocate's the string. The resulting memory leak is usually
not a problem; the exception is if you create strings containing `S"'
and `evaluate' them; then the leak is not bounded by the size of the
interpreted files and you may want to `free' the strings.  ANS Forth
only guarantees one buffer of 80 characters, so in standard programs
you should assume that the string lives only until the next `s"'.

`s\"'       compilation 'ccc"' - ; run-time - c-addr u         gforth       "s-backslash-quote"
   Like `S"', but translates C-like \-escape-sequences, as follows:
`\a' BEL (alert), `\b' BS, `\e' ESC (not in C99), `\f' FF, `\n'
newline, `\r' CR, `\t' HT, `\v' VT, `\"' ", `\\' \, `\'[0-7]{1,3} octal
numerical character value (non-standard), `\x'[0-9a-f]{0,2} hex
numerical character value (standard only with two digits); a `\' before
any other character is reserved.

`C"'       compilation "ccc<quote>" - ; run-time  - c-addr         core-ext       "c-quote"
   Compilation: parse a string ccc delimited by a `"' (double quote).
At run-time, return c-addr which specifies the counted string ccc.
Interpretation semantics are undefined.

`char'       '<spaces>ccc' - c         core       "char"
   Skip leading spaces. Parse the string ccc and return c, the display
code representing the first character of ccc.

`[Char]'       compilation '<spaces>ccc' - ; run-time - c         core       "bracket-char"
   Compilation: skip leading spaces. Parse the string ccc. Run-time:
return c, the display code representing the first character of ccc.
Interpretation semantics for this word are undefined.

As an example, consider the following text, stored in a file `test.fs':

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

     ." text-4"

     : my-char
       [char] ALPHABET emit
       char emit
     ;

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

     include test.fs <RET> text-1text-3text-4 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-4' is displayed because of Gforth's added
     interpretation semantics for `."'.

   * Message `text-2' is not displayed, because the text interpreter
     performs the compilation semantics for `."' within the definition
     of `my-word'.

   Here are some examples of executing `my-word' and `my-char':

     my-word <RET> text-2
      ok
     my-char fred <RET> Af ok
     my-char jim <RET> Aj ok

   * Message `text-2' is displayed because of the run-time behaviour of
     `."'.

   * `[char]' compiles the "A" from "ALPHABET" and puts its display code
     on the stack at run-time. `emit' always displays the character
     when `my-char' is executed.

   * `char' parses a string at run-time and the second `emit' displays
     the first character of the string.

   * If you type `see my-char' you can see that `[char]' discarded the
     text "LPHABET" and only compiled the display code for "A" into the
     definition of `my-char'.


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

5.19.5 Terminal output
----------------------

If you are outputting to a terminal, you may want to control the
positioning of the cursor: 

`at-xy'       u1 u2 -         facility       "at-x-y"
   Position the cursor so that subsequent text output will take place
at column U1, row U2 of the display. (column 0, row 0 is the top
left-hand corner of the display).

   In order to know where to position the cursor, it is often helpful to
know the size of the screen: 

`form'       - urows ucols        gforth       "form"
   The number of lines and columns in the terminal. These numbers may
change with the window size.  Note that it depends on the OS whether
this reflects the actual size and changes with the window size
(currently only on Unix-like OSs).  On other OSs you just get a
default, and can tell Gforth the terminal size by setting the
environment variables `COLUMNS' and `LINES' before starting Gforth.

   And sometimes you want to use: 

`page'       -         facility       "page"
   Clear the display and set the cursor to the top left-hand corner.

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


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

5.19.6 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?'       - 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.

   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>char if ( c )
       ... \ 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>char'       u - u false | c true         facility-ext       "e-key-to-char"
   Convert keyboard event U into character `c' if possible.

`ekey>fkey'       u1 - u2 f         X:ekeys       "ekey>fkey"
   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         X:ekeys       "k-left"

`k-right'       - u         X:ekeys       "k-right"

`k-up'       - u         X:ekeys       "k-up"

`k-down'       - u         X:ekeys       "k-down"

`k-home'       - u         X:ekeys       "k-home"
   aka Pos1

`k-end'       - u         X:ekeys       "k-end"

`k-prior'       - u         X:ekeys       "k-prior"
   aka PgUp

`k-next'       - u         X:ekeys       "k-next"
   aka PgDn

`k-insert'       - u         X:ekeys       "k-insert"

`k-delete'       - u         X:ekeys       "k-delete"

   The key identifiers for function keys (aka keypad keys) are:

`k-f1'       - u         X:ekeys       "k-f1"

`k-f2'       - u         X:ekeys       "k-f2"

`k-f3'       - u         X:ekeys       "k-f3"

`k-f4'       - u         X:ekeys       "k-f4"

`k-f5'       - u         X:ekeys       "k-f5"

`k-f6'       - u         X:ekeys       "k-f6"

`k-f7'       - u         X:ekeys       "k-f7"

`k-f8'       - u         X:ekeys       "k-f8"

`k-f9'       - u         X:ekeys       "k-f9"

`k-f10'       - u         X:ekeys       "k-f10"

`k-f11'       - u         X:ekeys       "k-f11"

`k-f12'       - u         X:ekeys       "k-f12"

   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         X:ekeys       "k-shift-mask"

`k-ctrl-mask'       - u         X:ekeys       "k-ctrl-mask"

`k-alt-mask'       - u         X:ekeys       "k-alt-mask"

   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.


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

5.19.7 Line input and conversion
--------------------------------

For ways of storing character strings in memory see *note String
Formats::.

   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       "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       "s>number?"
   converts string addr u into d, flag indicates success

`s>unumber?'       c-addr u - ud flag         gforth       "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        float       "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.

   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

5.19.8 Pipes
------------

In addition to using Gforth in pipes created by other processes (*note
Gforth in pipes::), you can create your own pipe with `open-pipe', and
read from or write to it.

`open-pipe'       c-addr u wfam - wfileid wior        gforth       "open-pipe"

`close-pipe'       wfileid - wretval wior        gforth       "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       "broken-pipe-error"
   the error number for a broken pipe


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

5.19.9 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. Most prominent representant is UTF-8.
Let's call these extended characters xchars. The primitive fixed-size
characters stored as bytes are called pchars in this section.

   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. Note: UTF-8 can not store more
     that 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
     character set can be used.

   * 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 pchars in
     memory.

   * XC-ADDR U is a buffer of xchars in memory, starting at XC-ADDR, U
     pchars long.


`xc-size'       xc - u         xchar-ext       "xc-size"
   Computes the memory size of the xchar XC in pchars.

`x-size'       xc-addr u1 - u2         xchar       "x-size"
   Computes the memory size of the first xchar stored at XC-ADDR in
pchars.

`xc@+'       xc-addr1 - xc-addr2 xc         xchar-ext       "xc-fetch-plus"
   Fetchs the xchar XC at XC-ADDR1. XC-ADDR2 points to the first memory
location after XC.

`xc!+?'       xc xc-addr1 u1 - xc-addr2 u2 f         xchar-ext       "xc-store-plus-query"
   Stores the xchar XC into the buffer starting at address XC-ADDR1, U1
pchars 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!+.

`xchar+'       xc-addr1 - xc-addr2         xchar-ext       "xchar+"
   Adds the size of the xchar stored at XC-ADDR1 to this address,
giving XC-ADDR2.

`xchar-'       xc-addr1 - xc-addr2         xchar-ext       "xchar-"
   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       "plus-x-slash-string"
   Step forward by one xchar in the buffer defined by address XC-ADDR1,
size U1 pchars. XC-ADDR2 is the address and u2 the size in pchars of
the remaining buffer after stepping over the first xchar in the buffer.

`x\string-'       xc-addr1 u1 - xc-addr1 u2         xchar       "x-back-string-minus"
   Step backward by one xchar in the buffer defined by address XC-ADDR1
and size U1 in pchars, starting at the end of the buffer. XC-ADDR1 is
the address and U2 the size in pchars of the remaining buffer after
stepping backward over the last xchar in the buffer.

`-trailing-garbage'       xc-addr u1 - addr u2         xchar-ext       "-trailing-garbage"
   Examine the last XCHAR in the buffer XC-ADDR U1--if the encoding is
correct and it repesents a full pchar, 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 pchars that take the same space
to display as the the xchar string starting at XC-ADDR, using U pchars;
assuming a monospaced display font, i.e. pchar width is always an
integer multiple of the width of an ASCII pchar.

`xkey'       - xc         xchar-ext       "xkey"
   Reads an xchar from the terminal. This will discard all input events
up to the completion of the xchar.

`xemit'       xc -         xchar-ext       "xemit"
   Prints an xchar on the terminal.

   There's a new environment query

`xchar-encoding'       - addr u         xchar-ext       "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".


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

5.20 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       "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       "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       "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       "argc"
   `Variable' - the number of command-line arguments (including the
command name).  Changed by `next-arg' and `shift-args'.

`argv'       - addr         gforth       "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: Structures,  Prev: OS command line arguments,  Up: Words

5.21 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 M. Anton Ertl,
`Automatic Scoping of Local Variables
(http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz)', EuroForth '94.

* Menu:

* Gforth locals::
* ANS Forth locals::


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

5.21.1 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?::
* Locals programming style::
* Locals implementation::


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

5.21.1.1 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: Locals programming style,  Prev: Where are locals visible by name?,  Up: Gforth locals

5.21.1.2 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: Locals programming style,  Next: Locals implementation,  Prev: How long do locals live?,  Up: Gforth locals

5.21.1.3 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

5.21.1.4 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#'       #noffset - w        gforth       "fetch-local-number"

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

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

`lp+!#'       #noffset -        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-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 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.

   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 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: ANS Forth locals,  Prev: Gforth locals,  Up: Locals

5.21.2 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 ANS Forth behave like `VALUE's (*note Values::).
I.e., they are initialized from the stack. Using their name produces
their value. Their value can be changed using `TO'.

   Since the syntax above 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 one word:

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

   The ANS Forth locals extension wordset defines a syntax using
`locals|', 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: Structures,  Next: Object-oriented Forth,  Prev: Locals,  Up: Words

5.22 Structures
===============

This section presents the structure package that comes with Gforth. A
version of the package implemented in ANS Forth is available in
`compat/struct.fs'. This package was inspired by a posting on
comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
possibly John Hayes). A version of this section has been published in
M. Anton Ertl, Yet Another Forth Structures Package
(http://www.complang.tuwien.ac.at/forth/objects/structs.html), Forth
Dimensions 19(3), pages 13-16. Marcel Hendrix provided helpful comments.

* Menu:

* Why explicit structure support?::
* Structure Usage::
* Structure Naming Convention::
* Structure Implementation::
* Structure Glossary::
* Forth200x Structures::


File: gforth.info,  Node: Why explicit structure support?,  Next: Structure Usage,  Prev: Structures,  Up: Structures

5.22.1 Why explicit structure support?
--------------------------------------

If we want to use a structure containing several fields, we could simply
reserve memory for it, and access the fields using address arithmetic
(*note Address arithmetic::). As an example, consider a structure with
the following fields

`a'
     is a float

`b'
     is a cell

`c'
     is a float

   Given the (float-aligned) base address of the structure we get the
address of the field

`a'
     without doing anything further.

`b'
     with `float+'

`c'
     with `float+ cell+ faligned'

   It is easy to see that this can become quite tiring.

   Moreover, it is not very readable, because seeing a `cell+' tells us
neither which kind of structure is accessed nor what field is accessed;
we have to somehow infer the kind of structure, and then look up in the
documentation, which field of that structure corresponds to that offset.

   Finally, this kind of address arithmetic also causes maintenance
troubles: If you add or delete a field somewhere in the middle of the
structure, you have to find and change all computations for the fields
afterwards.

   So, instead of using `cell+' and friends directly, how about storing
the offsets in constants:

     0 constant a-offset
     0 float+ constant b-offset
     0 float+ cell+ faligned c-offset

   Now we can get the address of field `x' with `x-offset +'. This is
much better in all respects. Of course, you still have to change all
later offset definitions if you add a field. You can fix this by
declaring the offsets in the following way:

     0 constant a-offset
     a-offset float+ constant b-offset
     b-offset cell+ faligned constant c-offset

   Since we always use the offsets with `+', we could use a defining
word `cfield' that includes the `+' in the action of the defined word:

     : cfield ( n "name" -- )
         create ,
     does> ( name execution: addr1 -- addr2 )
         @ + ;

     0 cfield a
     0 a float+ cfield b
     0 b cell+ faligned cfield c

   Instead of `x-offset +', we now simply write `x'.

   The structure field words now can be used quite nicely. However,
their definition is still a bit cumbersome: We have to repeat the name,
the information about size and alignment is distributed before and
after the field definitions etc.  The structure package presented here
addresses these problems.


File: gforth.info,  Node: Structure Usage,  Next: Structure Naming Convention,  Prev: Why explicit structure support?,  Up: Structures

5.22.2 Structure Usage
----------------------

You can define a structure for a (data-less) linked list with:
     struct
         cell% field list-next
     end-struct list%

   With the address of the list node on the stack, you can compute the
address of the field that contains the address of the next node with
`list-next'. E.g., you can determine the length of a list with:

     : list-length ( list -- n )
     \ "list" is a pointer to the first element of a linked list
     \ "n" is the length of the list
         0 BEGIN ( list1 n1 )
             over
         WHILE ( list1 n1 )
             1+ swap list-next @ swap
         REPEAT
         nip ;

   You can reserve memory for a list node in the dictionary with `list%
%allot', which leaves the address of the list node on the stack. For
the equivalent allocation on the heap you can use `list% %alloc' (or,
for an `allocate'-like stack effect (i.e., with ior), use `list%
%allocate'). You can get the the size of a list node with `list% %size'
and its alignment with `list% %alignment'.

   Note that in ANS Forth the body of a `create'd word is `aligned' but
not necessarily `faligned'; therefore, if you do a:

     create _name_ foo% %allot drop

then the memory alloted for `foo%' is guaranteed to start at the body
of `_name_' only if `foo%' contains only character, cell and double
fields.  Therefore, if your structure contains floats, better use

     foo% %allot constant _name_

   You can include a structure `foo%' as a field of another structure,
like this:
     struct
     ...
         foo% field ...
     ...
     end-struct ...

   Instead of starting with an empty structure, you can extend an
existing structure. E.g., a plain linked list without data, as defined
above, is hardly useful; You can extend it to a linked list of integers,
like this:(1)

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

   `intlist%' is a structure with two fields: `list-next' and
`intlist-int'.

   You can specify an array type containing _n_ elements of type `foo%'
like this:

     foo% _n_ *

   You can use this array type in any place where you can use a normal
type, e.g., when defining a `field', or with `%allot'.

   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 the
structure package optimizes this case: If you compile a first-field
words, no code is generated. So, in the interest of readability and
maintainability you should include the word for the field when accessing
the field.

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

   (1) This feature is also known as _extended records_. It is the main
innovation in the Oberon language; in other words, adding this feature
to Modula-2 led Wirth to create a new language, write a new compiler
etc.  Adding this feature to Forth just required a few lines of code.


File: gforth.info,  Node: Structure Naming Convention,  Next: Structure Implementation,  Prev: Structure Usage,  Up: Structures

5.22.3 Structure Naming Convention
----------------------------------

The field names that come to (my) mind are often quite generic, and, if
used, would cause frequent name clashes. E.g., many structures probably
contain a `counter' field. The structure names that come to (my) mind
are often also the logical choice for the names of words that create
such a structure.

   Therefore, I have adopted the following naming conventions:

   * The names of fields are of the form `_struct_-_field_', where
     `_struct_' is the basic name of the structure, and `_field_' is
     the basic name of the field. You can think of field words as
     converting the (address of the) structure into the (address of
     the) field.

   * The names of structures are of the form `_struct_%', where
     `_struct_' is the basic name of the structure.

   This naming convention does not work that well for fields of extended
structures; e.g., the integer list structure has a field `intlist-int',
but has `list-next', not `intlist-next'.


File: gforth.info,  Node: Structure Implementation,  Next: Structure Glossary,  Prev: Structure Naming Convention,  Up: Structures

5.22.4 Structure Implementation
-------------------------------

The central idea in the implementation is to pass the data about the
structure being built on the stack, not in some global variable.
Everything else falls into place naturally once this design decision is
made.

   The type description on the stack is of the form _align size_.
Keeping the size on the top-of-stack makes dealing with arrays very
simple.

   `field' is a defining word that uses `Create' and `DOES>'. The body
of the field contains the offset of the field, and the normal `DOES>'
action is simply:

     @ +

i.e., add the offset to the address, giving the stack effect addr1 -
addr2 for a field.

   This simple structure is slightly complicated by the optimization
for fields with offset 0, which requires a different `DOES>'-part
(because we cannot rely on there being something on the stack if such a
field is invoked during compilation). Therefore, we put the different
`DOES>'-parts in separate words, and decide which one to invoke based
on the offset. For a zero offset, the field is basically a noop; it is
immediate, and therefore no code is generated when it is compiled.


File: gforth.info,  Node: Structure Glossary,  Next: Forth200x Structures,  Prev: Structure Implementation,  Up: Structures

5.22.5 Structure Glossary
-------------------------

`%align'       align size -         gforth       "%align"
Align the data space pointer to the alignment ALIGN.

`%alignment'       align size - align         gforth       "%alignment"
   The alignment of the structure.

`%alloc'       align size - addr         gforth       "%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       "%allocate"
   Allocate SIZE address units with alignment ALIGN, similar to
`allocate'.

`%allot'       align size - addr         gforth       "%allot"
   Allot SIZE address units of data space with alignment ALIGN; the
resulting block of data is found at ADDR.

`cell%'       - align size         gforth       "cell%"

`char%'       - align size         gforth       "char%"

`dfloat%'       - align size         gforth       "dfloat%"

`double%'       - align size         gforth       "double%"

`end-struct'       align size "name" -         gforth       "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       "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       "float%"

`naligned'       addr1 n - addr2         gforth       "naligned"
   ADDR2 is the aligned version of ADDR1 with respect to the alignment
N.

`sfloat%'       - align size         gforth       "sfloat%"

`%size'       align size - size         gforth       "%size"
   The size of the structure.

`struct'       - align size         gforth       "struct"
   An empty structure, used to start a structure definition.


File: gforth.info,  Node: Forth200x Structures,  Prev: Structure Glossary,  Up: Structures

5.22.6 Forth200x Structures
---------------------------

The Forth 200x standard defines a slightly less convenient form of
structures.  In general (when using `field+', you have to perform the
alignment yourself, but there are a number of convenience words (e.g.,
`field:' that perform the alignment for you.

   A typical usage example is:

     0
       field:                   s-a
       faligned 2 floats +field s-b
     constant s-struct

   An alternative way of writing this structure is:

     begin-structure s-struct
       field:                   s-a
       faligned 2 floats +field s-b
     end-structure

`begin-structure'       "name" - struct-sys 0         X:structures       "begin-structure"

`end-structure'       struct-sys +n -         X:structures       "end-structure"

`+field'       n1 n2 "name" - n3         X:structures       "plus-field"

`cfield:'       u1 "name" - u2         X:structures       "cfield:"

`field:'       u1 "name" - u2         X:structures       "field:"

`2field:'       u1 "name" - u2         gforth       "2field:"

`ffield:'       u1 "name" - u2         X:structures       "ffield:"

`sffield:'       u1 "name" - u2         X:structures       "sffield:"

`dffield:'       u1 "name" - u2         X:structures       "dffield:"


File: gforth.info,  Node: Object-oriented Forth,  Next: Programming Tools,  Prev: Structures,  Up: Words

5.23 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 ANS
Forth and can be used with any other ANS Forth.

* Menu:

* Why object-oriented programming?::
* Object-Oriented Terminology::
* Objects::
* OOF::
* Mini-OOF::
* 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

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

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

5.23.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
(http://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

5.23.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 ANS Forth is available.



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

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

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

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

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

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

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

5.23.3.8 Classes and Scoping
............................

Inheritance is frequent, unlike structure extension. This exacerbates
the problem with the field name convention (*note Structure Naming
Convention::): 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

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

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

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

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

5.23.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::
* Class Implementation::


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

5.23.4.1 Properties of the `oof.fs' model
.........................................

   * This model combines object oriented programming with information
     hiding. It helps you writing large application, where scoping is
     necessary, because it provides class-oriented scoping.

   * Named objects, object pointers, and object arrays can be created,
     selector invocation uses the "object selector" syntax. Selector
     invocation to objects and/or selectors on the stack is a bit less
     convenient, but possible.

   * Selector invocation and instance variable usage of the active
     object is straightforward, since both make use of the active
     object.

   * Late binding is efficient and easy to use.

   * State-smart objects parse selectors. However, extensibility is
     provided using a (parsing) selector `postpone' and a selector `''.

   * An implementation in ANS Forth is available.



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

5.23.4.2 Basic `oof.fs' Usage
.............................

This section uses the same example as for `objects' (*note Basic
Objects Usage::).

   You can define a class for graphical objects like this:

     object class graphical \ "object" is the parent class
       method draw ( x y -- )
     class;

   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 an object or object pointer, created with e.g.
`graphical : t-rex'.

   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 circle \ "graphical" is the parent class
       cell var circle-radius
     how:
       : draw ( x y -- )
         circle-radius @ draw-circle ;

       : init ( n-radius -- )
         circle-radius ! ;
     class;

   Here we define a class `circle' as a child of `graphical', with a
field `circle-radius'; it defines new methods for the selectors `draw'
and `init' (`init' is defined in `object', the parent class of
`graphical').

   Now we can create a circle in the dictionary with:

     50 circle : my-circle

`:' invokes `init', 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 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'). The scoping mechanism will check
if you try to invoke a selector that is not defined in this class
hierarchy, so you'll get an error at compilation time.


File: gforth.info,  Node: The OOF base class,  Next: Class Declaration,  Prev: Basic OOF Usage,  Up: OOF

5.23.4.3 The `oof.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'. You have to use it as ancestor for all classes. It is the
only class that has no parent. Classes are also objects, except that
they don't have instance variables; class manipulation such as
inheritance or changing definitions of a class is handled through
selectors of the class `object'.

   `object' provides a number of selectors:

   * `class' for subclassing, `definitions' to add definitions later
     on, and `class?' to get type informations (is the class a subclass
     of the class passed on the stack?).

     `class'       "name" -         oof       "class"

     `definitions'       -         oof       "definitions"

     `class?'       o - flag         oof       "class-query"

   * `init' and `dispose' as constructor and destructor of the object.
     `init' is invocated after the object's memory is allocated, while
     `dispose' also handles deallocation. Thus if you redefine
     `dispose', you have to call the parent's dispose with `super
     dispose', too.

     `init'       ... -         oof       "init"

     `dispose'       -         oof       "dispose"

   * `new', `new[]', `:', `ptr', `asptr', and `[]' to create named and
     unnamed objects and object arrays or object pointers.

     `new'       - o         oof       "new"

     `new[]'       n - o         oof       "new-array"

     `:'       "name" -         oof       "define"

     `ptr'       "name" -         oof       "ptr"

     `asptr'       o "name" -         oof       "asptr"

     `[]'       n "name" -         oof       "array"

   * `::' and `super' for explicit scoping. You should use explicit
     scoping only for super classes or classes with the same set of
     instance variables. Explicitly-scoped selectors use early binding.

     `::'       "name" -         oof       "scope"

     `super'       "name" -         oof       "super"

   * `self' to get the address of the object

     `self'       - o         oof       "self"

   * `bind', `bound', `link', and `is' to assign object pointers and
     instance defers.

     `bind'       o "name" -         oof       "bind"

     `bound'       class addr "name" -         oof       "bound"

     `link'       "name" - class addr         oof       "link"

     `is'       xt "name" -         oof       "is"

   * `'' to obtain selector tokens, `send' to invocate selectors form
     the stack, and `postpone' to generate selector invocation code.

     `''       "name" - xt         oof       "tick"

     `postpone'       "name" -         oof       "postpone"

   * `with' and `endwith' to select the active object from the stack,
     and enable its scope. Using `with' and `endwith' also allows you
     to create code using selector `postpone' without being trapped by
     the state-smart objects.

     `with'       o -         oof       "with"

     `endwith'       -         oof       "endwith"



File: gforth.info,  Node: Class Declaration,  Next: Class Implementation,  Prev: The OOF base class,  Up: OOF

5.23.4.4 Class Declaration
..........................

   * Instance variables

     `var'       size -         oof       "var"
     Create an instance variable

   * Object pointers

     `ptr'       -         oof       "ptr"
     Create an instance pointer

     `asptr'       class -         oof       "asptr"
     Create an alias to an instance pointer, cast to another class.

   * Instance defers

     `defer'       -         oof       "defer"
     Create an instance defer

   * Method selectors

     `early'       -         oof       "early"
     Create a method selector for early binding.

     `method'       -         oof       "method"
     Create a method selector.

   * Class-wide variables

     `static'       -         oof       "static"
     Create a class-wide cell-sized variable.

   * End declaration

     `how:'       -         oof       "how-to"
     End declaration, start implementation

     `class;'       -         oof       "end-class"
     End class declaration or implementation



File: gforth.info,  Node: Class Implementation,  Prev: Class Declaration,  Up: OOF

5.23.4.5 Class Implementation
.............................


File: gforth.info,  Node: Mini-OOF,  Next: Comparison with other object models,  Prev: OOF,  Up: Object-oriented Forth

5.23.5 The `mini-oof.fs' model
------------------------------

Gforth's third object oriented Forth package is a 12-liner. It uses a
mixture of the `objects.fs' and the `oof.fs' syntax, and reduces to the
bare minimum of features. This is based on a posting of Bernd Paysan in
comp.lang.forth.

* Menu:

* Basic Mini-OOF Usage::
* Mini-OOF Example::
* Mini-OOF Implementation::


File: gforth.info,  Node: Basic Mini-OOF Usage,  Next: Mini-OOF Example,  Prev: Mini-OOF,  Up: Mini-OOF

5.23.5.1 Basic `mini-oof.fs' Usage
..................................

There is a base class (`class', which allocates one cell for the object
pointer) plus seven other words: to define a method, a variable, a
class; to end a class, to resolve binding, to allocate an object and to
compile a class method.

`object'       - a-addr         mini-oof       "object"
   OBJECT is the base class of all objects.

`method'       m v "name" - m' v         mini-oof       "method"
   Define a selector.

`var'       m v size "name" - m v'         mini-oof       "var"
   Define a variable with SIZE bytes.

`class'       class - class selectors vars         mini-oof       "class"
   Start the definition of a class.

`end-class'       class selectors vars "name" -         mini-oof       "end-class"
   End the definition of a class.

`defines'       xt class "name" -         mini-oof       "defines"
   Bind XT to the selector NAME in class CLASS.

`new'       class - o         mini-oof       "new"
   Create a new incarnation of the class CLASS.

`::'       class "name" -         mini-oof       "colon-colon"
   Compile the method for the selector NAME of the class CLASS (not
immediate!).


File: gforth.info,  Node: Mini-OOF Example,  Next: Mini-OOF Implementation,  Prev: Basic Mini-OOF Usage,  Up: Mini-OOF

5.23.5.2 Mini-OOF Example
.........................

A short example shows how to use this package. This example, in slightly
extended form, is supplied as `moof-exm.fs'

     object class
       method init
       method draw
     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 an object or object pointer, created with e.g.
`graphical new Constant t-rex'.

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

     graphical class
       cell var circle-radius
     end-class circle \ "graphical" is the parent class

     :noname ( x y -- )
       circle-radius @ draw-circle ; circle defines draw
     :noname ( r -- )
       circle-radius ! ; circle defines init

   There is no implicit init method, so we have to define one. The
creation code of the object now has to call init explicitely.

     circle new Constant my-circle
     50 my-circle init

   It is also possible to add a function to create named objects with
automatic call of `init', given that all objects have `init' on the
same place:

     : new: ( .. o "name" -- )
         new dup Constant init ;
     80 circle new: large-circle

   We can draw this new circle at (100,100) with:

     100 100 my-circle draw


File: gforth.info,  Node: Mini-OOF Implementation,  Prev: Mini-OOF Example,  Up: Mini-OOF

5.23.5.3 `mini-oof.fs' Implementation
.....................................

Object-oriented systems with late binding typically use a
"vtable"-approach: the first variable in each object is a pointer to a
table, which contains the methods as function pointers. The vtable may
also contain other information.

   So first, let's declare selectors:

     : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
       DOES> ( ... o -- ... ) @ over @ + @ execute ;

   During selector declaration, the number of selectors and instance
variables is on the stack (in address units). `method' creates one
selector and increments the selector number. To execute a selector, it
takes the object, fetches the vtable pointer, adds the offset, and
executes the method xt stored there. Each selector takes the object it
is invoked with as top of stack parameter; it passes the parameters
(including the object) unchanged to the appropriate method which should
consume that object.

   Now, we also have to declare instance variables

     : var ( m v size "name" -- m v' ) Create  over , +
       DOES> ( o -- addr ) @ + ;

   As before, a word is created with the current offset. Instance
variables can have different sizes (cells, floats, doubles, chars), so
all we do is take the size and add it to the offset. If your machine
has alignment restrictions, put the proper `aligned' or `faligned'
before the variable, to adjust the variable offset. That's why it is on
the top of stack.

   We need a starting point (the base object) and some syntactic sugar:

     Create object  1 cells , 2 cells ,
     : class ( class -- class selectors vars ) dup 2@ ;

   For inheritance, the vtable of the parent object has to be copied
when a new, derived class is declared. This gives all the methods of
the parent class, which can be overridden, though.

     : end-class  ( class selectors vars "name" -- )
       Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
       cell+ dup cell+ r> rot @ 2 cells /string move ;

   The first line creates the vtable, initialized with `noop's. The
second line is the inheritance mechanism, it copies the xts from the
parent vtable.

   We still have no way to define new methods, let's do that now:

     : defines ( xt class "name" -- ) ' >body @ + ! ;

   To allocate a new object, we need a word, too:

     : new ( class -- o )  here over @ allot swap over ! ;

   Sometimes derived classes want to access the method of the parent
object. There are two ways to achieve this with Mini-OOF: first, you
could use named words, and second, you could look up the vtable of the
parent object.

     : :: ( class "name" -- ) ' >body @ + @ compile, ;

   Nothing can be more confusing than a good example, so here is one.
First let's declare a text object (called `button'), that stores text
and position:

     object class
       cell var text
       cell var len
       cell var x
       cell var y
       method init
       method draw
     end-class button

Now, implement the two methods, `draw' and `init':

     :noname ( o -- )
      >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
      button defines draw
     :noname ( addr u o -- )
      >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
      button defines init

To demonstrate inheritance, we define a class `bold-button', with no
new data and no new selectors:

     button class
     end-class bold-button

     : bold   27 emit ." [1m" ;
     : normal 27 emit ." [0m" ;

The class `bold-button' has a different draw method to `button', but
the new method is defined in terms of the draw method for `button':

     :noname bold [ button :: draw ] normal ; bold-button defines draw

Finally, create two objects and apply selectors:

     button new Constant foo
     s" thin foo" foo init
     page
     foo draw
     bold-button new Constant bar
     s" fat bar" bar init
     1 bar y !
     bar draw


File: gforth.info,  Node: Comparison with other object models,  Prev: Mini-OOF,  Up: Object-oriented Forth

5.23.6 Comparison with other object models
------------------------------------------

Many object-oriented Forth extensions have been proposed (`A survey of
object-oriented Forths' (SIGPLAN Notices, April 1996) by Bradford J.
Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
relation of the object models described here to two well-known and two
closely-related (by the use of method maps) models.  Andras Zsoter
helped us with this section.

   The most popular model currently seems to be the Neon model (see
`Object-oriented programming in ANS Forth' (Forth Dimensions, March
1997) by Andrew McKewan) but this model has a number of limitations (1):

   * It uses a `_selector object_' syntax, which makes it unnatural to
     pass objects on the stack.

   * It requires that the selector parses the input stream (at compile
     time); this leads to reduced extensibility and to bugs that are
     hard to find.

   * It allows using every selector on every object; this eliminates the
     need for interfaces, but makes it harder to create efficient
     implementations.

   Another well-known publication is `Object-Oriented Forth' (Academic
Press, London, 1987) by Dick Pountain. However, it is not really about
object-oriented programming, because it hardly deals with late binding.
Instead, it focuses on features like information hiding and overloading
that are characteristic of modular languages like Ada (83).

   In Does late binding have to be slow?
(http://www.forth.org/oopf.html) (Forth Dimensions 18(1) 1996, pages
31-35) Andras Zsoter describes a model that makes heavy use of an
active object (like `this' in `objects.fs'): The active object is not
only used for accessing all fields, but also specifies the receiving
object of every selector invocation; you have to change the active
object explicitly with `{ ... }', whereas in `objects.fs' it changes
more or less implicitly at `m: ... ;m'. Such a change at the method
entry point is unnecessary with Zsoter's model, because the receiving
object is the active object already. On the other hand, the explicit
change is absolutely necessary in that model, because otherwise no one
could ever change the active object. An ANS Forth implementation of
this model is available through `http://www.forth.org/oopf.html'.

   The `oof.fs' model combines information hiding and overloading
resolution (by keeping names in various word lists) with object-oriented
programming. It sets the active object implicitly on method entry, but
also allows explicit changing (with `>o...o>' or with
`with...endwith'). It uses parsing and state-smart objects and classes
for resolving overloading and for early binding: the object or class
parses the selector and determines the method from this. If the
selector is not parsed by an object or class, it performs a call to the
selector for the active object (late binding), like Zsoter's model.
Fields are always accessed through the active object. The big
disadvantage of this model is the parsing and the state-smartness, which
reduces extensibility and increases the opportunities for subtle bugs;
essentially, you are only safe if you never tick or `postpone' an
object or class (Bernd disagrees, but I (Anton) am not convinced).

   The `mini-oof.fs' model is quite similar to a very stripped-down
version of the `objects.fs' model, but syntactically it is a mixture of
the `objects.fs' and `oof.fs' models.

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

   (1) A longer version of this critique can be found in `On
Standardizing Object-Oriented Forth Extensions' (Forth Dimensions, May
1997) by Anton Ertl.


File: gforth.info,  Node: Programming Tools,  Next: C Interface,  Prev: Object-oriented Forth,  Up: Words

5.24 Programming Tools
======================

* Menu:

* Examining::                   Data and Code.
* Forgetting words::            Usually before reloading.
* Debugging::                   Simple and quick.
* Assertions::                  Making your programs self-checking.
* Singlestep Debugger::         Executing your program word by word.


File: gforth.info,  Node: Examining,  Next: Forgetting words,  Prev: Programming Tools,  Up: Programming Tools

5.24.1 Examining data and code
------------------------------

The following words inspect the stack non-destructively:

`.s'       -         tools       "dot-s"
   Display the number of items on the data stack, followed by a list of
the items (but not more than specified by `maxdepth-.s'; TOS is the
right-most item.

`f.s'       -         gforth       "f-dot-s"
   Display the number of items on the floating-point stack, followed by
a list of the items (but not more than specified by `maxdepth-.s'; TOS
is the right-most item.

`maxdepth-.s'       - addr         gforth       "maxdepth-dot-s"
   A variable containing 9 by default.  `.s' and `f.s' display at most
that many stack items.

   There is a word `.r' but it does not display the return stack!  It
is used for formatted numeric output (*note Simple numeric output::).

`depth'       - +n         core       "depth"
   +N is the number of values that were on the data stack before +N
itself was placed on the stack.

`fdepth'       - +n         float       "f-depth"
   +n is the current number of (floating-point) values on the
floating-point stack.

`clearstack'       ... -         gforth       "clear-stack"
   remove and discard all/any items from the data stack.

`clearstacks'       ... -         gforth       "clear-stacks"
   empty data and FP stack

   The following words inspect memory.

`?'       a-addr -         tools       "question"
   Display the contents of address A-ADDR in the current number base.

`dump'       addr u -         tools       "dump"
   Display U lines of memory starting at address ADDR. Each line
displays the contents of 16 bytes. When Gforth is running under an
operating system you may get `Invalid memory address' errors if you
attempt to access arbitrary locations.

   And finally, `see' allows to inspect code:

`see'       "<spaces>name" -         tools       "see"
   Locate NAME using the current search order. Display the definition
of NAME. Since this is achieved by decompiling the definition, the
formatting is mechanised and some source information (comments,
interpreted sequences within definitions etc.) is lost.

`xt-see'       xt -         gforth       "xt-see"
   Decompile the definition represented by xt.

`simple-see'       "name" -         gforth       "simple-see"
   a simple decompiler that's closer to `dump' than `see'.

`simple-see-range'       addr1 addr2 -         gforth       "simple-see-range"

`see-code'       "name" -         gforth       "see-code"
   like `simple-see', but also shows the dynamic native code for the
inlined primitives (except for the last).

`see-code-range'       addr1 addr2 -         gforth       "see-code-range"


File: gforth.info,  Node: Forgetting words,  Next: Debugging,  Prev: Examining,  Up: Programming Tools

5.24.2 Forgetting words
-----------------------

Forth allows you to forget words (and everything that was alloted in the
dictonary after them) in a LIFO manner.

`marker'       "<spaces> name" -         core-ext       "marker"
   Create a definition, name (called a mark) whose execution semantics
are to remove itself and everything defined after it.

   The most common use of this feature is during progam development:
when you change a source file, forget all the words it defined and load
it again (since you also forget everything defined after the source file
was loaded, you have to reload that, too).  Note that effects like
storing to variables and destroyed system words are not undone when you
forget words.  With a system like Gforth, that is fast enough at
starting up and compiling, I find it more convenient to exit and restart
Gforth, as this gives me a clean slate.

   Here's an example of using `marker' at the start of a source file
that you are debugging; it ensures that you only ever have one copy of
the file's definitions compiled at any time:

     [IFDEF] my-code
         my-code
     [ENDIF]

     marker my-code
     init-included-files

     \ .. definitions start here
     \ .
     \ .
     \ end


File: gforth.info,  Node: Debugging,  Next: Assertions,  Prev: Forgetting words,  Up: Programming Tools

5.24.3 Debugging
----------------

Languages with a slow edit/compile/link/test development loop tend to
require sophisticated tracing/stepping debuggers to facilate debugging.

   A much better (faster) way in fast-compiling languages is to add
printing code at well-selected places, let the program run, look at the
output, see where things went wrong, add more printing code, etc.,
until the bug is found.

   The simple debugging aids provided in `debugs.fs' are meant to
support this style of debugging.

   The word `~~' prints debugging information (by default the source
location and the stack contents). It is easy to insert. If you use Emacs
it is also easy to remove (`C-x ~' in the Emacs Forth mode to
query-replace them with nothing). The deferred words `printdebugdata'
and `.debugline' control the output of `~~'. The default source
location output format works well with Emacs' compilation mode, so you
can step through the program at the source level using `C-x `' (the
advantage over a stepping debugger is that you can step in any
direction and you know where the crash has happened or where the
strange data has occurred).

`~~'       -         gforth       "tilde-tilde"
   Prints the source code location of the `~~' and the stack contents
with `.debugline'.

`printdebugdata'       -         gforth       "print-debug-data"

`.debugline'       nfile nline -         gforth       "print-debug-line"
   Print the source code location indicated by NFILE NLINE, and
additional debugging information; the default `.debugline' prints the
additional information with `printdebugdata'.

   `~~' (and assertions) will usually print the wrong file name if a
marker is executed in the same file after their occurance.  They will
print `*somewhere*' as file name if a marker is executed in the same
file before their occurance.


File: gforth.info,  Node: Assertions,  Next: Singlestep Debugger,  Prev: Debugging,  Up: Programming Tools

5.24.4 Assertions
-----------------

It is a good idea to make your programs self-checking, especially if you
make an assumption that may become invalid during maintenance (for
example, that a certain field of a data structure is never zero). Gforth
supports "assertions" for this purpose. They are used like this:

     assert( flag )

   The code between `assert(' and `)' should compute a flag, that
should be true if everything is alright and false otherwise. It should
not change anything else on the stack. The overall stack effect of the
assertion is `( -- )'. E.g.

     assert( 1 1 + 2 = ) \ what we learn in school
     assert( dup 0<> ) \ assert that the top of stack is not zero
     assert( false ) \ this code should not be reached

   The need for assertions is different at different times. During
debugging, we want more checking, in production we sometimes care more
for speed. Therefore, assertions can be turned off, i.e., the assertion
becomes a comment. Depending on the importance of an assertion and the
time it takes to check it, you may want to turn off some assertions and
keep others turned on. Gforth provides several levels of assertions for
this purpose:

`assert0('       -         gforth       "assert-zero"
   Important assertions that should always be turned on.

`assert1('       -         gforth       "assert-one"
   Normal assertions; turned on by default.

`assert2('       -         gforth       "assert-two"
   Debugging assertions.

`assert3('       -         gforth       "assert-three"
   Slow assertions that you may not want to turn on in normal debugging;
you would turn them on mainly for thorough checking.

`assert('       -         gforth       "assert("
   Equivalent to `assert1('

`)'       -         gforth       "close-paren"
   End an assertion.

   The variable `assert-level' specifies the highest assertions that
are turned on. I.e., at the default `assert-level' of one, `assert0('
and `assert1(' assertions perform checking, while `assert2(' and
`assert3(' assertions are treated as comments.

   The value of `assert-level' is evaluated at compile-time, not at
run-time. Therefore you cannot turn assertions on or off at run-time;
you have to set the `assert-level' appropriately before compiling a
piece of code. You can compile different pieces of code at different
`assert-level's (e.g., a trusted library at level 1 and newly-written
code at level 3).

`assert-level'       - a-addr         gforth       "assert-level"
   All assertions above this level are turned off.

   If an assertion fails, a message compatible with Emacs' compilation
mode is produced and the execution is aborted (currently with `ABORT"'.
If there is interest, we will introduce a special throw code. But if you
intend to `catch' a specific condition, using `throw' is probably more
appropriate than an assertion).

   Assertions (and `~~') will usually print the wrong file name if a
marker is executed in the same file after their occurance.  They will
print `*somewhere*' as file name if a marker is executed in the same
file before their occurance.

   Definitions in ANS Forth for these assertion words are provided in
`compat/assert.fs'.


File: gforth.info,  Node: Singlestep Debugger,  Prev: Assertions,  Up: Programming Tools

5.24.5 Singlestep Debugger
--------------------------

The singlestep debugger works only with the engine `gforth-itc'.

   When you create a new word there's often the need to check whether it
behaves correctly or not. You can do this by typing `dbg badword'. A
debug session might look like this:

     : badword 0 DO i . LOOP ;  ok
     2 dbg badword
     : badword
     Scanning code...

     Nesting debugger ready!

     400D4738  8049BC4 0              -> [ 2 ] 00002 00000
     400D4740  8049F68 DO             -> [ 0 ]
     400D4744  804A0C8 i              -> [ 1 ] 00000
     400D4748 400C5E60 .              -> 0 [ 0 ]
     400D474C  8049D0C LOOP           -> [ 0 ]
     400D4744  804A0C8 i              -> [ 1 ] 00001
     400D4748 400C5E60 .              -> 1 [ 0 ]
     400D474C  8049D0C LOOP           -> [ 0 ]
     400D4758  804B384 ;              ->  ok

   Each line displayed is one step. You always have to hit return to
execute the next word that is displayed. If you don't want to execute
the next word in a whole, you have to type `n' for `nest'. Here is an
overview what keys are available:

<RET>
     Next; Execute the next word.

n
     Nest; Single step through next word.

u
     Unnest; Stop debugging and execute rest of word. If we got to this
     word with nest, continue debugging with the calling word.

d
     Done; Stop debugging and execute rest.

s
     Stop; Abort immediately.


   Debugging large application with this mechanism is very difficult,
because you have to nest very deeply into the program before the
interesting part begins. This takes a lot of time.

   To do it more directly put a `BREAK:' command into your source code.
When program execution reaches `BREAK:' the single step debugger is
invoked and you have all the features described above.

   If you have more than one part to debug it is useful to know where
the program has stopped at the moment. You can do this by the `BREAK"
string"' command. This behaves like `BREAK:' except that string is
typed out when the "breakpoint" is reached.

`dbg'       "name" -         gforth       "dbg"

`break:'       -         gforth       "break:"

`break"'       'ccc"' -         gforth       "break""


File: gforth.info,  Node: C Interface,  Next: Assembler and Code Words,  Prev: Programming Tools,  Up: Words

5.25 C Interface
================

Note that the C interface is not yet complete; callbacks are missing,
as well as a way of declaring structs, unions, and their fields.

* Menu:

* Calling C Functions::
* Declaring C Functions::
* Calling C function pointers::
* Defining library interfaces::
* Declaring OS-level libraries::
* Callbacks::
* C interface internals::
* Low-Level C Interface Words::


File: gforth.info,  Node: Calling C Functions,  Next: Declaring C Functions,  Prev: C Interface,  Up: C Interface

5.25.1 Calling C functions
--------------------------

Once a C function is declared (see *note Declaring C Functions::), you
can call it as follows: You push the arguments on the stack(s), and
then call the word for the C function.  The arguments have to be pushed
in the same order as the arguments appear in the C documentation (i.e.,
the first argument is deepest on the stack).  Integer and pointer
arguments have to be pushed on the data stack, floating-point arguments
on the FP stack; these arguments are consumed by the called C function.

   On returning from the C function, the return value, if any, resides
on the appropriate stack: an integer return value is pushed on the data
stack, an FP return value on the FP stack, and a void return value
results in not pushing anything.  Note that most C functions have a
return value, even if that is often not used in C; in Forth, you have
to `drop' this return value explicitly if you do not use it.

   The C interface automatically converts between the C type and the
Forth type as necessary, on a best-effort basis (in some cases, there
may be some loss).

   As an example, consider the POSIX function `lseek()':

     off_t lseek(int fd, off_t offset, int whence);

   This function takes three integer arguments, and returns an integer
argument, so a Forth call for setting the current file offset to the
start of the file could look like this:

     fd @ 0 SEEK_SET lseek -1 = if
       ... \ error handling
     then

   You might be worried that an `off_t' does not fit into a cell, so
you could not pass larger offsets to lseek, and might get only a part
of the return values.  In that case, in your declaration of the
function (*note Declaring C Functions::) you should declare it to use
double-cells for the off_t argument and return value, and maybe give
the resulting Forth word a different name, like `dlseek'; the result
could be called like this:

     fd @ 0. SEEK_SET dlseek -1. d= if
       ... \ error handling
     then

   Passing and returning structs or unions is currently not supported by
our interface(1).

   Calling functions with a variable number of arguments (_variadic_
functions, e.g., `printf()') is only supported by having you declare
one function-calling word for each argument pattern, and calling the
appropriate word for the desired pattern.

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

   (1) If you know the calling convention of your C compiler, you
usually can call such functions in some way, but that way is usually
not portable between platforms, and sometimes not even between C
compilers.


File: gforth.info,  Node: Declaring C Functions,  Next: Calling C function pointers,  Prev: Calling C Functions,  Up: C Interface

5.25.2 Declaring C Functions
----------------------------

Before you can call `lseek' or `dlseek', you have to declare it.  The
declaration consists of two parts:

The C part
     is the C declaration of the function, or more typically and
     portably, a C-style `#include' of a file that contains the
     declaration of the C function.

The Forth part
     declares the Forth types of the parameters and the Forth word name
     corresponding to the C function.


   For the words `lseek' and `dlseek' mentioned earlier, the
declarations are:

     \c #define _FILE_OFFSET_BITS 64
     \c #include <sys/types.h>
     \c #include <unistd.h>
     c-function lseek lseek n n n -- n
     c-function dlseek lseek n d n -- d

   The C part of the declarations is prefixed by `\c', and the rest of
the line is ordinary C code.  You can use as many lines of C
declarations as you like, and they are visible for all further function
declarations.

   The Forth part declares each interface word with `c-function',
followed by the Forth name of the word, the C name of the called
function, and the stack effect of the word.  The stack effect contains
an arbitrary number of types of parameters, then `--', and then exactly
one type for the return value.  The possible types are:

`n'
     single-cell integer

`a'
     address (single-cell)

`d'
     double-cell integer

`r'
     floating-point value

`func'
     C function pointer

`void'
     no value (used as return type for void functions)


   To deal with variadic C functions, you can declare one Forth word for
every pattern you want to use, e.g.:

     \c #include <stdio.h>
     c-function printf-nr printf a n r -- n
     c-function printf-rn printf a r n -- n

   Note that with C functions declared as variadic (or if you don't
provide a prototype), the C interface has no C type to convert to, so
no automatic conversion happens, which may lead to portability problems
in some cases.  In such cases you can perform the conversion explicitly
on the C level, e.g., as follows:

     \c #define printfll(s,ll) printf(s,(long long)ll)
     c-function printfll printfll a n -- n

   Here, instead of calling `printf()' directly, we define a macro that
casts (converts) the Forth single-cell integer into a C `long long'
before calling `printf()'.

`\c'       "rest-of-line" -         gforth       "backslash-c"
   One line of C declarations for the C interface

`c-function'       "forth-name" "c-name" "{type}" "-" "type" -         gforth       "c-function"
   Define a Forth word forth-name.  Forth-name has the specified stack
effect and calls the C function `c-name'.

   In order to work, this C interface invokes GCC at run-time and uses
dynamic linking.  If these features are not available, there are other,
less convenient and less portable C interfaces in `lib.fs' and
`oldlib.fs'.  These interfaces are mostly undocumented and mostly
incompatible with each other and with the documented C interface; you
can find some examples for the `lib.fs' interface in `lib.fs'.


File: gforth.info,  Node: Calling C function pointers,  Next: Defining library interfaces,  Prev: Declaring C Functions,  Up: C Interface

5.25.3 Calling C function pointers from Forth
---------------------------------------------

If you come across a C function pointer (e.g., in some C-constructed
structure) and want to call it from your Forth program, you can also
use the features explained until now to achieve that, as follows:

   Let us assume that there is a C function pointer type `func1'
defined in some header file `func1.h', and you know that these
functions take one integer argument and return an integer result; and
you want to call functions through such pointers.  Just define

     \c #include <func1.h>
     \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
     c-function call-func1 call_func1 n func -- n

   and then you can call a function pointed to by, say `func1a' as
follows:

     -5 func1a call-func1 .

   In the C part, `call_func' is defined as a macro to avoid having to
declare the exact parameter and return types, so the C compiler knows
them from the declaration of `func1'.

   The Forth word `call-func1' is similar to `execute', except that it
takes a C `func1' pointer instead of a Forth execution token, and it is
specific to `func1' pointers.  For each type of function pointer you
want to call from Forth, you have to define a separate calling word.


File: gforth.info,  Node: Defining library interfaces,  Next: Declaring OS-level libraries,  Prev: Calling C function pointers,  Up: C Interface

5.25.4 Defining library interfaces
----------------------------------

You can give a name to a bunch of C function declarations (a library
interface), as follows:

     c-library lseek-lib
     \c #define _FILE_OFFSET_BITS 64
     ...
     end-c-library

   The effect of giving such a name to the interface is that the
generated files will contain that name, and when you use the interface
a second time, it will use the existing files instead of generating and
compiling them again, saving you time.  Note that even if you change
the declarations, the old (stale) files will be used, probably leading
to errors.  So, during development of the declarations we recommend not
using `c-library'.

   Note that the library name is not allocated in the dictionary and
therefore does not shadow dictionary names.  It is used in the file
system, so you have to use naming conventions appropriate for file
systems.  Also, you must not call a function you declare after
`c-library' before you perform `end-c-library'.

   A major benefit of these named library interfaces is that, once they
are generated, the tools used to generated them (in particular, the C
compiler and libtool) are no longer needed, so the interface can be
used even on machines that do not have the tools installed.

`c-library-name'       c-addr u -         gforth       "c-library-name"
   Start a C library interface with name c-addr u.

`c-library'       "name" -         gforth       "c-library"
   Parsing version of `c-library-name'

`end-c-library'       -         gforth       "end-c-library"
   Finish and (if necessary) build the latest C library interface.


File: gforth.info,  Node: Declaring OS-level libraries,  Next: Callbacks,  Prev: Defining library interfaces,  Up: C Interface

5.25.5 Declaring OS-level libraries
-----------------------------------

For calling some C functions, you need to link with a specific OS-level
library that contains that function.  E.g., the `sin' function requires
linking a special library by using the command line switch `-lm'.  In
our C iterface you do the equivalent thing by calling `add-lib' as
follows:

     clear-libs
     s" m" add-lib
     \c #include <math.h>
     c-function sin sin r -- r

   First, you clear any libraries that may have been declared earlier
(you don't need them for `sin'); then you add the `m' library (actually
`libm.so' or somesuch) to the currently declared libraries; you can add
as many as you need.  Finally you declare the function as shown above.
Typically you will use the same set of library declarations for many
function declarations; you need to write only one set for that, right
at the beginning.

   Note that you must not call `clear-libs' inside
`c-library...end-c-library'; however, `c-library' performs the function
of `clear-libs', so `clear-libs' is not necessary, and you usually want
to put `add-lib' calls inside `c-library...end-c-library'.

`clear-libs'       -         gforth       "clear-libs"
   Clear the list of libs

`add-lib'       c-addr u -         gforth       "add-lib"
   Add library libstring to the list of libraries, where string is
represented by c-addr u.


File: gforth.info,  Node: Callbacks,  Next: C interface internals,  Prev: Declaring OS-level libraries,  Up: C Interface

5.25.6 Callbacks
----------------

Callbacks are not yet supported by the documented C interface.  You can
use the undocumented `lib.fs' interface for callbacks.

   In some cases you have to pass a function pointer to a C function,
i.e., the library wants to call back to your application (and the
pointed-to function is called a callback function).  You can pass the
address of an existing C function (that you get with `lib-sym', *note
Low-Level C Interface Words::), but if there is no appropriate C
function, you probably want to define the function as a Forth word.


File: gforth.info,  Node: C interface internals,  Next: Low-Level C Interface Words,  Prev: Callbacks,  Up: C Interface

5.25.7 How the C interface works
--------------------------------

The documented C interface works by generating a C code out of the
declarations.

   In particular, for every Forth word declared with `c-function', it
generates a wrapper function in C that takes the Forth data from the
Forth stacks, and calls the target C function with these data as
arguments.  The C compiler then performs an implicit conversion between
the Forth type from the stack, and the C type for the parameter, which
is given by the C function prototype.  After the C function returns,
the return value is likewise implicitly converted to a Forth type and
written back on the stack.

   The `\c' lines are literally included in the C code (but without the
`\c'), and provide the necessary declarations so that the C compiler
knows the C types and has enough information to perform the conversion.

   These wrapper functions are eventually compiled and dynamically
linked into Gforth, and then they can be called.

   The libraries added with `add-lib' are used in the compile command
line to specify dependent libraries with `-lLIB', causing these
libraries to be dynamically linked when the wrapper function is linked.


File: gforth.info,  Node: Low-Level C Interface Words,  Prev: C interface internals,  Up: C Interface

5.25.8 Low-Level C Interface Words
----------------------------------

`open-lib'       c-addr1 u1 - u2        gforth       "open-lib"

`lib-sym'       c-addr1 u1 u2 - u3        gforth       "lib-sym"

`lib-error'       - c-addr u        gforth       "lib-error"
   Error message for last failed `open-lib' or `lib-sym'.

`call-c'       ... w - ...        gforth       "call-c"
   Call the C function pointed to by w. The C function has to access
the stack itself. The stack pointers are exported in the global
variables `gforth_SP' and `gforth_FP'.


File: gforth.info,  Node: Assembler and Code Words,  Next: Threading Words,  Prev: C Interface,  Up: Words

5.26 Assembler and Code Words
=============================

* Menu:

* Code and ;code::
* Common Assembler::            Assembler Syntax
* Common Disassembler::
* 386 Assembler::               Deviations and special cases
* Alpha Assembler::             Deviations and special cases
* MIPS assembler::              Deviations and special cases
* PowerPC assembler::           Deviations and special cases
* ARM Assembler::               Deviations and special cases
* Other assemblers::            How to write them


File: gforth.info,  Node: Code and ;code,  Next: Common Assembler,  Prev: Assembler and Code Words,  Up: Assembler and Code Words

5.26.1 `Code' and `;code'
-------------------------

Gforth provides some words for defining primitives (words written in
machine code), and for defining the machine-code equivalent of
`DOES>'-based defining words. However, the machine-independent nature
of Gforth poses a few problems: First of all, Gforth runs on several
architectures, so it can provide no standard assembler. What's worse is
that the register allocation not only depends on the processor, but
also on the `gcc' version and options used.

   The words that Gforth offers encapsulate some system dependences
(e.g., the header structure), so a system-independent assembler may be
used in Gforth. If you do not have an assembler, you can compile
machine code directly with `,' and `c,'(1).

`assembler'       -         tools-ext       "assembler"

`init-asm'       -         gforth       "init-asm"

`code'       "name" - colon-sys         tools-ext       "code"

`end-code'       colon-sys -         gforth       "end-code"

`;code'       compilation. colon-sys1 - colon-sys2         tools-ext       "semicolon-code"

`flush-icache'       c-addr u -        gforth       "flush-icache"
   Make sure that the instruction cache of the processor (if there is
one) does not contain stale data at c-addr and u bytes afterwards.
`END-CODE' performs a `flush-icache' automatically. Caveat:
`flush-icache' might not work on your installation; this is usually the
case if direct threading is not supported on your machine (take a look
at your `machine.h') and your machine has a separate instruction cache.
In such cases, `flush-icache' does nothing instead of flushing the
instruction cache.

   If `flush-icache' does not work correctly, `code' words etc. will
not work (reliably), either.

   The typical usage of these `code' words can be shown most easily by
analogy to the equivalent high-level defining words:

     : foo                              code foo
        <high-level Forth words>              <assembler>
     ;                                  end-code

     : bar                              : bar
        <high-level Forth words>           <high-level Forth words>
        CREATE                             CREATE
           <high-level Forth words>           <high-level Forth words>
        DOES>                              ;code
           <high-level Forth words>           <assembler>
     ;                                  end-code

   In the assembly code you will want to refer to the inner
interpreter's registers (e.g., the data stack pointer) and you may want
to use other registers for temporary storage. Unfortunately, the
register allocation is installation-dependent.

   In particular, `ip' (Forth instruction pointer) and `rp' (return
stack pointer) may be in different places in `gforth' and
`gforth-fast', or different installations.  This means that you cannot
write a `NEXT' routine that works reliably on both versions or
different installations; so for doing `NEXT', I recommend jumping to `'
noop >code-address', which contains nothing but a `NEXT'.

   For general accesses to the inner interpreter's registers, the
easiest solution is to use explicit register declarations (*note
Variables in Specified Registers: (gcc.info)Explicit Reg Vars.) for all
of the inner interpreter's registers: You have to compile Gforth with
`-DFORCE_REG' (configure option `--enable-force-reg') and the
appropriate declarations must be present in the `machine.h' file (see
`mips.h' for an example; you can find a full list of all declarable
register symbols with `grep register engine.c'). If you give explicit
registers to all variables that are declared at the beginning of
`engine()', you should be able to use the other caller-saved registers
for temporary storage. Alternatively, you can use the `gcc' option
`-ffixed-REG' (*note Options for Code Generation Conventions:
(gcc.info)Code Gen Options.) to reserve a register (however, this
restriction on register allocation may slow Gforth significantly).

   If this solution is not viable (e.g., because `gcc' does not allow
you to explicitly declare all the registers you need), you have to find
out by looking at the code where the inner interpreter's registers
reside and which registers can be used for temporary storage. You can
get an assembly listing of the engine's code with `make engine.s'.

   In any case, it is good practice to abstract your assembly code from
the actual register allocation. E.g., if the data stack pointer resides
in register `$17', create an alias for this register called `sp', and
use that in your assembly code.

   Another option for implementing normal and defining words efficiently
is to add the desired functionality to the source of Gforth. For normal
words you just have to edit `primitives' (*note Automatic
Generation::). Defining words (equivalent to `;CODE' words, for fast
defined words) may require changes in `engine.c', `kernel.fs',
`prims2x.fs', and possibly `cross.fs'.

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

   (1) This isn't portable, because these words emit stuff in data
space; it works because Gforth has unified code/data spaces. Assembler
isn't likely to be portable anyway.


File: gforth.info,  Node: Common Assembler,  Next: Common Disassembler,  Prev: Code and ;code,  Up: Assembler and Code Words

5.26.2 Common Assembler
-----------------------

The assemblers in Gforth generally use a postfix syntax, i.e., the
instruction name follows the operands.

   The operands are passed in the usual order (the same that is used in
the manual of the architecture).  Since they all are Forth words, they
have to be separated by spaces; you can also use Forth words to compute
the operands.

   The instruction names usually end with a `,'.  This makes it easier
to visually separate instructions if you put several of them on one
line; it also avoids shadowing other Forth words (e.g., `and').

   Registers are usually specified by number; e.g., (decimal) `11'
specifies registers R11 and F11 on the Alpha architecture (which one,
depends on the instruction).  The usual names are also available, e.g.,
`s2' for R11 on Alpha.

   Control flow is specified similar to normal Forth code (*note
Arbitrary control structures::), with `if,', `ahead,', `then,',
`begin,', `until,', `again,', `cs-roll', `cs-pick', `else,', `while,',
and `repeat,'.  The conditions are specified in a way specific to each
assembler.

   Note that the register assignments of the Gforth engine can change
between Gforth versions, or even between different compilations of the
same Gforth version (e.g., if you use a different GCC version).  So if
you want to refer to Gforth's registers (e.g., the stack pointer or
TOS), I recommend defining your own words for refering to these
registers, and using them later on; then you can easily adapt to a
changed register assignment.  The stability of the register assignment
is usually better if you build Gforth with `--enable-force-reg'.

   The most common use of these registers is to dispatch to the next
word (the `next' routine).  A portable way to do this is to jump to `'
noop >code-address' (of course, this is less efficient than integrating
the `next' code and scheduling it well).

   Another difference between Gforth version is that the top of stack is
kept in memory in `gforth' and, on most platforms, in a register in
`gforth-fast'.


File: gforth.info,  Node: Common Disassembler,  Next: 386 Assembler,  Prev: Common Assembler,  Up: Assembler and Code Words

5.26.3 Common Disassembler
--------------------------

You can disassemble a `code' word with `see' (*note Debugging::).  You
can disassemble a section of memory with

`discode'       addr u -         gforth       "discode"
   hook for the disassembler: disassemble code at addr of length u

   There are two kinds of disassembler for Gforth: The Forth
disassembler (available on some CPUs) and the gdb disassembler
(available on platforms with `gdb' and `mktemp').  If both are
available, the Forth disassembler is used by default.  If you prefer
the gdb disassembler, say

     ' disasm-gdb is discode

   If neither is available, `discode' performs `dump'.

   The Forth disassembler generally produces output that can be fed
into the assembler (i.e., same syntax, etc.).  It also includes
additional information in comments.  In particular, the address of the
instruction is given in a comment before the instruction.

   The gdb disassembler produces output in the same format as the gdb
`disassemble' command (*note Source and machine code: (gdb)Machine
Code.), in the default flavour (AT&T syntax for the 386 and AMD64
architectures).

   `See' may display more or less than the actual code of the word,
because the recognition of the end of the code is unreliable.  You can
use `discode' if it did not display enough.  It may display more, if
the code word is not immediately followed by a named word.  If you have
something else there, you can follow the word with `align latest ,' to
ensure that the end is recognized.


File: gforth.info,  Node: 386 Assembler,  Next: Alpha Assembler,  Prev: Common Disassembler,  Up: Assembler and Code Words

5.26.4 386 Assembler
--------------------

The 386 assembler included in Gforth was written by Bernd Paysan, it's
available under GPL, and originally part of bigFORTH.

   The 386 disassembler included in Gforth was written by Andrew McKewan
and is in the public domain.

   The disassembler displays code in an Intel-like prefix syntax.

   The assembler uses a postfix syntax with reversed parameters.

   The assembler includes all instruction of the Athlon, i.e. 486 core
instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
bit, you can switch to 16 bit with .86 and back to 32 bit with .386.

   There are several prefixes to switch between different operation
sizes, `.b' for byte accesses, `.w' for word accesses, `.d' for
double-word accesses. Addressing modes can be switched with `.wa' for
16 bit addresses, and `.da' for 32 bit addresses. You don't need a
prefix for byte register names (`AL' et al).

   For floating point operations, the prefixes are `.fs' (IEEE single),
`.fl' (IEEE double), `.fx' (extended), `.fw' (word), `.fd'
(double-word), and `.fq' (quad-word).

   The MMX opcodes don't have size prefixes, they are spelled out like
in the Intel assembler. Instead of move from and to memory, there are
PLDQ/PLDD and PSTQ/PSTD.

   The registers lack the 'e' prefix; even in 32 bit mode, eax is called
ax.  Immediate values are indicated by postfixing them with `#', e.g.,
`3 #'.  Here are some examples of addressing modes in various syntaxes:

     Gforth          Intel (NASM)   AT&T (gas)      Name
     .w ax           ax             %ax             register (16 bit)
     ax              eax            %eax            register (32 bit)
     3 #             offset 3       $3              immediate
     1000 #)         byte ptr 1000  1000            displacement
     bx )            [ebx]          (%ebx)          base
     100 di d)       100[edi]       100(%edi)       base+displacement
     20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
     di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
     4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
     12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement

   You can use `L)' and `LI)' instead of `D)' and `DI)' to enforce
32-bit displacement fields (useful for later patching).

   Some example of instructions are:

     ax bx mov             \ move ebx,eax
     3 # ax mov            \ mov eax,3
     100 di d) ax mov      \ mov eax,100[edi]
     4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
     .w ax bx mov          \ mov bx,ax

   The following forms are supported for binary instructions:

     <reg> <reg> <inst>
     <n> # <reg> <inst>
     <mem> <reg> <inst>
     <reg> <mem> <inst>
     <n> # <mem> <inst>

   The shift/rotate syntax is:

     <reg/mem> 1 # shl \ shortens to shift without immediate
     <reg/mem> 4 # shl
     <reg/mem> cl shl

   Precede string instructions (`movs' etc.) with `.b' to get the byte
version.

   The control structure words `IF' `UNTIL' etc. must be preceded by
one of these conditions: `vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps pc < >=
<= >'. (Note that most of these words shadow some Forth words when
`assembler' is in front of `forth' in the search path, e.g., in `code'
words).  Currently the control structure words use one stack item, so
you have to use `roll' instead of `cs-roll' to shuffle them (you can
also use `swap' etc.).

   Here is an example of a `code' word (assumes that the stack pointer
is in esi and the TOS is in ebx):

     code my+ ( n1 n2 -- n )
         4 si D) bx add
         4 # si add
         Next
     end-code


File: gforth.info,  Node: Alpha Assembler,  Next: MIPS assembler,  Prev: 386 Assembler,  Up: Assembler and Code Words

5.26.5 Alpha Assembler
----------------------

The Alpha assembler and disassembler were originally written by Bernd
Thallner.

   The register names `a0'-`a5' are not available to avoid shadowing
hex numbers.

   Immediate forms of arithmetic instructions are distinguished by a
`#' just before the `,', e.g., `and#,' (note: `lda,' does not count as
arithmetic instruction).

   You have to specify all operands to an instruction, even those that
other assemblers consider optional, e.g., the destination register for
`br,', or the destination register and hint for `jmp,'.

   You can specify conditions for `if,' by removing the first `b' and
the trailing `,' from a branch with a corresponding name; e.g.,

     11 fgt if, \ if F11>0e
       ...
     endif,

   `fbgt,' gives `fgt'.


File: gforth.info,  Node: MIPS assembler,  Next: PowerPC assembler,  Prev: Alpha Assembler,  Up: Assembler and Code Words

5.26.6 MIPS assembler
---------------------

The MIPS assembler was originally written by Christian Pirker.

   Currently the assembler and disassembler only cover the MIPS-I
architecture (R3000), and don't support FP instructions.

   The register names `$a0'-`$a3' are not available to avoid shadowing
hex numbers.

   Because there is no way to distinguish registers from immediate
values, you have to explicitly use the immediate forms of instructions,
i.e., `addiu,', not just `addu,' (`as' does this implicitly).

   If the architecture manual specifies several formats for the
instruction (e.g., for `jalr,'), you usually have to use the one with
more arguments (i.e., two for `jalr,').  When in doubt, see
`arch/mips/testasm.fs' for an example of correct use.

   Branches and jumps in the MIPS architecture have a delay slot.  You
have to fill it yourself (the simplest way is to use `nop,'), the
assembler does not do it for you (unlike `as').  Even `if,', `ahead,',
`until,', `again,', `while,', `else,' and `repeat,' need a delay slot.
Since `begin,' and `then,' just specify branch targets, they are not
affected.

   Note that you must not put branches, jumps, or `li,' into the delay
slot: `li,' may expand to several instructions, and control flow
instructions may not be put into the branch delay slot in any case.

   For branches the argument specifying the target is a relative
address; You have to add the address of the delay slot to get the
absolute address.

   The MIPS architecture also has load delay slots and restrictions on
using `mfhi,' and `mflo,'; you have to order the instructions yourself
to satisfy these restrictions, the assembler does not do it for you.

   You can specify the conditions for `if,' etc. by taking a
conditional branch and leaving away the `b' at the start and the `,' at
the end.  E.g.,

     4 5 eq if,
       ... \ do something if $4 equals $5
     then,


File: gforth.info,  Node: PowerPC assembler,  Next: ARM Assembler,  Prev: MIPS assembler,  Up: Assembler and Code Words

5.26.7 PowerPC assembler
------------------------

The PowerPC assembler and disassembler were contributed by Michal
Revucky.

   This assembler does not follow the convention of ending mnemonic
names with a ",", so some mnemonic names shadow regular Forth words (in
particular: `and or xor fabs'); so if you want to use the Forth words,
you have to make them visible first, e.g., with `also forth'.

   Registers are referred to by their number, e.g., `9' means the
integer register 9 or the FP register 9 (depending on the instruction).

   Because there is no way to distinguish registers from immediate
values, you have to explicitly use the immediate forms of instructions,
i.e., `addi,', not just `add,'.

   The assembler and disassembler usually support the most general form
of an instruction, but usually not the shorter forms (especially for
branches).


File: gforth.info,  Node: ARM Assembler,  Next: Other assemblers,  Prev: PowerPC assembler,  Up: Assembler and Code Words

5.26.8 ARM Assembler
--------------------

The ARM assembler included in Gforth was written from scratch by David
Kuehling.

   The assembler includes all instruction of ARM architecture version 4,
but does not (yet) have support for Thumb instructions.  It also lacks
support for any co-processors.

   The assembler uses a postfix syntax with the target operand specified
last.  For load/store instructions the last operand will be the
register(s) to be loaded from/stored to.

   Registers are specified by their names `r0' through `r15', with the
aliases `pc', `lr', `sp', `ip' and `fp' provided for convenience.  Note
that `ip' means intra procedure call scratch register (`r12') and does
not refer to the instruction pointer.

   Condition codes can be specified anywhere in the instruction, but
will be most readable if specified just in front of the mnemonic.  The
'S' flag is not a separate word, but encoded into instruction mnemonics,
ie. just use `adds,' instead of `add,' if you want the status register
to be updated.

   The following table lists the syntax of operands for general
instructions:

     Gforth          normal assembler      description
     123 #           #123                  immediate
     r12             r12                   register
     r12 4 #LSL      r12, LSL #4           shift left by immediate
     r12 r1 #LSL     r12, LSL r1           shift left by register
     r12 4 #LSR      r12, LSR #4           shift right by immediate
     r12 r1 #LSR     r12, LSR r1           shift right by register
     r12 4 #ASR      r12, ASR #4           arithmetic shift right
     r12 r1 #ASR     r12, ASR r1           ... by register
     r12 4 #ROR      r12, ROR #4           rotate right by immediate
     r12 r1 #ROR     r12, ROR r1           ... by register
     r12 RRX         r12, RRX              rotate right with extend by 1

   Memory operand syntax is listed in this table:

     Gforth            normal assembler      description
     r4 ]              [r4]                  register
     r4 4 #]           [r4, #+4]             register with immediate offset
     r4 -4 #]          [r4, #-4]             with negative offset
     r4 r1 +]          [r4, +r1]             register with register offset
     r4 r1 -]          [r4, -r1]             with negated register offset
     r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
     r4 4 #]!          [r4, #+4]!            immediate preincrement
     r4 r1 +]!         [r4, +r1]!            register preincrement
     r4 r1 -]!         [r4, +r1]!            register predecrement
     r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
     r4 -4 ]#          [r4], #-4             immediate postdecrement
     r4 r1 ]+          [r4], r1              register postincrement
     r4 r1 ]-          [r4], -r1             register postdecrement
     r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
     ' xyz >body [#]   xyz                   PC-relative addressing

   Register lists for load/store multiple instructions are started and
terminated by using the words `{' and `}' respectivly.  Between braces,
register names can be listed one by one, or register ranges can be
formed by using the postfix operator `r-r'.  The `^' flag is not
encoded in the register list operand, but instead directly encoded into
the instruction mnemonic, ie. use `^ldm,' and `^stm,'.

   Addressing modes for load/store multiple are not encoded as
instruction suffixes, but instead specified after the register that
supplies the address.  Use one of `DA', `IA', `DB', `IB', `DA!', `IA!',
`DB!' or `IB!'.

   The following table gives some examples:

     Gforth                           normal assembler
     { r0 r7 r8 }  r4 ia  stm,        stmia    {r0,r7,r8}, r4
     { r0 r7 r8 }  r4 db!  ldm,       ldmdb    {r0,r7,r8}, r4!
     { r0 r15 r-r }  sp ia!  ^ldm,    ldmfd    {r0-r15}^, sp!

   Conditions for control structure words are specified in front of a
word:

     r1 r2 cmp,    \ compare r1 and r2
     eq if,        \ equal?
        ...          \ code executed if r1 == r2
     then,

   Here is an example of a `code' word (assumes that the stack pointer
is in `r9', and that `r2' and `r3' can be clobbered):

     code my+ ( n1 n2 --  n3 )
        r9 IA!       { r2 r3 } ldm,  \ pop r2 = n2, r3 = n1
        r2   r3      r3        add,  \ r3 = n2+n1
        r9 -4 #]!    r3        str,  \ push r3
        next,
     end-code

   Look at `arch/arm/asm-example.fs' for more examples.


File: gforth.info,  Node: Other assemblers,  Prev: ARM Assembler,  Up: Assembler and Code Words

5.26.9 Other assemblers
-----------------------

If you want to contribute another assembler/disassembler, please contact
us (<anton@mips.complang.tuwien.ac.at>) to check if we have such an
assembler already.  If you are writing them from scratch, please use a
similar syntax style as the one we use (i.e., postfix, commas at the
end of the instruction names, *note Common Assembler::); make the output
of the disassembler be valid input for the assembler, and keep the style
similar to the style we used.

   Hints on implementation: The most important part is to have a good
test suite that contains all instructions.  Once you have that, the
rest is easy.  For actual coding you can take a look at
`arch/mips/disasm.fs' to get some ideas on how to use data for both the
assembler and disassembler, avoiding redundancy and some potential
bugs.  You can also look at that file (and *note Advanced does> usage
example::) to get ideas how to factor a disassembler.

   Start with the disassembler, because it's easier to reuse data from
the disassembler for the assembler than the other way round.

   For the assembler, take a look at `arch/alpha/asm.fs', which shows
how simple it can be.


File: gforth.info,  Node: Threading Words,  Next: Passing Commands to the OS,  Prev: Assembler and Code Words,  Up: Words

5.27 Threading Words
====================

These words provide access to code addresses and other threading stuff
in Gforth (and, possibly, other interpretive Forths). It more or less
abstracts away the differences between direct and indirect threading
(and, for direct threading, the machine dependences). However, at
present this wordset is still incomplete. It is also pretty low-level;
some day it will hopefully be made unnecessary by an internals wordset
that abstracts implementation details away completely.

   The terminology used here stems from indirect threaded Forth
systems; in such a system, the XT of a word is represented by the CFA
(code field address) of a word; the CFA points to a cell that contains
the code address.  The code address is the address of some machine code
that performs the run-time action of invoking the word (e.g., the
`dovar:' routine pushes the address of the body of the word (a
variable) on the stack ).

   In an indirect threaded Forth, you can get the code address of name
with `' name @'; in Gforth you can get it with `' name >code-address',
independent of the threading method.

`threading-method'       - n        gforth       "threading-method"
   0 if the engine is direct threaded. Note that this may change during
the lifetime of an image.

`>code-address'       xt - c_addr         gforth       ">code-address"
   c-addr is the code address of the word xt.

`code-address!'       c_addr xt -         gforth       "code-address!"
   Create a code field with code address c-addr at xt.

   For a word defined with `DOES>', the code address usually points to
a jump instruction (the "does-handler") that jumps to the dodoes
routine (in Gforth on some platforms, it can also point to the dodoes
routine itself).  What you are typically interested in, though, is
whether a word is a `DOES>'-defined word, and what Forth code it
executes; `>does-code' tells you that.

`>does-code'       xt - a_addr         gforth       ">does-code"
   If xt is the execution token of a child of a `DOES>' word, a-addr is
the start of the Forth code after the `DOES>'; Otherwise a-addr is 0.

   To create a `DOES>'-defined word with the following basic words, you
have to set up a `DOES>'-handler with `does-handler!'; `/does-handler'
aus behind you have to place your executable Forth code.  Finally you
have to create a word and modify its behaviour with `does-handler!'.

`does-code!'       a_addr xt -         gforth       "does-code!"
   Create a code field at xt for a child of a `DOES>'-word; a-addr is
the start of the Forth code after `DOES>'.

`does-handler!'       a_addr -         gforth       "does-handler!"
   Create a `DOES>'-handler at address a-addr. Normally, a-addr points
just behind a `DOES>'.

`/does-handler'       - n         gforth       "/does-handler"
   The size of a `DOES>'-handler (includes possible padding).

   The code addresses produced by various defining words are produced by
the following words:

`docol:'       - addr         gforth       "docol:"
   The code address of a colon definition.

`docon:'       - addr         gforth       "docon:"
   The code address of a `CONSTANT'.

`dovar:'       - addr         gforth       "dovar:"
   The code address of a `CREATE'd word.

`douser:'       - addr         gforth       "douser:"
   The code address of a `USER' variable.

`dodefer:'       - addr         gforth       "dodefer:"
   The code address of a `defer'ed word.

`dofield:'       - addr         gforth       "dofield:"
   The code address of a `field'.

   The following two words generalize `>code-address', `>does-code',
`code-address!', and `does-code!':

`>definer'       xt - definer         gforth       ">definer"
   DEFINER is a unique identifier for the way the XT was defined.
Words defined with different `does>'-codes have different definers.
The definer can be used for comparison and in `definer!'.

`definer!'       definer xt -         gforth       "definer!"
   The word represented by XT changes its behaviour to the behaviour
associated with DEFINER.


File: gforth.info,  Node: Passing Commands to the OS,  Next: Keeping track of Time,  Prev: Threading Words,  Up: Words

5.28 Passing Commands to the Operating System
=============================================

Gforth allows you to pass an arbitrary string to the host operating
system shell (if such a thing exists) for execution.

`sh'       "..." -         gforth       "sh"
   Parse a string and use `system' to pass it to the host operating
system for execution in a sub-shell.

`system'       c-addr u -         gforth       "system"
   Pass the string specified by C-ADDR U to the host operating system
for execution in a sub-shell.  The value of the environment variable
`GFORTHSYSTEMPREFIX' (or its default value) is prepended to the string
(mainly to support using `command.com' as shell in Windows instead of
whatever shell Cygwin uses by default; *note Environment variables::).

`$?'       - n         gforth       "dollar-question"
   `Value' - the exit status returned by the most recently executed
`system' command.

`getenv'       c-addr1 u1 - c-addr2 u2        gforth       "getenv"
   The string c-addr1 u1 specifies an environment variable. The string
c-addr2 u2 is the host operating system's expansion of that environment
variable. If the environment variable does not exist, c-addr2 u2
specifies a string 0 characters in length.


File: gforth.info,  Node: Keeping track of Time,  Next: Miscellaneous Words,  Prev: Passing Commands to the OS,  Up: Words

5.29 Keeping track of Time
==========================

`ms'       u -        facility-ext       "ms"
Wait at least n milli-second.

`time&date'       - nsec nmin nhour nday nmonth nyear        facility-ext       "time-and-date"
   Report the current time of day. Seconds, minutes and hours are
numbered from 0.  Months are numbered from 1.

`utime'       - dtime        gforth       "utime"
   Report the current time in microseconds since some epoch.

`cputime'       - duser dsystem        gforth       "cputime"
   duser and dsystem are the respective user- and system-level CPU
times used since the start of the Forth system (excluding child
processes), in microseconds (the granularity may be much larger,
however).  On platforms without the getrusage call, it reports elapsed
time (since some epoch) for duser and 0 for dsystem.


File: gforth.info,  Node: Miscellaneous Words,  Prev: Keeping track of Time,  Up: Words

5.30 Miscellaneous Words
========================

These section lists the ANS Forth words that are not documented
elsewhere in this manual. Ultimately, they all need proper homes.

`quit'       ?? - ??         core       "quit"
   Empty the return stack, make the user input device the input source,
enter interpret state and start the text interpreter.

   The following ANS Forth words are not currently supported by Gforth
(*note ANS conformance::):

   `EDITOR' `EMIT?' `FORGET'


File: gforth.info,  Node: Error messages,  Next: Tools,  Prev: Words,  Up: Top

6 Error messages
****************

A typical Gforth error message looks like this:

     in file included from \evaluated string/:-1
     in file included from ./yyy.fs:1
     ./xxx.fs:4: Invalid memory address
     >>>bar<<<
     Backtrace:
     $400E664C @
     $400E6664 foo

   The message identifying the error is `Invalid memory address'.  The
error happened when text-interpreting line 4 of the file `./xxx.fs'.
This line is given (it contains `bar'), and the word on the line where
the error happened, is pointed out (with `>>>' and `<<<').

   The file containing the error was included in line 1 of `./yyy.fs',
and `yyy.fs' was included from a non-file (in this case, by giving
`yyy.fs' as command-line parameter to Gforth).

   At the end of the error message you find a return stack dump that
can be interpreted as a backtrace (possibly empty). On top you find the
top of the return stack when the `throw' happened, and at the bottom you
find the return stack entry just above the return stack of the topmost
text interpreter.

   To the right of most return stack entries you see a guess for the
word that pushed that return stack entry as its return address. This
gives a backtrace. In our case we see that `bar' called `foo', and
`foo' called `@' (and `@' had an _Invalid memory address_ exception).

   Note that the backtrace is not perfect: We don't know which return
stack entries are return addresses (so we may get false positives); and
in some cases (e.g., for `abort"') we cannot determine from the return
address the word that pushed the return address, so for some return
addresses you see no names in the return stack dump.

   The return stack dump represents the return stack at the time when a
specific `throw' was executed.  In programs that make use of `catch',
it is not necessarily clear which `throw' should be used for the return
stack dump (e.g., consider one `throw' that indicates an error, which
is caught, and during recovery another error happens; which `throw'
should be used for the stack dump?).  Gforth presents the return stack
dump for the first `throw' after the last executed (not returned-to)
`catch' or `nothrow'; this works well in the usual case. To get the
right backtrace, you usually want to insert `nothrow' or `['] false
catch drop' after a `catch' if the error is not rethrown.

   `Gforth' is able to do a return stack dump for throws generated from
primitives (e.g., invalid memory address, stack empty etc.);
`gforth-fast' is only able to do a return stack dump from a directly
called `throw' (including `abort' etc.).  Given an exception caused by
a primitive in `gforth-fast', you will typically see no return stack
dump at all; however, if the exception is caught by `catch' (e.g., for
restoring some state), and then `throw'n again, the return stack dump
will be for the first such `throw'.


File: gforth.info,  Node: Tools,  Next: ANS conformance,  Prev: Error messages,  Up: Top

7 Tools
*******

* Menu:

* ANS Report::                  Report the words used, sorted by wordset.
* Stack depth changes::         Where does this stack item come from?

   See also *note Emacs and Gforth::.


File: gforth.info,  Node: ANS Report,  Next: Stack depth changes,  Prev: Tools,  Up: Tools

7.1 `ans-report.fs': Report the words used, sorted by wordset
=============================================================

If you want to label a Forth program as ANS Forth Program, you must
document which wordsets the program uses; for extension wordsets, it is
helpful to list the words the program requires from these wordsets
(because Forth systems are allowed to provide only some words of them).

   The `ans-report.fs' tool makes it easy for you to determine which
words from which wordset and which non-ANS words your application uses.
You simply have to include `ans-report.fs' before loading the program
you want to check. After loading your program, you can get the report
with `print-ans-report'. A typical use is to run this as batch job like
this:
     gforth ans-report.fs myprog.fs -e "print-ans-report bye"

   The output looks like this (for `compat/control.fs'):
     The program uses the following words
     from CORE :
     : POSTPONE THEN ; immediate ?dup IF 0=
     from BLOCK-EXT :
     \
     from FILE :
     (

7.1.1 Caveats
-------------

Note that `ans-report.fs' just checks which words are used, not whether
they are used in an ANS Forth conforming way!

   Some words are defined in several wordsets in the standard.
`ans-report.fs' reports them for only one of the wordsets, and not
necessarily the one you expect. It depends on usage which wordset is
the right one to specify. E.g., if you only use the compilation
semantics of `S"', it is a Core word; if you also use its
interpretation semantics, it is a File word.


File: gforth.info,  Node: Stack depth changes,  Prev: ANS Report,  Up: Tools

7.2 Stack depth changes during interpretation
=============================================

Sometimes you notice that, after loading a file, there are items left
on the stack.  The tool `depth-changes.fs' helps you find out quickly
where in the file these stack items are coming from.

   The simplest way of using `depth-changes.fs' is to include it before
the file(s) you want to check, e.g.:

     gforth depth-changes.fs my-file.fs

   This will compare the stack depths of the data and FP stack at every
empty line (in interpretation state) against these depths at the last
empty line (in interpretation state).  If the depths are not equal, the
position in the file and the stack contents are printed with `~~'
(*note Debugging::).  This indicates that a stack depth change has
occured in the paragraph of non-empty lines before the indicated line.
It is a good idea to leave an empty line at the end of the file, so the
last paragraph is checked, too.

   Checking only at empty lines usually works well, but sometimes you
have big blocks of non-empty lines (e.g., when building a big table),
and you want to know where in this block the stack depth changed.  You
can check all interpreted lines with

     gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs

   This checks the stack depth at every end-of-line.  So the depth
change occured in the line reported by the `~~' (not in the line
before).

   Note that, while this offers better accuracy in indicating where the
stack depth changes, it will often report many intentional stack depth
changes (e.g., when an interpreted computation stretches across several
lines).  You can suppress the checking of some lines by putting
backslashes at the end of these lines (not followed by white space),
and using

     gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs


File: gforth.info,  Node: ANS conformance,  Next: Standard vs Extensions,  Prev: Tools,  Up: Top

8 ANS conformance
*****************

To the best of our knowledge, Gforth is an

   ANS Forth System
   * providing the Core Extensions word set

   * providing the Block word set

   * providing the Block Extensions word set

   * providing the Double-Number word set

   * providing the Double-Number Extensions word set

   * providing the Exception word set

   * providing the Exception Extensions word set

   * providing the Facility word set

   * providing `EKEY', `EKEY>CHAR', `EKEY?', `MS' and `TIME&DATE' from
     the Facility Extensions word set

   * providing the File Access word set

   * providing the File Access Extensions word set

   * providing the Floating-Point word set

   * providing the Floating-Point Extensions word set

   * providing the Locals word set

   * providing the Locals Extensions word set

   * providing the Memory-Allocation word set

   * providing the Memory-Allocation Extensions word set (that one's
     easy)

   * providing the Programming-Tools word set

   * providing `;CODE', `AHEAD', `ASSEMBLER', `BYE', `CODE', `CS-PICK',
     `CS-ROLL', `STATE', `[ELSE]', `[IF]', `[THEN]' from the
     Programming-Tools Extensions word set

   * providing the Search-Order word set

   * providing the Search-Order Extensions word set

   * providing the String word set

   * providing the String Extensions word set (another easy one)

   Gforth has the following environmental restrictions:

   * While processing the OS command line, if an exception is not
     caught, Gforth exits with a non-zero exit code instyead of
     performing QUIT.

   * When an `throw' is performed after a `query', Gforth does not
     allways restore the input source specification in effect at the
     corresponding catch.


   In addition, ANS Forth systems are required to document certain
implementation choices. This chapter tries to meet these requirements.
In many cases it gives a way to ask the system for the information
instead of providing the information directly, in particular, if the
information depends on the processor, the operating system or the
installation options chosen, or if they are likely to change during the
maintenance of Gforth.

* Menu:

* The Core Words::
* The optional Block word set::
* The optional Double Number word set::
* The optional Exception word set::
* The optional Facility word set::
* The optional File-Access word set::
* The optional Floating-Point word set::
* The optional Locals word set::
* The optional Memory-Allocation word set::
* The optional Programming-Tools word set::
* The optional Search-Order word set::


File: gforth.info,  Node: The Core Words,  Next: The optional Block word set,  Prev: ANS conformance,  Up: ANS conformance

8.1 The Core Words
==================

* Menu:

* core-idef::                   Implementation Defined Options
* core-ambcond::                Ambiguous Conditions
* core-other::                  Other System Documentation


File: gforth.info,  Node: core-idef,  Next: core-ambcond,  Prev: The Core Words,  Up: The Core Words

8.1.1 Implementation Defined Options
------------------------------------

(Cell) aligned addresses:
     processor-dependent. Gforth's alignment words perform natural
     alignment (e.g., an address aligned for a datum of size 8 is
     divisible by 8). Unaligned accesses usually result in a `-23
     THROW'.

`EMIT' and non-graphic characters:
     The character is output using the C library function (actually,
     macro) `putc'.

character editing of `ACCEPT' and `EXPECT':
     This is modeled on the GNU readline library (*note Command Line
     Editing: (readline)Readline Interaction.) with Emacs-like key
     bindings. `Tab' deviates a little by producing a full word
     completion every time you type it (instead of producing the common
     prefix of all completions). *Note Command-line editing::.

character set:
     The character set of your computer and display device. Gforth is
     8-bit-clean (but some other component in your system may make
     trouble).

Character-aligned address requirements:
     installation-dependent. Currently a character is represented by a C
     `unsigned char'; in the future we might switch to `wchar_t'
     (Comments on that requested).

character-set extensions and matching of names:
     Any character except the ASCII NUL character can be used in a
     name. Matching is case-insensitive (except in `TABLE's). The
     matching is performed using the C library function `strncasecmp',
     whose function is probably influenced by the locale. E.g., the `C'
     locale does not know about accents and umlauts, so they are matched
     case-sensitively in that locale. For portability reasons it is
     best to write programs such that they work in the `C' locale. Then
     one can use libraries written by a Polish programmer (who might
     use words containing ISO Latin-2 encoded characters) and by a
     French programmer (ISO Latin-1) in the same program (of course,
     `WORDS' will produce funny results for some of the words (which
     ones, depends on the font you are using)). Also, the locale you
     prefer may not be available in other operating systems. Hopefully,
     Unicode will solve these problems one day.

conditions under which control characters match a space delimiter:
     If `word' is called with the space character as a delimiter, all
     white-space characters (as identified by the C macro `isspace()')
     are delimiters. `Parse', on the other hand, treats space like other
     delimiters.  `Parse-name', which is used by the outer interpreter
     (aka text interpreter) by default, treats all white-space
     characters as delimiters.

format of the control-flow stack:
     The data stack is used as control-flow stack. The size of a
     control-flow stack item in cells is given by the constant
     `cs-item-size'. At the time of this writing, an item consists of a
     (pointer to a) locals list (third), an address in the code
     (second), and a tag for identifying the item (TOS). The following
     tags are used: `defstart', `live-orig', `dead-orig', `dest',
     `do-dest', `scopestart'.

conversion of digits > 35
     The characters `[\]^_'' are the digits with the decimal value
     36-41. There is no way to input many of the larger digits.

display after input terminates in `ACCEPT' and `EXPECT':
     The cursor is moved to the end of the entered string. If the input
     is terminated using the `Return' key, a space is typed.

exception abort sequence of `ABORT"':
     The error string is stored into the variable `"error' and a `-2
     throw' is performed.

input line terminator:
     For interactive input, `C-m' (CR) and `C-j' (LF) terminate lines.
     One of these characters is typically produced when you type the
     `Enter' or `Return' key.

maximum size of a counted string:
     `s" /counted-string" environment? drop .'. Currently 255 characters
     on all platforms, but this may change.

maximum size of a parsed string:
     Given by the constant `/line'. Currently 255 characters.

maximum size of a definition name, in characters:
     MAXU/8

maximum string length for `ENVIRONMENT?', in characters:
     MAXU/8

method of selecting the user input device:
     The user input device is the standard input. There is currently no
     way to change it from within Gforth. However, the input can
     typically be redirected in the command line that starts Gforth.

method of selecting the user output device:
     `EMIT' and `TYPE' output to the file-id stored in the value
     `outfile-id' (`stdout' by default). Gforth uses unbuffered output
     when the user output device is a terminal, otherwise the output is
     buffered.

methods of dictionary compilation:
     What are we expected to document here?

number of bits in one address unit:
     `s" address-units-bits" environment? drop .'. 8 in all current
     platforms.

number representation and arithmetic:
     Processor-dependent. Binary two's complement on all current
     platforms.

ranges for integer types:
     Installation-dependent. Make environmental queries for `MAX-N',
     `MAX-U', `MAX-D' and `MAX-UD'. The lower bounds for unsigned (and
     positive) types is 0. The lower bound for signed types on two's
     complement and one's complement machines machines can be computed
     by adding 1 to the upper bound.

read-only data space regions:
     The whole Forth data space is writable.

size of buffer at `WORD':
     `PAD HERE - .'. 104 characters on 32-bit machines. The buffer is
     shared with the pictured numeric output string. If overwriting
     `PAD' is acceptable, it is as large as the remaining dictionary
     space, although only as much can be sensibly used as fits in a
     counted string.

size of one cell in address units:
     `1 cells .'.

size of one character in address units:
     `1 chars .'. 1 on all current platforms.

size of the keyboard terminal buffer:
     Varies. You can determine the size at a specific time using `lp@
     tib - .'. It is shared with the locals stack and TIBs of files that
     include the current file. You can change the amount of space for
     TIBs and locals stack at Gforth startup with the command line
     option `-l'.

size of the pictured numeric output buffer:
     `PAD HERE - .'. 104 characters on 32-bit machines. The buffer is
     shared with `WORD'.

size of the scratch area returned by `PAD':
     The remainder of dictionary space. `unused pad here - - .'.

system case-sensitivity characteristics:
     Dictionary searches are case-insensitive (except in `TABLE's).
     However, as explained above under character-set extensions, the
     matching for non-ASCII characters is determined by the locale you
     are using. In the default `C' locale all non-ASCII characters are
     matched case-sensitively.

system prompt:
     ` ok' in interpret state, ` compiled' in compile state.

division rounding:
     The ordinary division words `/ mod /mod */ */mod' perform floored
     division (with the default installation of Gforth).  You can check
     this with `s" floored" environment? drop .'.  If you write
     programs that need a specific division rounding, best use `fm/mod'
     or `sm/rem' for portability.

values of `STATE' when true:
     -1.

values returned after arithmetic overflow:
     On two's complement machines, arithmetic is performed modulo
     2**bits-per-cell for single arithmetic and 4**bits-per-cell for
     double arithmetic (with appropriate mapping for signed types).
     Division by zero typically results in a `-55 throw' (Floating-point
     unidentified fault) or `-10 throw' (divide by zero).  Integer
     division overflow can result in these throws, or in `-11 throw';
     in `gforth-fast' division overflow and divide by zero may also
     result in returning bogus results without producing an exception.

whether the current definition can be found after DOES>:
     No.



File: gforth.info,  Node: core-ambcond,  Next: core-other,  Prev: core-idef,  Up: The Core Words

8.1.2 Ambiguous conditions
--------------------------

a name is neither a word nor a number:
     `-13 throw' (Undefined word).

a definition name exceeds the maximum length allowed:
     `-19 throw' (Word name too long)

addressing a region not inside the various data spaces of the forth system:
     The stacks, code space and header space are accessible. Machine
     code space is typically readable. Accessing other addresses gives
     results dependent on the operating system. On decent systems: `-9
     throw' (Invalid memory address).

argument type incompatible with parameter:
     This is usually not caught. Some words perform checks, e.g., the
     control flow words, and issue a `ABORT"' or `-12 THROW' (Argument
     type mismatch).

attempting to obtain the execution token of a word with undefined execution semantics:
     `-14 throw' (Interpreting a compile-only word). In some cases, you
     get an execution token for `compile-only-error' (which performs a
     `-14 throw' when executed).

dividing by zero:
     On some platforms, this produces a `-10 throw' (Division by zero);
     on other systems, this typically results in a `-55 throw'
     (Floating-point unidentified fault).

insufficient data stack or return stack space:
     Depending on the operating system, the installation, and the
     invocation of Gforth, this is either checked by the memory
     management hardware, or it is not checked. If it is checked, you
     typically get a `-3 throw' (Stack overflow), `-5 throw' (Return
     stack overflow), or `-9 throw' (Invalid memory address) (depending
     on the platform and how you achieved the overflow) as soon as the
     overflow happens. If it is not checked, overflows typically result
     in mysterious illegal memory accesses, producing `-9 throw'
     (Invalid memory address) or `-23 throw' (Address alignment
     exception); they might also destroy the internal data structure of
     `ALLOCATE' and friends, resulting in various errors in these words.

insufficient space for loop control parameters:
     Like other return stack overflows.

insufficient space in the dictionary:
     If you try to allot (either directly with `allot', or indirectly
     with `,', `create' etc.) more memory than available in the
     dictionary, you get a `-8 throw' (Dictionary overflow). If you try
     to access memory beyond the end of the dictionary, the results are
     similar to stack overflows.

interpreting a word with undefined interpretation semantics:
     For some words, we have defined interpretation semantics. For the
     others: `-14 throw' (Interpreting a compile-only word).

modifying the contents of the input buffer or a string literal:
     These are located in writable memory and can be modified.

overflow of the pictured numeric output string:
     `-17 throw' (Pictured numeric ouput string overflow).

parsed string overflow:
     `PARSE' cannot overflow. `WORD' does not check for overflow.

producing a result out of range:
     On two's complement machines, arithmetic is performed modulo
     2**bits-per-cell for single arithmetic and 4**bits-per-cell for
     double arithmetic (with appropriate mapping for signed types).
     Division by zero typically results in a `-10 throw' (divide by
     zero) or `-55 throw' (floating point unidentified fault). Overflow
     on division may result in these errors or in `-11 throw' (result
     out of range).  `Gforth-fast' may silently produce bogus results on
     division overflow or division by zero.  `Convert' and `>number'
     currently overflow silently.

reading from an empty data or return stack:
     The data stack is checked by the outer (aka text) interpreter after
     every word executed. If it has underflowed, a `-4 throw' (Stack
     underflow) is performed. Apart from that, stacks may be checked or
     not, depending on operating system, installation, and invocation.
     If they are caught by a check, they typically result in `-4 throw'
     (Stack underflow), `-6 throw' (Return stack underflow) or `-9
     throw' (Invalid memory address), depending on the platform and
     which stack underflows and by how much. Note that even if the
     system uses checking (through the MMU), your program may have to
     underflow by a significant number of stack items to trigger the
     reaction (the reason for this is that the MMU, and therefore the
     checking, works with a page-size granularity).  If there is no
     checking, the symptoms resulting from an underflow are similar to
     those from an overflow.  Unbalanced return stack errors can result
     in a variety of symptoms, including `-9 throw' (Invalid memory
     address) and Illegal Instruction (typically `-260 throw').

unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
     `Create' and its descendants perform a `-16 throw' (Attempt to use
     zero-length string as a name). Words like `'' probably will not
     find what they search. Note that it is possible to create
     zero-length names with `nextname' (should it not?).

`>IN' greater than input buffer:
     The next invocation of a parsing word returns a string with length
     0.

`RECURSE' appears after `DOES>':
     Compiles a recursive call to the defining word, not to the defined
     word.

argument input source different than current input source for `RESTORE-INPUT':
     `-12 THROW'. Note that, once an input file is closed (e.g., because
     the end of the file was reached), its source-id may be reused.
     Therefore, restoring an input source specification referencing a
     closed file may lead to unpredictable results instead of a `-12
     THROW'.

     In the future, Gforth may be able to restore input source
     specifications from other than the current input source.

data space containing definitions gets de-allocated:
     Deallocation with `allot' is not checked. This typically results in
     memory access faults or execution of illegal instructions.

data space read/write with incorrect alignment:
     Processor-dependent. Typically results in a `-23 throw' (Address
     alignment exception). Under Linux-Intel on a 486 or later
     processor with alignment turned on, incorrect alignment results in
     a `-9 throw' (Invalid memory address). There are reportedly some
     processors with alignment restrictions that do not report
     violations.

data space pointer not properly aligned, `,', `C,':
     Like other alignment errors.

less than u+2 stack items (`PICK' and `ROLL'):
     Like other stack underflows.

loop control parameters not available:
     Not checked. The counted loop words simply assume that the top of
     return stack items are loop control parameters and behave
     accordingly.

most recent definition does not have a name (`IMMEDIATE'):
     `abort" last word was headerless"'.

name not defined by `VALUE' used by `TO':
     `-32 throw' (Invalid name argument) (unless name is a local or was
     defined by `CONSTANT'; in the latter case it just changes the
     constant).

name not found (`'', `POSTPONE', `[']', `[COMPILE]'):
     `-13 throw' (Undefined word)

parameters are not of the same type (`DO', `?DO', `WITHIN'):
     Gforth behaves as if they were of the same type. I.e., you can
     predict the behaviour by interpreting all parameters as, e.g.,
     signed.

`POSTPONE' or `[COMPILE]' applied to `TO':
     Assume `: X POSTPONE TO ; IMMEDIATE'. `X' performs the compilation
     semantics of `TO'.

String longer than a counted string returned by `WORD':
     Not checked. The string will be ok, but the count will, of course,
     contain only the least significant bits of the length.

u greater than or equal to the number of bits in a cell (`LSHIFT', `RSHIFT'):
     Processor-dependent. Typical behaviours are returning 0 and using
     only the low bits of the shift count.

word not defined via `CREATE':
     `>BODY' produces the PFA of the word no matter how it was defined.

     `DOES>' changes the execution semantics of the last defined word no
     matter how it was defined. E.g., `CONSTANT DOES>' is equivalent to
     `CREATE , DOES>'.

words improperly used outside `<#' and `#>':
     Not checked. As usual, you can expect memory faults.



File: gforth.info,  Node: core-other,  Prev: core-ambcond,  Up: The Core Words

8.1.3 Other system documentation
--------------------------------

nonstandard words using `PAD':
     None.

operator's terminal facilities available:
     After processing the OS's command line, Gforth goes into
     interactive mode, and you can give commands to Gforth
     interactively. The actual facilities available depend on how you
     invoke Gforth.

program data space available:
     `UNUSED .' gives the remaining dictionary space. The total
     dictionary space can be specified with the `-m' switch (*note
     Invoking Gforth::) when Gforth starts up.

return stack space available:
     You can compute the total return stack space in cells with `s"
     RETURN-STACK-CELLS" environment? drop .'. You can specify it at
     startup time with the `-r' switch (*note Invoking Gforth::).

stack space available:
     You can compute the total data stack space in cells with `s"
     STACK-CELLS" environment? drop .'. You can specify it at startup
     time with the `-d' switch (*note Invoking Gforth::).

system dictionary space required, in address units:
     Type `here forthstart - .' after startup. At the time of this
     writing, this gives 80080 (bytes) on a 32-bit system.


File: gforth.info,  Node: The optional Block word set,  Next: The optional Double Number word set,  Prev: The Core Words,  Up: ANS conformance

8.2 The optional Block word set
===============================

* Menu:

* block-idef::                  Implementation Defined Options
* block-ambcond::               Ambiguous Conditions
* block-other::                 Other System Documentation


File: gforth.info,  Node: block-idef,  Next: block-ambcond,  Prev: The optional Block word set,  Up: The optional Block word set

8.2.1 Implementation Defined Options
------------------------------------

the format for display by `LIST':
     First the screen number is displayed, then 16 lines of 64
     characters, each line preceded by the line number.

the length of a line affected by `\':
     64 characters.


File: gforth.info,  Node: block-ambcond,  Next: block-other,  Prev: block-idef,  Up: The optional Block word set

8.2.2 Ambiguous conditions
--------------------------

correct block read was not possible:
     Typically results in a `throw' of some OS-derived value (between
     -512 and -2048). If the blocks file was just not long enough,
     blanks are supplied for the missing portion.

I/O exception in block transfer:
     Typically results in a `throw' of some OS-derived value (between
     -512 and -2048).

invalid block number:
     `-35 throw' (Invalid block number)

a program directly alters the contents of `BLK':
     The input stream is switched to that other block, at the same
     position. If the storing to `BLK' happens when interpreting
     non-block input, the system will get quite confused when the block
     ends.

no current block buffer for `UPDATE':
     `UPDATE' has no effect.



File: gforth.info,  Node: block-other,  Prev: block-ambcond,  Up: The optional Block word set

8.2.3 Other system documentation
--------------------------------

any restrictions a multiprogramming system places on the use of buffer addresses:
     No restrictions (yet).

the number of blocks available for source and data:
     depends on your disk space.



File: gforth.info,  Node: The optional Double Number word set,  Next: The optional Exception word set,  Prev: The optional Block word set,  Up: ANS conformance

8.3 The optional Double Number word set
=======================================

* Menu:

* double-ambcond::              Ambiguous Conditions


File: gforth.info,  Node: double-ambcond,  Prev: The optional Double Number word set,  Up: The optional Double Number word set

8.3.1 Ambiguous conditions
--------------------------

d outside of range of n in `D>S':
     The least significant cell of d is produced.



File: gforth.info,  Node: The optional Exception word set,  Next: The optional Facility word set,  Prev: The optional Double Number word set,  Up: ANS conformance

8.4 The optional Exception word set
===================================

* Menu:

* exception-idef::              Implementation Defined Options


File: gforth.info,  Node: exception-idef,  Prev: The optional Exception word set,  Up: The optional Exception word set

8.4.1 Implementation Defined Options
------------------------------------

`THROW'-codes used in the system:
     The codes -256--511 are used for reporting signals. The mapping
     from OS signal numbers to throw codes is -256-signal. The codes
     -512--2047 are used for OS errors (for file and memory allocation
     operations). The mapping from OS error numbers to throw codes is
     -512-`errno'. One side effect of this mapping is that undefined OS
     errors produce a message with a strange number; e.g., `-1000
     THROW' results in `Unknown error 488' on my system.


File: gforth.info,  Node: The optional Facility word set,  Next: The optional File-Access word set,  Prev: The optional Exception word set,  Up: ANS conformance

8.5 The optional Facility word set
==================================

* Menu:

* facility-idef::               Implementation Defined Options
* facility-ambcond::            Ambiguous Conditions


File: gforth.info,  Node: facility-idef,  Next: facility-ambcond,  Prev: The optional Facility word set,  Up: The optional Facility word set

8.5.1 Implementation Defined Options
------------------------------------

encoding of keyboard events (`EKEY'):
     Keys corresponding to ASCII characters are encoded as ASCII
     characters.  Other keys are encoded with the constants `k-left',
     `k-right', `k-up', `k-down', `k-home', `k-end', `k1', `k2', `k3',
     `k4', `k5', `k6', `k7', `k8', `k9', `k10', `k11', `k12'.

duration of a system clock tick:
     System dependent. With respect to `MS', the time is specified in
     microseconds. How well the OS and the hardware implement this, is
     another question.

repeatability to be expected from the execution of `MS':
     System dependent. On Unix, a lot depends on load. If the system is
     lightly loaded, and the delay is short enough that Gforth does not
     get swapped out, the performance should be acceptable. Under
     MS-DOS and other single-tasking systems, it should be good.



File: gforth.info,  Node: facility-ambcond,  Prev: facility-idef,  Up: The optional Facility word set

8.5.2 Ambiguous conditions
--------------------------

`AT-XY' can't be performed on user output device:
     Largely terminal dependent. No range checks are done on the
     arguments.  No errors are reported. You may see some garbage
     appearing, you may see simply nothing happen.



File: gforth.info,  Node: The optional File-Access word set,  Next: The optional Floating-Point word set,  Prev: The optional Facility word set,  Up: ANS conformance

8.6 The optional File-Access word set
=====================================

* Menu:

* file-idef::                   Implementation Defined Options
* file-ambcond::                Ambiguous Conditions


File: gforth.info,  Node: file-idef,  Next: file-ambcond,  Prev: The optional File-Access word set,  Up: The optional File-Access word set

8.6.1 Implementation Defined Options
------------------------------------

file access methods used:
     `R/O', `R/W' and `BIN' work as you would expect. `W/O' translates
     into the C file opening mode `w' (or `wb'): The file is cleared,
     if it exists, and created, if it does not (with both `open-file'
     and `create-file').  Under Unix `create-file' creates a file with
     666 permissions modified by your umask.

file exceptions:
     The file words do not raise exceptions (except, perhaps, memory
     access faults when you pass illegal addresses or file-ids).

file line terminator:
     System-dependent. Gforth uses C's newline character as line
     terminator. What the actual character code(s) of this are is
     system-dependent.

file name format:
     System dependent. Gforth just uses the file name format of your OS.

information returned by `FILE-STATUS':
     `FILE-STATUS' returns the most powerful file access mode allowed
     for the file: Either `R/O', `W/O' or `R/W'. If the file cannot be
     accessed, `R/O BIN' is returned. `BIN' is applicable along with
     the returned mode.

input file state after an exception when including source:
     All files that are left via the exception are closed.

ior values and meaning:
     The iors returned by the file and memory allocation words are
     intended as throw codes. They typically are in the range
     -512--2047 of OS errors.  The mapping from OS error numbers to
     iors is -512-errno.

maximum depth of file input nesting:
     limited by the amount of return stack, locals/TIB stack, and the
     number of open files available. This should not give you troubles.

maximum size of input line:
     `/line'. Currently 255.

methods of mapping block ranges to files:
     By default, blocks are accessed in the file `blocks.fb' in the
     current working directory. The file can be switched with `USE'.

number of string buffers provided by `S"':
     1

size of string buffer used by `S"':
     `/line'. currently 255.



File: gforth.info,  Node: file-ambcond,  Prev: file-idef,  Up: The optional File-Access word set

8.6.2 Ambiguous conditions
--------------------------

attempting to position a file outside its boundaries:
     `REPOSITION-FILE' is performed as usual: Afterwards,
     `FILE-POSITION' returns the value given to `REPOSITION-FILE'.

attempting to read from file positions not yet written:
     End-of-file, i.e., zero characters are read and no error is
     reported.

file-id is invalid (`INCLUDE-FILE'):
     An appropriate exception may be thrown, but a memory fault or other
     problem is more probable.

I/O exception reading or closing file-id (`INCLUDE-FILE', `INCLUDED'):
     The ior produced by the operation, that discovered the problem, is
     thrown.

named file cannot be opened (`INCLUDED'):
     The ior produced by `open-file' is thrown.

requesting an unmapped block number:
     There are no unmapped legal block numbers. On some operating
     systems, writing a block with a large number may overflow the file
     system and have an error message as consequence.

using `source-id' when `blk' is non-zero:
     `source-id' performs its function. Typically it will give the id of
     the source which loaded the block. (Better ideas?)



File: gforth.info,  Node: The optional Floating-Point word set,  Next: The optional Locals word set,  Prev: The optional File-Access word set,  Up: ANS conformance

8.7 The optional Floating-Point word set
========================================

* Menu:

* floating-idef::               Implementation Defined Options
* floating-ambcond::            Ambiguous Conditions


File: gforth.info,  Node: floating-idef,  Next: floating-ambcond,  Prev: The optional Floating-Point word set,  Up: The optional Floating-Point word set

8.7.1 Implementation Defined Options
------------------------------------

format and range of floating point numbers:
     System-dependent; the `double' type of C.

results of `REPRESENT' when float is out of range:
     System dependent; `REPRESENT' is implemented using the C library
     function `ecvt()' and inherits its behaviour in this respect.

rounding or truncation of floating-point numbers:
     System dependent; the rounding behaviour is inherited from the
     hosting C compiler. IEEE-FP-based (i.e., most) systems by default
     round to nearest, and break ties by rounding to even (i.e., such
     that the last bit of the mantissa is 0).

size of floating-point stack:
     `s" FLOATING-STACK" environment? drop .' gives the total size of
     the floating-point stack (in floats). You can specify this on
     startup with the command-line option `-f' (*note Invoking
     Gforth::).

width of floating-point stack:
     `1 floats'.



File: gforth.info,  Node: floating-ambcond,  Prev: floating-idef,  Up: The optional Floating-Point word set

8.7.2 Ambiguous conditions
--------------------------

`df@' or `df!' used with an address that is not double-float  aligned:
     System-dependent. Typically results in a `-23 THROW' like other
     alignment violations.

`f@' or `f!' used with an address that is not float  aligned:
     System-dependent. Typically results in a `-23 THROW' like other
     alignment violations.

floating-point result out of range:
     System-dependent. Can result in a `-43 throw' (floating point
     overflow), `-54 throw' (floating point underflow), `-41 throw'
     (floating point inexact result), `-55 THROW' (Floating-point
     unidentified fault), or can produce a special value representing,
     e.g., Infinity.

`sf@' or `sf!' used with an address that is not single-float  aligned:
     System-dependent. Typically results in an alignment fault like
     other alignment violations.

`base' is not decimal (`REPRESENT', `F.', `FE.', `FS.'):
     The floating-point number is converted into decimal nonetheless.

Both arguments are equal to zero (`FATAN2'):
     System-dependent. `FATAN2' is implemented using the C library
     function `atan2()'.

Using `FTAN' on an argument r1 where cos(r1) is zero:
     System-dependent. Anyway, typically the cos of r1 will not be zero
     because of small errors and the tan will be a very large (or very
     small) but finite number.

d cannot be presented precisely as a float in `D>F':
     The result is rounded to the nearest float.

dividing by zero:
     Platform-dependent; can produce an Infinity, NaN, `-42 throw'
     (floating point divide by zero) or `-55 throw' (Floating-point
     unidentified fault).

exponent too big for conversion (`DF!', `DF@', `SF!', `SF@'):
     System dependent. On IEEE-FP based systems the number is converted
     into an infinity.

float<1 (`FACOSH'):
     Platform-dependent; on IEEE-FP systems typically produces a NaN.

float=<-1 (`FLNP1'):
     Platform-dependent; on IEEE-FP systems typically produces a NaN
     (or a negative infinity for float=-1).

float=<0 (`FLN', `FLOG'):
     Platform-dependent; on IEEE-FP systems typically produces a NaN
     (or a negative infinity for float=0).

float<0 (`FASINH', `FSQRT'):
     Platform-dependent; for `fsqrt' this typically gives a NaN, for
     `fasinh' some platforms produce a NaN, others a number (bug in the
     C library?).

|float|>1 (`FACOS', `FASIN', `FATANH'):
     Platform-dependent; IEEE-FP systems typically produce a NaN.

integer part of float cannot be represented by d in `F>D':
     Platform-dependent; typically, some double number is produced and
     no error is reported.

string larger than pictured numeric output area (`f.', `fe.', `fs.'):
     `Precision' characters of the numeric output area are used.  If
     `precision' is too high, these words will smash the data or code
     close to `here'.


File: gforth.info,  Node: The optional Locals word set,  Next: The optional Memory-Allocation word set,  Prev: The optional Floating-Point word set,  Up: ANS conformance

8.8 The optional Locals word set
================================

* Menu:

* locals-idef::                 Implementation Defined Options
* locals-ambcond::              Ambiguous Conditions


File: gforth.info,  Node: locals-idef,  Next: locals-ambcond,  Prev: The optional Locals word set,  Up: The optional Locals word set

8.8.1 Implementation Defined Options
------------------------------------

maximum number of locals in a definition:
     `s" #locals" environment? drop .'. Currently 15. This is a lower
     bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
     characters. The number of locals in a definition is bounded by the
     size of locals-buffer, which contains the names of the locals.



File: gforth.info,  Node: locals-ambcond,  Prev: locals-idef,  Up: The optional Locals word set

8.8.2 Ambiguous conditions
--------------------------

executing a named local in interpretation state:
     Locals have no interpretation semantics. If you try to perform the
     interpretation semantics, you will get a `-14 throw' somewhere
     (Interpreting a compile-only word). If you perform the compilation
     semantics, the locals access will be compiled (irrespective of
     state).

name not defined by `VALUE' or `(LOCAL)' (`TO'):
     `-32 throw' (Invalid name argument)



File: gforth.info,  Node: The optional Memory-Allocation word set,  Next: The optional Programming-Tools word set,  Prev: The optional Locals word set,  Up: ANS conformance

8.9 The optional Memory-Allocation word set
===========================================

* Menu:

* memory-idef::                 Implementation Defined Options


File: gforth.info,  Node: memory-idef,  Prev: The optional Memory-Allocation word set,  Up: The optional Memory-Allocation word set

8.9.1 Implementation Defined Options
------------------------------------

values and meaning of ior:
     The iors returned by the file and memory allocation words are
     intended as throw codes. They typically are in the range
     -512--2047 of OS errors.  The mapping from OS error numbers to
     iors is -512-errno.



File: gforth.info,  Node: The optional Programming-Tools word set,  Next: The optional Search-Order word set,  Prev: The optional Memory-Allocation word set,  Up: ANS conformance

8.10 The optional Programming-Tools word set
============================================

* Menu:

* programming-idef::            Implementation Defined Options
* programming-ambcond::         Ambiguous Conditions


File: gforth.info,  Node: programming-idef,  Next: programming-ambcond,  Prev: The optional Programming-Tools word set,  Up: The optional Programming-Tools word set

8.10.1 Implementation Defined Options
-------------------------------------

ending sequence for input following `;CODE' and `CODE':
     `END-CODE'

manner of processing input following `;CODE' and `CODE':
     The `ASSEMBLER' vocabulary is pushed on the search order stack, and
     the input is processed by the text interpreter, (starting) in
     interpret state.

search order capability for `EDITOR' and `ASSEMBLER':
     The ANS Forth search order word set.

source and format of display by `SEE':
     The source for `see' is the executable code used by the inner
     interpreter.  The current `see' tries to output Forth source code
     (and on some platforms, assembly code for primitives) as well as
     possible.



File: gforth.info,  Node: programming-ambcond,  Prev: programming-idef,  Up: The optional Programming-Tools word set

8.10.2 Ambiguous conditions
---------------------------

deleting the compilation word list (`FORGET'):
     Not implemented (yet).

fewer than u+1 items on the control-flow stack (`CS-PICK', `CS-ROLL'):
     This typically results in an `abort"' with a descriptive error
     message (may change into a `-22 throw' (Control structure mismatch)
     in the future). You may also get a memory access error. If you are
     unlucky, this ambiguous condition is not caught.

name can't be found (`FORGET'):
     Not implemented (yet).

name not defined via `CREATE':
     `;CODE' behaves like `DOES>' in this respect, i.e., it changes the
     execution semantics of the last defined word no matter how it was
     defined.

`POSTPONE' applied to `[IF]':
     After defining `: X POSTPONE [IF] ; IMMEDIATE'. `X' is equivalent
     to `[IF]'.

reaching the end of the input source before matching `[ELSE]' or `[THEN]':
     Continue in the same state of conditional compilation in the next
     outer input source. Currently there is no warning to the user
     about this.

removing a needed definition (`FORGET'):
     Not implemented (yet).



File: gforth.info,  Node: The optional Search-Order word set,  Prev: The optional Programming-Tools word set,  Up: ANS conformance

8.11 The optional Search-Order word set
=======================================

* Menu:

* search-idef::                 Implementation Defined Options
* search-ambcond::              Ambiguous Conditions


File: gforth.info,  Node: search-idef,  Next: search-ambcond,  Prev: The optional Search-Order word set,  Up: The optional Search-Order word set

8.11.1 Implementation Defined Options
-------------------------------------

maximum number of word lists in search order:
     `s" wordlists" environment? drop .'. Currently 16.

minimum search order:
     `root root'.



File: gforth.info,  Node: search-ambcond,  Prev: search-idef,  Up: The optional Search-Order word set

8.11.2 Ambiguous conditions
---------------------------

changing the compilation word list (during compilation):
     The word is entered into the word list that was the compilation
     word list at the start of the definition. Any changes to the name
     field (e.g., `immediate') or the code field (e.g., when executing
     `DOES>') are applied to the latest defined word (as reported by
     `latest' or `latestxt'), if possible, irrespective of the
     compilation word list.

search order empty (`previous'):
     `abort" Vocstack empty"'.

too many word lists in search order (`also'):
     `abort" Vocstack full"'.



File: gforth.info,  Node: Standard vs Extensions,  Next: Model,  Prev: ANS conformance,  Up: Top

9 Should I use Gforth extensions?
*********************************

As you read through the rest of this manual, you will see documentation
for Standard words, and documentation for some appealing Gforth
extensions. You might ask yourself the question: "Should I restrict
myself to the standard, or should I use the extensions?"

   The answer depends on the goals you have for the program you are
working on:

   * Is it just for yourself or do you want to share it with others?

   * If you want to share it, do the others all use Gforth?

   * If it is just for yourself, do you want to restrict yourself to
     Gforth?


   If restricting the program to Gforth is ok, then there is no reason
not to use extensions.  It is still a good idea to keep to the standard
where it is easy, in case you want to reuse these parts in another
program that you want to be portable.

   If you want to be able to port the program to other Forth systems,
there are the following points to consider:

   * Most Forth systems that are being maintained support the ANS Forth
     standard.  So if your program complies with the standard, it will
     be portable among many systems.

   * A number of the Gforth extensions can be implemented in ANS Forth
     using public-domain files provided in the `compat/' directory.
     These are mentioned in the text in passing.  There is no reason
     not to use these extensions, your program will still be ANS Forth
     compliant; just include the appropriate compat files with your
     program.

   * The tool `ans-report.fs' (*note ANS Report::) makes it easy to
     analyse your program and determine what non-Standard words it
     relies upon.  However, it does not check whether you use standard
     words in a non-standard way.

   * Some techniques are not standardized by ANS Forth, and are hard or
     impossible to implement in a standard way, but can be implemented
     in most Forth systems easily, and usually in similar ways (e.g.,
     accessing word headers).  Forth has a rich historical precedent
     for programmers taking advantage of implementation-dependent
     features of their tools (for example, relying on a knowledge of
     the dictionary structure). Sometimes these techniques are
     necessary to extract every last bit of performance from the
     hardware, sometimes they are just a programming shorthand.

   * Does using a Gforth extension save more work than the porting this
     part to other Forth systems (if any) will cost?

   * Is the additional functionality worth the reduction in portability
     and the additional porting problems?


   In order to perform these consideratios, you need to know what's
standard and what's not.  This manual generally states if something is
non-standard, but the authoritative source is the standard document
(http://www.taygeta.com/forth/dpans.html).  Appendix A of the Standard
(RATIONALE) provides a valuable insight into the thought processes of
the technical committee.

   Note also that portability between Forth systems is not the only
portability issue; there is also the issue of portability between
different platforms (processor/OS combinations).


File: gforth.info,  Node: Model,  Next: Integrating Gforth,  Prev: Standard vs Extensions,  Up: Top

10 Model
********

This chapter has yet to be written. It will contain information, on
which internal structures you can rely.


File: gforth.info,  Node: Integrating Gforth,  Next: Emacs and Gforth,  Prev: Model,  Up: Top

11 Integrating Gforth into C programs
*************************************

This is not yet implemented.

   Several people like to use Forth as scripting language for
applications that are otherwise written in C, C++, or some other
language.

   The Forth system ATLAST provides facilities for embedding it into
applications; unfortunately it has several disadvantages: most
importantly, it is not based on ANS Forth, and it is apparently dead
(i.e., not developed further and not supported). The facilities
provided by Gforth in this area are inspired by ATLAST's facilities, so
making the switch should not be hard.

   We also tried to design the interface such that it can easily be
implemented by other Forth systems, so that we may one day arrive at a
standardized interface. Such a standard interface would allow you to
replace the Forth system without having to rewrite C code.

   You embed the Gforth interpreter by linking with the library
`libgforth.a' (give the compiler the option `-lgforth').  All global
symbols in this library that belong to the interface, have the prefix
`forth_'. (Global symbols that are used internally have the prefix
`gforth_').

   You can include the declarations of Forth types and the functions and
variables of the interface with `#include <forth.h>'.

   Types.

   Variables.

   Data and FP Stack pointer. Area sizes.

   functions.

   forth_init(imagefile) forth_evaluate(string) exceptions?
forth_goto(address) (or forth_execute(xt)?)  forth_continue() (a
corountining mechanism)

   Adding primitives.

   No checking.

   Signals?

   Accessing the Stacks


File: gforth.info,  Node: Emacs and Gforth,  Next: Image Files,  Prev: Integrating Gforth,  Up: Top

12 Emacs and Gforth
*******************

Gforth comes with `gforth.el', an improved version of `forth.el' by
Goran Rydqvist (included in the TILE package). The improvements are:

   * A better handling of indentation.

   * A custom hilighting engine for Forth-code.

   * Comment paragraph filling (`M-q')

   * Commenting (`C-x \') and uncommenting (`C-u C-x \') of regions

   * Removal of debugging tracers (`C-x ~', *note Debugging::).

   * Support of the `info-lookup' feature for looking up the
     documentation of a word.

   * Support for reading and writing blocks files.

   To get a basic description of these features, enter Forth mode and
type `C-h m'.

   In addition, Gforth supports Emacs quite well: The source code
locations given in error messages, debugging output (from `~~') and
failed assertion messages are in the right format for Emacs'
compilation mode (*note Running Compilations under Emacs:
(emacs)Compilation.) so the source location corresponding to an error
or other message is only a few keystrokes away (`C-x `' for the next
error, `C-c C-c' for the error under the cursor).

   Moreover, for words documented in this manual, you can look up the
glossary entry quickly by using `C-h TAB' (`info-lookup-symbol', *note
Documentation Commands: (emacs)Documentation.).  This feature requires
Emacs 20.3 or later and does not work for words containing `:'.

* Menu:

* Installing gforth.el::        Making Emacs aware of Forth.
* Emacs Tags::                  Viewing the source of a word in Emacs.
* Hilighting::                  Making Forth code look prettier.
* Auto-Indentation::            Customizing auto-indentation.
* Blocks Files::                Reading and writing blocks files.


File: gforth.info,  Node: Installing gforth.el,  Next: Emacs Tags,  Prev: Emacs and Gforth,  Up: Emacs and Gforth

12.1 Installing gforth.el
=========================

To make the features from `gforth.el' available in Emacs, add the
following lines to your `.emacs' file:

     (autoload 'forth-mode "gforth.el")
     (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
     			    auto-mode-alist))
     (autoload 'forth-block-mode "gforth.el")
     (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
     			    auto-mode-alist))
     (add-hook 'forth-mode-hook (function (lambda ()
        ;; customize variables here:
        (setq forth-indent-level 4)
        (setq forth-minor-indent-level 2)
        (setq forth-hilight-level 3)
        ;;; ...
     )))


File: gforth.info,  Node: Emacs Tags,  Next: Hilighting,  Prev: Installing gforth.el,  Up: Emacs and Gforth

12.2 Emacs Tags
===============

If you `require' `etags.fs', a new `TAGS' file will be produced (*note
Tags Tables: (emacs)Tags.) that contains the definitions of all words
defined afterwards. You can then find the source for a word using
`M-.'. Note that Emacs can use several tags files at the same time
(e.g., one for the Gforth sources and one for your program, *note
Selecting a Tags Table: (emacs)Select Tags Table.). The TAGS file for
the preloaded words is `$(datadir)/gforth/$(VERSION)/TAGS' (e.g.,
`/usr/local/share/gforth/0.2.0/TAGS').  To get the best behaviour with
`etags.fs', you should avoid putting definitions both before and after
`require' etc., otherwise you will see the same file visited several
times by commands like `tags-search'.


File: gforth.info,  Node: Hilighting,  Next: Auto-Indentation,  Prev: Emacs Tags,  Up: Emacs and Gforth

12.3 Hilighting
===============

`gforth.el' comes with a custom source hilighting engine.  When you
open a file in `forth-mode', it will be completely parsed, assigning
faces to keywords, comments, strings etc.  While you edit the file,
modified regions get parsed and updated on-the-fly.

   Use the variable `forth-hilight-level' to change the level of
decoration from 0 (no hilighting at all) to 3 (the default).  Even if
you set the hilighting level to 0, the parser will still work in the
background, collecting information about whether regions of text are
"compiled" or "interpreted".  Those information are required for
auto-indentation to work properly.  Set `forth-disable-parser' to
non-nil if your computer is too slow to handle parsing.  This will have
an impact on the smartness of the auto-indentation engine, though.

   Sometimes Forth sources define new features that should be hilighted,
new control structures, defining-words etc.  You can use the variable
`forth-custom-words' to make `forth-mode' hilight additional words and
constructs.  See the docstring of `forth-words' for details (in Emacs,
type `C-h v forth-words').

   `forth-custom-words' is meant to be customized in your `.emacs'
file.  To customize hilighing in a file-specific manner, set
`forth-local-words' in a local-variables section at the end of your
source file (*note Variables: (emacs)Local Variables in Files.).

   Example:
     0 [IF]
        Local Variables:
        forth-local-words:
           ((("t:") definition-starter (font-lock-keyword-face . 1)
             "[ \t\n]" t name (font-lock-function-name-face . 3))
            ((";t") definition-ender (font-lock-keyword-face . 1)))
        End:
     [THEN]


File: gforth.info,  Node: Auto-Indentation,  Next: Blocks Files,  Prev: Hilighting,  Up: Emacs and Gforth

12.4 Auto-Indentation
=====================

`forth-mode' automatically tries to indent lines in a smart way,
whenever you type <TAB> or break a line with `C-m'.

   Simple customization can be achieved by setting `forth-indent-level'
and `forth-minor-indent-level' in your `.emacs' file. For historical
reasons `gforth.el' indents per default by multiples of 4 columns.  To
use the more traditional 3-column indentation, add the following lines
to your `.emacs':

     (add-hook 'forth-mode-hook (function (lambda ()
        ;; customize variables here:
        (setq forth-indent-level 3)
        (setq forth-minor-indent-level 1)
     )))

   If you want indentation to recognize non-default words, customize it
by setting `forth-custom-indent-words' in your `.emacs'.  See the
docstring of `forth-indent-words' for details (in Emacs, type `C-h v
forth-indent-words').

   To customize indentation in a file-specific manner, set
`forth-local-indent-words' in a local-variables section at the end of
your source file (*note Variables: (emacs)Local Variables in Files.).

   Example:
     0 [IF]
        Local Variables:
        forth-local-indent-words:
           ((("t:") (0 . 2) (0 . 2))
            ((";t") (-2 . 0) (0 . -2)))
        End:
     [THEN]


File: gforth.info,  Node: Blocks Files,  Prev: Auto-Indentation,  Up: Emacs and Gforth

12.5 Blocks Files
=================

`forth-mode' Autodetects blocks files by checking whether the length of
the first line exceeds 1023 characters.  It then tries to convert the
file into normal text format.  When you save the file, it will be
written to disk as normal stream-source file.

   If you want to write blocks files, use `forth-blocks-mode'.  It
inherits all the features from `forth-mode', plus some additions:

   * Files are written to disk in blocks file format.

   * Screen numbers are displayed in the mode line (enumerated beginning
     with the value of `forth-block-base')

   * Warnings are displayed when lines exceed 64 characters.

   * The beginning of the currently edited block is marked with an
     overlay-arrow.

   There are some restrictions you should be aware of.  When you open a
blocks file that contains tabulator or newline characters, these
characters will be translated into spaces when the file is written back
to disk.  If tabs or newlines are encountered during blocks file
reading, an error is output to the echo area. So have a look at the
`*Messages*' buffer, when Emacs' bell rings during reading.

   Please consult the docstring of `forth-blocks-mode' for more
information by typing `C-h v forth-blocks-mode').


File: gforth.info,  Node: Image Files,  Next: Engine,  Prev: Emacs and Gforth,  Up: Top

13 Image Files
**************

An image file is a file containing an image of the Forth dictionary,
i.e., compiled Forth code and data residing in the dictionary.  By
convention, we use the extension `.fi' for image files.

* Menu:

* Image Licensing Issues::      Distribution terms for images.
* Image File Background::       Why have image files?
* Non-Relocatable Image Files::  don't always work.
* Data-Relocatable Image Files::  are better.
* Fully Relocatable Image Files::  better yet.
* Stack and Dictionary Sizes::  Setting the default sizes for an image.
* Running Image Files::         `gforth -i file' or file.
* Modifying the Startup Sequence::  and turnkey applications.


File: gforth.info,  Node: Image Licensing Issues,  Next: Image File Background,  Prev: Image Files,  Up: Image Files

13.1 Image Licensing Issues
===========================

An image created with `gforthmi' (*note gforthmi::) or `savesystem'
(*note Non-Relocatable Image Files::) includes the original image;
i.e., according to copyright law it is a derived work of the original
image.

   Since Gforth is distributed under the GNU GPL, the newly created
image falls under the GNU GPL, too. In particular, this means that if
you distribute the image, you have to make all of the sources for the
image available, including those you wrote.  For details see *note GNU
General Public License (Section 3): Copying.

   If you create an image with `cross' (*note cross.fs::), the image
contains only code compiled from the sources you gave it; if none of
these sources is under the GPL, the terms discussed above do not apply
to the image. However, if your image needs an engine (a gforth binary)
that is under the GPL, you should make sure that you distribute both in
a way that is at most a _mere aggregation_, if you don't want the terms
of the GPL to apply to the image.


File: gforth.info,  Node: Image File Background,  Next: Non-Relocatable Image Files,  Prev: Image Licensing Issues,  Up: Image Files

13.2 Image File Background
==========================

Gforth consists not only of primitives (in the engine), but also of
definitions written in Forth. Since the Forth compiler itself belongs to
those definitions, it is not possible to start the system with the
engine and the Forth source alone. Therefore we provide the Forth code
as an image file in nearly executable form. When Gforth starts up, a C
routine loads the image file into memory, optionally relocates the
addresses, then sets up the memory (stacks etc.) according to
information in the image file, and (finally) starts executing Forth
code.

   The image file variants represent different compromises between the
goals of making it easy to generate image files and making them
portable.

   Win32Forth 3.4 and Mitch Bradley's `cforth' use relocation at
run-time. This avoids many of the complications discussed below (image
files are data relocatable without further ado), but costs performance
(one addition per memory access).

   By contrast, the Gforth loader performs relocation at image load
time. The loader also has to replace tokens that represent primitive
calls with the appropriate code-field addresses (or code addresses in
the case of direct threading).

   There are three kinds of image files, with different degrees of
relocatability: non-relocatable, data-relocatable, and fully relocatable
image files.

   These image file variants have several restrictions in common; they
are caused by the design of the image file loader:

   * There is only one segment; in particular, this means, that an
     image file cannot represent `ALLOCATE'd memory chunks (and
     pointers to them). The contents of the stacks are not represented,
     either.

   * The only kinds of relocation supported are: adding the same offset
     to all cells that represent data addresses; and replacing special
     tokens with code addresses or with pieces of machine code.

     If any complex computations involving addresses are performed, the
     results cannot be represented in the image file. Several
     applications that use such computations come to mind:
        - Hashing addresses (or data structures which contain
          addresses) for table lookup. If you use Gforth's `table's or
          `wordlist's for this purpose, you will have no problem,
          because the hash tables are recomputed automatically when the
          system is started. If you use your own hash tables, you will
          have to do something similar.

        - There's a cute implementation of doubly-linked lists that uses
          `XOR'ed addresses. You could represent such lists as
          singly-linked in the image file, and restore the
          doubly-linked representation on startup.(1)

        - The code addresses of run-time routines like `docol:' cannot
          be represented in the image file (because their tokens would
          be replaced by machine code in direct threaded
          implementations). As a workaround, compute these addresses at
          run-time with `>code-address' from the executions tokens of
          appropriate words (see the definitions of `docol:' and
          friends in `kernel/getdoers.fs').

        - On many architectures addresses are represented in machine
          code in some shifted or mangled form. You cannot put `CODE'
          words that contain absolute addresses in this form in a
          relocatable image file. Workarounds are representing the
          address in some relative form (e.g., relative to the CFA,
          which is present in some register), or loading the address
          from a place where it is stored in a non-mangled form.

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

   (1) In my opinion, though, you should think thrice before using a
doubly-linked list (whatever implementation).


File: gforth.info,  Node: Non-Relocatable Image Files,  Next: Data-Relocatable Image Files,  Prev: Image File Background,  Up: Image Files

13.3 Non-Relocatable Image Files
================================

These files are simple memory dumps of the dictionary. They are specific
to the executable (i.e., `gforth' file) they were created with. What's
worse, they are specific to the place on which the dictionary resided
when the image was created. Now, there is no guarantee that the
dictionary will reside at the same place the next time you start
Gforth, so there's no guarantee that a non-relocatable image will work
the next time (Gforth will complain instead of crashing, though).

   You can create a non-relocatable image file with

`savesystem'       "name" -         gforth       "savesystem"


File: gforth.info,  Node: Data-Relocatable Image Files,  Next: Fully Relocatable Image Files,  Prev: Non-Relocatable Image Files,  Up: Image Files

13.4 Data-Relocatable Image Files
=================================

These files contain relocatable data addresses, but fixed code addresses
(instead of tokens). They are specific to the executable (i.e.,
`gforth' file) they were created with. For direct threading on some
architectures (e.g., the i386), data-relocatable images do not work. You
get a data-relocatable image, if you use `gforthmi' with a Gforth
binary that is not doubly indirect threaded (*note Fully Relocatable
Image Files::).


File: gforth.info,  Node: Fully Relocatable Image Files,  Next: Stack and Dictionary Sizes,  Prev: Data-Relocatable Image Files,  Up: Image Files

13.5 Fully Relocatable Image Files
==================================

These image files have relocatable data addresses, and tokens for code
addresses. They can be used with different binaries (e.g., with and
without debugging) on the same machine, and even across machines with
the same data formats (byte order, cell size, floating point format).
However, they are usually specific to the version of Gforth they were
created with. The files `gforth.fi' and `kernl*.fi' are fully
relocatable.

   There are two ways to create a fully relocatable image file:

* Menu:

* gforthmi::                    The normal way
* cross.fs::                    The hard way


File: gforth.info,  Node: gforthmi,  Next: cross.fs,  Prev: Fully Relocatable Image Files,  Up: Fully Relocatable Image Files

13.5.1 `gforthmi'
-----------------

You will usually use `gforthmi'. If you want to create an image file
that contains everything you would load by invoking Gforth with `gforth
options', you simply say:
     gforthmi file options

   E.g., if you want to create an image `asm.fi' that has the file
`asm.fs' loaded in addition to the usual stuff, you could do it like
this:

     gforthmi asm.fi asm.fs

   `gforthmi' is implemented as a sh script and works like this: It
produces two non-relocatable images for different addresses and then
compares them. Its output reflects this: first you see the output (if
any) of the two Gforth invocations that produce the non-relocatable
image files, then you see the output of the comparing program: It
displays the offset used for data addresses and the offset used for
code addresses; moreover, for each cell that cannot be represented
correctly in the image files, it displays a line like this:

          78DC         BFFFFA50         BFFFFA40

   This means that at offset $78dc from `forthstart', one input image
contains $bffffa50, and the other contains $bffffa40. Since these cells
cannot be represented correctly in the output image, you should examine
these places in the dictionary and verify that these cells are dead
(i.e., not read before they are written).

   If you insert the option `--application' in front of the image file
name, you will get an image that uses the `--appl-image' option instead
of the `--image-file' option (*note Invoking Gforth::). When you
execute such an image on Unix (by typing the image name as command),
the Gforth engine will pass all options to the image instead of trying
to interpret them as engine options.

   If you type `gforthmi' with no arguments, it prints some usage
instructions.

   There are a few wrinkles: After processing the passed options, the
words `savesystem' and `bye' must be visible. A special doubly indirect
threaded version of the `gforth' executable is used for creating the
non-relocatable images; you can pass the exact filename of this
executable through the environment variable `GFORTHD' (default:
`gforth-ditc'); if you pass a version that is not doubly indirect
threaded, you will not get a fully relocatable image, but a
data-relocatable image (because there is no code address offset). The
normal `gforth' executable is used for creating the relocatable image;
you can pass the exact filename of this executable through the
environment variable `GFORTH'.


File: gforth.info,  Node: cross.fs,  Prev: gforthmi,  Up: Fully Relocatable Image Files

13.5.2 `cross.fs'
-----------------

You can also use `cross', a batch compiler that accepts a Forth-like
programming language (*note Cross Compiler::).

   `cross' allows you to create image files for machines with different
data sizes and data formats than the one used for generating the image
file. You can also use it to create an application image that does not
contain a Forth compiler. These features are bought with restrictions
and inconveniences in programming. E.g., addresses have to be stored in
memory with special words (`A!', `A,', etc.) in order to make the code
relocatable.


File: gforth.info,  Node: Stack and Dictionary Sizes,  Next: Running Image Files,  Prev: Fully Relocatable Image Files,  Up: Image Files

13.6 Stack and Dictionary Sizes
===============================

If you invoke Gforth with a command line flag for the size (*note
Invoking Gforth::), the size you specify is stored in the dictionary.
If you save the dictionary with `savesystem' or create an image with
`gforthmi', this size will become the default for the resulting image
file. E.g., the following will create a fully relocatable version of
`gforth.fi' with a 1MB dictionary:

     gforthmi gforth.fi -m 1M

   In other words, if you want to set the default size for the
dictionary and the stacks of an image, just invoke `gforthmi' with the
appropriate options when creating the image.

   Note: For cache-friendly behaviour (i.e., good performance), you
should make the sizes of the stacks modulo, say, 2K, somewhat
different. E.g., the default stack sizes are: data: 16k (mod 2k=0); fp:
15.5k (mod 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod
2k=0.5k).


File: gforth.info,  Node: Running Image Files,  Next: Modifying the Startup Sequence,  Prev: Stack and Dictionary Sizes,  Up: Image Files

13.7 Running Image Files
========================

You can invoke Gforth with an image file image instead of the default
`gforth.fi' with the `-i' flag (*note Invoking Gforth::):
     gforth -i image

   If your operating system supports starting scripts with a line of the
form `#! ...', you just have to type the image file name to start
Gforth with this image file (note that the file extension `.fi' is just
a convention). I.e., to run Gforth with the image file image, you can
just type image instead of `gforth -i image'.  This works because every
`.fi' file starts with a line of this format:

     #! /usr/local/bin/gforth-0.4.0 -i

   The file and pathname for the Gforth engine specified on this line is
the specific Gforth executable that it was built against; i.e. the value
of the environment variable `GFORTH' at the time that `gforthmi' was
executed.

   You can make use of the same shell capability to make a Forth source
file into an executable. For example, if you place this text in a file:

     #! /usr/local/bin/gforth

     ." Hello, world" CR
     bye

and then make the file executable (chmod +x in Unix), you can run it
directly from the command line. The sequence `#!' is used in two ways;
firstly, it is recognised as a "magic sequence" by the operating
system(1) secondly it is treated as a comment character by Gforth.
Because of the second usage, a space is required between `#!' and the
path to the executable (moreover, some Unixes require the sequence `#!
/').

   The disadvantage of this latter technique, compared with using
`gforthmi', is that it is slightly slower; the Forth source code is
compiled on-the-fly, each time the program is invoked.

`#!'       -         gforth       "hash-bang"
   An alias for `\'

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

   (1) The Unix kernel actually recognises two types of files:
executable files and files of data, where the data is processed by an
interpreter that is specified on the "interpreter line" - the first
line of the file, starting with the sequence #!. There may be a small
limit (e.g., 32) on the number of characters that may be specified on
the interpreter line.


File: gforth.info,  Node: Modifying the Startup Sequence,  Prev: Running Image Files,  Up: Image Files

13.8 Modifying the Startup Sequence
===================================

You can add your own initialization to the startup sequence of an image
through the deferred word `'cold'. `'cold' is invoked just before the
image-specific command line processing (i.e., loading files and
evaluating (`-e') strings) starts.

   A sequence for adding your initialization usually looks like this:

     :noname
         Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
         ... \ your stuff
     ; IS 'cold

   After `'cold', Gforth processes the image options (*note Invoking
Gforth::), and then it performs `bootmessage', another deferred word.
This normally prints Gforth's startup message and does nothing else.

   So, if you want to make a turnkey image (i.e., an image for an
application instead of an extended Forth system), you can do this in
two ways:

   * If you want to do your interpretation of the OS command-line
     arguments, hook into `'cold'.  In that case you probably also want
     to build the image with `gforthmi --application' (*note
     gforthmi::) to keep the engine from processing OS command line
     options.  You can then do your own command-line processing with
     `next-arg'

   * If you want to have the normal Gforth processing of OS command-line
     arguments, hook into `bootmessage'.


   In either case, you probably do not want the word that you execute in
these hooks to exit normally, but use `bye' or `throw'.  Otherwise the
Gforth startup process would continue and eventually present the Forth
command line to the user.

`'cold'       -         gforth       "tick-cold"
   Hook (deferred word) for things to do right before interpreting the
OS command-line arguments.  Normally does some initializations that you
also want to perform.

`bootmessage'       -         gforth       "bootmessage"
   Hook (deferred word) executed right after interpreting the OS
command-line arguments.  Normally prints the Gforth startup message.


File: gforth.info,  Node: Engine,  Next: Cross Compiler,  Prev: Image Files,  Up: Top

14 Engine
*********

Reading this chapter is not necessary for programming with Gforth. It
may be helpful for finding your way in the Gforth sources.

   The ideas in this section have also been published in the following
papers: Bernd Paysan, `ANS fig/GNU/??? Forth' (in German), Forth-Tagung
'93; M. Anton Ertl, `A Portable Forth Engine
(http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z)', EuroForth '93;
M. Anton Ertl, `Threaded code variations and optimizations (extended
version) (http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz)',
Forth-Tagung '02.

* Menu:

* Portability::
* Threading::
* Primitives::
* Performance::


File: gforth.info,  Node: Portability,  Next: Threading,  Prev: Engine,  Up: Engine

14.1 Portability
================

An important goal of the Gforth Project is availability across a wide
range of personal machines. fig-Forth, and, to a lesser extent, F83,
achieved this goal by manually coding the engine in assembly language
for several then-popular processors. This approach is very
labor-intensive and the results are short-lived due to progress in
computer architecture.

   Others have avoided this problem by coding in C, e.g., Mitch Bradley
(cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
particularly popular for UNIX-based Forths due to the large variety of
architectures of UNIX machines. Unfortunately an implementation in C
does not mix well with the goals of efficiency and with using
traditional techniques: Indirect or direct threading cannot be expressed
in C, and switch threading, the fastest technique available in C, is
significantly slower. Another problem with C is that it is very
cumbersome to express double integer arithmetic.

   Fortunately, there is a portable language that does not have these
limitations: GNU C, the version of C processed by the GNU C compiler
(*note Extensions to the C Language Family: (gcc.info)C Extensions.).
Its labels as values feature (*note Labels as Values: (gcc.info)Labels
as Values.) makes direct and indirect threading possible, its `long
long' type (*note Double-Word Integers: (gcc.info)Long Long.)
corresponds to Forth's double numbers on many systems.  GNU C is freely
available on all important (and many unimportant) UNIX machines, VMS,
80386s running MS-DOS, the Amiga, and the Atari ST, so a Forth written
in GNU C can run on all these machines.

   Writing in a portable language has the reputation of producing code
that is slower than assembly. For our Forth engine we repeatedly looked
at the code produced by the compiler and eliminated most
compiler-induced inefficiencies by appropriate changes in the source
code.

   However, register allocation cannot be portably influenced by the
programmer, leading to some inefficiencies on register-starved
machines. We use explicit register declarations (*note Variables in
Specified Registers: (gcc.info)Explicit Reg Vars.) to improve the speed
on some machines. They are turned on by using the configuration flag
`--enable-force-reg' (`gcc' switch `-DFORCE_REG'). Unfortunately, this
feature not only depends on the machine, but also on the compiler
version: On some machines some compiler versions produce incorrect code
when certain explicit register declarations are used. So by default
`-DFORCE_REG' is not used.


File: gforth.info,  Node: Threading,  Next: Primitives,  Prev: Portability,  Up: Engine

14.2 Threading
==============

GNU C's labels as values extension (available since `gcc-2.0', *note
Labels as Values: (gcc.info)Labels as Values.)  makes it possible to
take the address of label by writing `&&label'.  This address can then
be used in a statement like `goto *address'. I.e., `goto *&&x' is the
same as `goto x'.

   With this feature an indirect threaded `NEXT' looks like:
     cfa = *ip++;
     ca = *cfa;
     goto *ca;
   For those unfamiliar with the names: `ip' is the Forth instruction
pointer; the `cfa' (code-field address) corresponds to ANS Forths
execution token and points to the code field of the next word to be
executed; The `ca' (code address) fetched from there points to some
executable code, e.g., a primitive or the colon definition handler
`docol'.

   Direct threading is even simpler:
     ca = *ip++;
     goto *ca;

   Of course we have packaged the whole thing neatly in macros called
`NEXT' and `NEXT1' (the part of `NEXT' after fetching the cfa).

* Menu:

* Scheduling::
* Direct or Indirect Threaded?::
* Dynamic Superinstructions::
* DOES>::


File: gforth.info,  Node: Scheduling,  Next: Direct or Indirect Threaded?,  Prev: Threading,  Up: Threading

14.2.1 Scheduling
-----------------

There is a little complication: Pipelined and superscalar processors,
i.e., RISC and some modern CISC machines can process independent
instructions while waiting for the results of an instruction. The
compiler usually reorders (schedules) the instructions in a way that
achieves good usage of these delay slots. However, on our first tries
the compiler did not do well on scheduling primitives. E.g., for `+'
implemented as
     n=sp[0]+sp[1];
     sp++;
     sp[0]=n;
     NEXT;
   the `NEXT' comes strictly after the other code, i.e., there is
nearly no scheduling. After a little thought the problem becomes clear:
The compiler cannot know that `sp' and `ip' point to different
addresses (and the version of `gcc' we used would not know it even if
it was possible), so it could not move the load of the cfa above the
store to the TOS. Indeed the pointers could be the same, if code on or
very near the top of stack were executed. In the interest of speed we
chose to forbid this probably unused "feature" and helped the compiler
in scheduling: `NEXT' is divided into several parts: `NEXT_P0',
`NEXT_P1' and `NEXT_P2'). `+' now looks like:
     NEXT_P0;
     n=sp[0]+sp[1];
     sp++;
     NEXT_P1;
     sp[0]=n;
     NEXT_P2;

   There are various schemes that distribute the different operations of
NEXT between these parts in several ways; in general, different schemes
perform best on different processors.  We use a scheme for most
architectures that performs well for most processors of this
architecture; in the future we may switch to benchmarking and chosing
the scheme on installation time.


File: gforth.info,  Node: Direct or Indirect Threaded?,  Next: Dynamic Superinstructions,  Prev: Scheduling,  Up: Threading

14.2.2 Direct or Indirect Threaded?
-----------------------------------

Threaded forth code consists of references to primitives (simple machine
code routines like `+') and to non-primitives (e.g., colon definitions,
variables, constants); for a specific class of non-primitives (e.g.,
variables) there is one code routine (e.g., `dovar'), but each variable
needs a separate reference to its data.

   Traditionally Forth has been implemented as indirect threaded code,
because this allows to use only one cell to reference a non-primitive
(basically you point to the data, and find the code address there).

   However, threaded code in Gforth (since 0.6.0) uses two cells for
non-primitives, one for the code address, and one for the data address;
the data pointer is an immediate argument for the virtual machine
instruction represented by the code address.  We call this
_primitive-centric_ threaded code, because all code addresses point to
simple primitives.  E.g., for a variable, the code address is for `lit'
(also used for integer literals like `99').

   Primitive-centric threaded code allows us to use (faster) direct
threading as dispatch method, completely portably (direct threaded code
in Gforth before 0.6.0 required architecture-specific code).  It also
eliminates the performance problems related to I-cache consistency that
386 implementations have with direct threaded code, and allows
additional optimizations.

   There is a catch, however: the XT parameter of `execute' can occupy
only one cell, so how do we pass non-primitives with their code _and_
data addresses to them?  Our answer is to use indirect threaded
dispatch for `execute' and other words that use a single-cell xt.  So,
normal threaded code in colon definitions uses direct threading, and
`execute' and similar words, which dispatch to xts on the data stack,
use indirect threaded code.  We call this _hybrid direct/indirect_
threaded code.

   The engines `gforth' and `gforth-fast' use hybrid direct/indirect
threaded code.  This means that with these engines you cannot use `,'
to compile an xt.  Instead, you have to use `compile,'.

   If you want to compile xts with `,', use `gforth-itc'.  This engine
uses plain old indirect threaded code.  It still compiles in a
primitive-centric style, so you cannot use `compile,' instead of `,'
(e.g., for producing tables of xts with `] word1 word2 ... [').  If you
want to do that, you have to use `gforth-itc' and execute `' , is
compile,'.  Your program can check if it is running on a hybrid
direct/indirect threaded engine or a pure indirect threaded engine with
`threading-method' (*note Threading Words::).


File: gforth.info,  Node: Dynamic Superinstructions,  Next: DOES>,  Prev: Direct or Indirect Threaded?,  Up: Threading

14.2.3 Dynamic Superinstructions
--------------------------------

The engines `gforth' and `gforth-fast' use another optimization:
Dynamic superinstructions with replication.  As an example, consider
the following colon definition:

     : squared ( n1 -- n2 )
       dup * ;

   Gforth compiles this into the threaded code sequence

     dup
     *
     ;s

   In normal direct threaded code there is a code address occupying one
cell for each of these primitives.  Each code address points to a
machine code routine, and the interpreter jumps to this machine code in
order to execute the primitive.  The routines for these three
primitives are (in `gforth-fast' on the 386):

     Code dup
     ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC
     ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4
     ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4
     ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC
     end-code
     Code *
     ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4
     ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4
     ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4
     ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8
     ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC
     end-code
     Code ;s
     ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7
     ( $804A695 )  add     edi , # 4  \ $83 $C7 $4
     ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4
     ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC
     end-code

   With dynamic superinstructions and replication the compiler does not
just lay down the threaded code, but also copies the machine code
fragments, usually without the jump at the end.

     ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC
     ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4
     ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4
     ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4
     ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4
     ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4
     ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8
     ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7
     ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4
     ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4
     ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC

   Only when a threaded-code control-flow change happens (e.g., in
`;s'), the jump is appended.  This optimization eliminates many of
these jumps and makes the rest much more predictable.  The speedup
depends on the processor and the application; on the Athlon and Pentium
III this optimization typically produces a speedup by a factor of 2.

   The code addresses in the direct-threaded code are set to point to
the appropriate points in the copied machine code, in this example like
this:

     primitive  code address
        dup       $4057D27D
        *         $4057D286
        ;s        $4057D292

   Thus there can be threaded-code jumps to any place in this piece of
code.  This also simplifies decompilation quite a bit.

   You can disable this optimization with `--no-dynamic'.  You can use
the copying without eliminating the jumps (i.e., dynamic replication,
but without superinstructions) with `--no-super'; this gives the branch
prediction benefit alone; the effect on performance depends on the CPU;
on the Athlon and Pentium III the speedup is a little less than for
dynamic superinstructions with replication.

   One use of these options is if you want to patch the threaded code.
With superinstructions, many of the dispatch jumps are eliminated, so
patching often has no effect.  These options preserve all the dispatch
jumps.

   On some machines dynamic superinstructions are disabled by default,
because it is unsafe on these machines.  However, if you feel
adventurous, you can enable it with `--dynamic'.


File: gforth.info,  Node: DOES>,  Prev: Dynamic Superinstructions,  Up: Threading

14.2.4 DOES>
------------

One of the most complex parts of a Forth engine is `dodoes', i.e., the
chunk of code executed by every word defined by a `CREATE'...`DOES>'
pair; actually with primitive-centric code, this is only needed if the
xt of the word is `execute'd. The main problem here is: How to find the
Forth code to be executed, i.e. the code after the `DOES>' (the
`DOES>'-code)? There are two solutions:

   In fig-Forth the code field points directly to the `dodoes' and the
`DOES>'-code address is stored in the cell after the code address (i.e.
at `CFA cell+'). It may seem that this solution is illegal in the
Forth-79 and all later standards, because in fig-Forth this address
lies in the body (which is illegal in these standards). However, by
making the code field larger for all words this solution becomes legal
again.  We use this approach.  Leaving a cell unused in most words is a
bit wasteful, but on the machines we are targeting this is hardly a
problem.


File: gforth.info,  Node: Primitives,  Next: Performance,  Prev: Threading,  Up: Engine

14.3 Primitives
===============

* Menu:

* Automatic Generation::
* TOS Optimization::
* Produced code::


File: gforth.info,  Node: Automatic Generation,  Next: TOS Optimization,  Prev: Primitives,  Up: Primitives

14.3.1 Automatic Generation
---------------------------

Since the primitives are implemented in a portable language, there is no
longer any need to minimize the number of primitives. On the contrary,
having many primitives has an advantage: speed. In order to reduce the
number of errors in primitives and to make programming them easier, we
provide a tool, the primitive generator (`prims2x.fs' aka Vmgen, *note
Vmgen: (vmgen)Top.), that automatically generates most (and sometimes
all) of the C code for a primitive from the stack effect notation.  The
source for a primitive has the following form:

Forth-name  ( stack-effect )        category    [pronounc.]
[`""'glossary entry`""']
C code
[`:'
Forth code]

   The items in brackets are optional. The category and glossary fields
are there for generating the documentation, the Forth code is there for
manual implementations on machines without GNU C. E.g., the source for
the primitive `+' is:
     +    ( n1 n2 -- n )   core    plus
     n = n1+n2;

   This looks like a specification, but in fact `n = n1+n2' is C code.
Our primitive generation tool extracts a lot of information from the
stack effect notations(1): The number of items popped from and pushed
on the stack, their type, and by what name they are referred to in the
C code. It then generates a C code prelude and postlude for each
primitive. The final C code for `+' looks like this:

     I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
     /*  */                          /* documentation */
     NAME("+")                       /* debugging output (with -DDEBUG) */
     {
     DEF_CA                          /* definition of variable ca (indirect threading) */
     Cell n1;                        /* definitions of variables */
     Cell n2;
     Cell n;
     NEXT_P0;                        /* NEXT part 0 */
     n1 = (Cell) sp[1];              /* input */
     n2 = (Cell) TOS;
     sp += 1;                        /* stack adjustment */
     {
     n = n1+n2;                      /* C code taken from the source */
     }
     NEXT_P1;                        /* NEXT part 1 */
     TOS = (Cell)n;                  /* output */
     NEXT_P2;                        /* NEXT part 2 */
     }

   This looks long and inefficient, but the GNU C compiler optimizes
quite well and produces optimal code for `+' on, e.g., the R3000 and the
HP RISC machines: Defining the `n's does not produce any code, and
using them as intermediate storage also adds no cost.

   There are also other optimizations that are not illustrated by this
example: assignments between simple variables are usually for free (copy
propagation). If one of the stack items is not used by the primitive
(e.g.  in `drop'), the compiler eliminates the load from the stack
(dead code elimination). On the other hand, there are some things that
the compiler does not do, therefore they are performed by `prims2x.fs':
The compiler does not optimize code away that stores a stack item to
the place where it just came from (e.g., `over').

   While programming a primitive is usually easy, there are a few cases
where the programmer has to take the actions of the generator into
account, most notably `?dup', but also words that do not (always) fall
through to `NEXT'.

   For more information

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

   (1) We use a one-stack notation, even though we have separate data
and floating-point stacks; The separate notation can be generated
easily from the unified notation.


File: gforth.info,  Node: TOS Optimization,  Next: Produced code,  Prev: Automatic Generation,  Up: Primitives

14.3.2 TOS Optimization
-----------------------

An important optimization for stack machine emulators, e.g., Forth
engines, is keeping  one or more of the top stack items in registers.
If a word has the stack effect in1...inx `--' out1...outy, keeping the
top n items in registers
   * is better than keeping n-1 items, if x>=n and y>=n, due to fewer
     loads from and stores to the stack.

   * is slower than keeping n-1 items, if x<>y and x<n and y<n, due to
     additional moves between registers.

   In particular, keeping one item in a register is never a
disadvantage, if there are enough registers. Keeping two items in
registers is a disadvantage for frequent words like `?branch',
constants, variables, literals and `i'. Therefore our generator only
produces code that keeps zero or one items in registers. The generated
C code covers both cases; the selection between these alternatives is
made at C-compile time using the switch `-DUSE_TOS'. `TOS' in the C
code for `+' is just a simple variable name in the one-item case,
otherwise it is a macro that expands into `sp[0]'. Note that the GNU C
compiler tries to keep simple variables like `TOS' in registers, and it
usually succeeds, if there are enough registers.

   The primitive generator performs the TOS optimization for the
floating-point stack, too (`-DUSE_FTOS'). For floating-point operations
the benefit of this optimization is even larger: floating-point
operations take quite long on most processors, but can be performed in
parallel with other operations as long as their results are not used.
If the FP-TOS is kept in a register, this works. If it is kept on the
stack, i.e., in memory, the store into memory has to wait for the
result of the floating-point operation, lengthening the execution time
of the primitive considerably.

   The TOS optimization makes the automatic generation of primitives a
bit more complicated. Just replacing all occurrences of `sp[0]' by
`TOS' is not sufficient. There are some special cases to consider:
   * In the case of `dup ( w -- w w )' the generator must not eliminate
     the store to the original location of the item on the stack, if
     the TOS optimization is turned on.

   * Primitives with stack effects of the form `--' out1...outy must
     store the TOS to the stack at the start.  Likewise, primitives
     with the stack effect in1...inx `--' must load the TOS from the
     stack at the end. But for the null stack effect `--' no stores or
     loads should be generated.


File: gforth.info,  Node: Produced code,  Prev: TOS Optimization,  Up: Primitives

14.3.3 Produced code
--------------------

To see what assembly code is produced for the primitives on your machine
with your compiler and your flag settings, type `make engine.s' and
look at the resulting file `engine.s'.  Alternatively, you can also
disassemble the code of primitives with `see' on some architectures.


File: gforth.info,  Node: Performance,  Prev: Primitives,  Up: Engine

14.4 Performance
================

On RISCs the Gforth engine is very close to optimal; i.e., it is usually
impossible to write a significantly faster threaded-code engine.

   On register-starved machines like the 386 architecture processors
improvements are possible, because `gcc' does not utilize the registers
as well as a human, even with explicit register declarations; e.g.,
Bernd Beuster wrote a Forth system fragment in assembly language and
hand-tuned it for the 486; this system is 1.19 times faster on the
Sieve benchmark on a 486DX2/66 than Gforth compiled with `gcc-2.6.3'
with `-DFORCE_REG'.  The situation has improved with gcc-2.95 and
gforth-0.4.9; now the most important virtual machine registers fit in
real registers (and we can even afford to use the TOS optimization),
resulting in a speedup of 1.14 on the sieve over the earlier results.
And dynamic superinstructions provide another speedup (but only around
a factor 1.2 on the 486).

   The potential advantage of assembly language implementations is not
necessarily realized in complete Forth systems: We compared Gforth-0.5.9
(direct threaded, compiled with `gcc-2.95.1' and `-DFORCE_REG') with
Win32Forth 1.2093 (newer versions are reportedly much faster), LMI's NT
Forth (Beta, May 1994) and Eforth (with and without peephole (aka
pinhole) optimization of the threaded code); all these systems were
written in assembly language. We also compared Gforth with three
systems written in C: PFE-0.9.14 (compiled with `gcc-2.6.3' with the
default configuration for Linux: `-O2 -fomit-frame-pointer -DUSE_REGS
-DUNROLL_NEXT'), ThisForth Beta (compiled with `gcc-2.6.3 -O3
-fomit-frame-pointer'; ThisForth employs peephole optimization of the
threaded code) and TILE (compiled with `make opt'). We benchmarked
Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
O'Heskin kindly provided the results for Win32Forth and NT Forth on a
486DX2/66 with similar memory performance under Windows NT. Marcel
Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
added the peephole optimizer, ran the benchmarks and reported the
results.

   We used four small benchmarks: the ubiquitous Sieve; bubble-sorting
and matrix multiplication come from the Stanford integer benchmarks and
have been translated into Forth by Martin Fraeman; we used the versions
included in the TILE Forth package, but with bigger data set sizes; and
a recursive Fibonacci number computation for benchmarking calling
performance. The following table shows the time taken for the benchmarks
scaled by the time taken by Gforth (in other words, it shows the speedup
factor that Gforth achieved over the other systems).

     relative       Win32-    NT       eforth       This-
     time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
     sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
     bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
     matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
     fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54

   You may be quite surprised by the good performance of Gforth when
compared with systems written in assembly language. One important reason
for the disappointing performance of these other systems is probably
that they are not written optimally for the 486 (e.g., they use the
`lods' instruction). In addition, Win32Forth uses a comfortable, but
costly method for relocating the Forth image: like `cforth', it
computes the actual addresses at run time, resulting in two address
computations per `NEXT' (*note Image File Background::).

   The speedup of Gforth over PFE, ThisForth and TILE can be easily
explained with the self-imposed restriction of the latter systems to
standard C, which makes efficient threading impossible (however, the
measured implementation of PFE uses a GNU C extension: *note Defining
Global Register Variables: (gcc.info)Global Reg Vars.).  Moreover,
current C compilers have a hard time optimizing other aspects of the
ThisForth and the TILE source.

   The performance of Gforth on 386 architecture processors varies
widely with the version of `gcc' used. E.g., `gcc-2.5.8' failed to
allocate any of the virtual machine registers into real machine
registers by itself and would not work correctly with explicit register
declarations, giving a significantly slower engine (on a 486DX2/66
running the Sieve) than the one measured above.

   Note that there have been several releases of Win32Forth since the
release presented here, so the results presented above may have little
predictive value for the performance of Win32Forth today (results for
the current release on an i486DX2/66 are welcome).

   In `Translating Forth to Efficient C
(http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz)' by
M. Anton Ertl and Martin Maierhofer (presented at EuroForth '95), an
indirect threaded version of Gforth is compared with Win32Forth, NT
Forth, PFE, ThisForth, and several native code systems; that version of
Gforth is slower on a 486 than the version used here. You can find a
newer version of these measurements at
`http://www.complang.tuwien.ac.at/forth/performance.html'. You can find
numbers for Gforth on various machines in `Benchres'.


File: gforth.info,  Node: Cross Compiler,  Next: Bugs,  Prev: Engine,  Up: Top

15 Cross Compiler
*****************

The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
mostly written in Forth, including crucial parts like the outer
interpreter and compiler, it needs compiled Forth code to get started.
The cross compiler allows to create new images for other architectures,
even running under another Forth system.

* Menu:

* Using the Cross Compiler::
* How the Cross Compiler Works::

