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

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

   Authors: Bernd Paysan, Anton Ertl, Gerald Wodni Copyright © 1995,
1996, 1997, 1998, 2000, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014,2015,2016,2017,2018,2019,2020,2021,2022,2023 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: Locating uses of a word,  Next: Locating exception source,  Prev: Locating source code definitions,  Up: Programming Tools

6.26.2 Locating uses of a word
------------------------------

‘where’ ( "name" –  ) gforth-1.0 “where”
   Show all places where name is used (text-interpreted).  You can then
use ‘ww’, ‘nw’ or ‘bw’ to inspect specific occurences more closely.
Gforth’s ‘where’ does not show the definition of name; use ‘locate’ for
that.

‘ww’ ( u –  ) gforth-1.0 “ww”
   The next ‘l’ or ‘g’ shows the ‘where’ result with index u

‘nw’ ( –  ) gforth-1.0 “nw”
   The next ‘l’ or ‘g’ shows the next ‘where’ result; if the current one
is the last one, after ‘nw’ there is no current one.  If there is no
current one, after ‘nw’ the first one is the current one.

‘bw’ ( –  ) gforth-1.0 “bw”
   The next ‘l’ or ‘g’ shows the previous ‘where’ result; if the current
one is the first one, after ‘bw’ there is no current one.  If there is
no current one, after ‘bw’ the last one is the current one.

‘gg’ ( –  ) gforth-1.0 “gg”
   The next ‘ww’, ‘nw’, ‘bw’, ‘bb’, ‘nb’, ‘lb’ (but not ‘locate’,
‘edit’, ‘l’ or ‘g’) puts it result in the editor (like ‘g’).  Use ‘gg
gg’ to make this permanent rather than one-shot.

‘ll’ ( –  ) gforth-1.0 “ll”
   The next ‘ww’, ‘nw’, ‘bw’, ‘bb’, ‘nb’, ‘lb’ (but not ‘locate’,
‘edit’, ‘l’ or ‘g’) displays in the Forth system (like ‘l’).  Use ‘ll
ll’ to make this permanent rather than one-shot.

‘whereg’ ( "name" –  ) gforth-1.0 “whereg”
   Like ‘where’, but puts the output in the editor.  In Emacs, you can
then use the compilation-mode commands (*note (emacs)Compilation Mode::)
to inspect specific occurences more closely.

‘short-where’ ( –  ) gforth-1.0 “short-where”
   Set up ‘where’ to use a short file format (default).

‘expand-where’ ( –  ) gforth-1.0 “expand-where”
   Set up ‘where’ to use a fully expanded file format (to pass to e.g.
editors).

‘prepend-where’ ( –  ) gforth-1.0 “prepend-where”
   Set up ‘where’ to show the file on a separate line, followed by
‘where’ lines without file names (like SwiftForth).

   The data we have on word usage also allows us to show which words
have no uses:

‘unused-words’ ( –  ) gforth-1.0 “unused-words”
   list all words without usage


File: gforth.info,  Node: Locating exception source,  Next: Examining compiled code,  Prev: Locating uses of a word,  Up: Programming Tools

6.26.3 Locating exception source
--------------------------------

‘tt’ ( u –  ) gforth-1.0 “tt”

‘nt’ (  –  ) gforth-1.0 “nt”

‘bt’ ( –  ) gforth-1.0 “bt”


File: gforth.info,  Node: Examining compiled code,  Next: Examining data,  Prev: Locating exception source,  Up: Programming Tools

6.26.4 Examining compiled code
------------------------------

And finally, ‘see’ and friends show compiled code.  Some of the things
in the source code are not present in the compiled code (e.g.,
formatting and comments), but this is useful to see what threaded code
or native code is produced by macros and Gforth’s optimization features.

‘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-0.2 “xt-see”
   Decompile the definition represented by xt.

‘simple-see’ ( "name" –  ) gforth-0.6 “simple-see”
   Decompile the colon definition name, showing a line for each cell,
and try to guess a meaning for the cell, and show that.

‘xt-simple-see’ ( xt –  ) gforth-1.0 “xt-simple-see”
   Decompile the colon definition xt like ‘simple-see’

‘simple-see-range’ ( addr1 addr2 –  ) gforth-0.6 “simple-see-range”
   Decompile code in [addr1,addr2) like ‘simple-see’

‘see-code’ ( "name" –  ) gforth-0.7 “see-code”
   Like ‘simple-see’, but also shows the dynamic native code for the
inlined primitives.  For static superinstructions, it shows the
primitive sequence instead of the first primitive (the other primitives
of the superinstruction are shown, too).  For primitives for which
native code is generated, it shows the number of stack items in
registers at the beginning and at the end (e.g., ‘1->1’ means 1 stack
item is in a register at the start and at the end).  For each primitive
or superinstruction with native code, the inline arguments and component
primitives are shown first, then the native code.

‘xt-see-code’ ( xt –  ) gforth-1.0 “xt-see-code”
   Decompile the colon definition xt like ‘see-code’.

‘see-code-range’ ( addr1 addr2 –  ) gforth-0.7 “see-code-range”
   Decompile code in [addr1,addr2) like ‘see-code’.

   As an example, consider:

     : foo x f@ fsin drop over ;

   This is not particularly useful, but it demonstrates the various code
generation differences.  Compiling this on ‘gforth-fast’ on AMD64 and
then using ‘see-code foo’ outputs:

     $7FD0CEE8C510 lit f@     1->1
     $7FD0CEE8C518 x
     $7FD0CEE8C520 f@
     7FD0CEB51697:   movsd   [r12],xmm15
     7FD0CEB5169D:   mov     rax,$00[r13]
     7FD0CEB516A1:   sub     r12,$08
     7FD0CEB516A5:   add     r13,$18
     7FD0CEB516A9:   movsd   xmm15,[rax]
     7FD0CEB516AE:   mov     rcx,-$08[r13]
     7FD0CEB516B2:   jmp     ecx
     $7FD0CEE8C528 fsin
     $7FD0CEE8C530 drop    1->0
     7FD0CEB516B4:   add     r13,$08
     $7FD0CEE8C538 over    0->1
     7FD0CEB516B8:   mov     r8,$10[r15]
     7FD0CEB516BC:   add     r13,$08
     $7FD0CEE8C540 ;s    1->1
     7FD0CEB516C0:   mov     r10,[rbx]
     7FD0CEB516C3:   add     rbx,$08
     7FD0CEB516C7:   lea     r13,$08[r10]
     7FD0CEB516CB:   mov     rcx,-$08[r13]
     7FD0CEB516CF:   jmp     ecx

   First, you see a threaded-code cell for a static superinstruction
with the components ‘lit’ and ‘f@’, starting and ending with one data
stack item in a register (‘1->1’); this is followed by the cell for the
argument ‘x’ of ‘lit’, and the cell for the ‘f@’ component of the
superinstruction; the latter cell is not used, but is there for
Gforth-internal reasons.

   Next, the dynamically generated native code for the superinstruction
‘lit f@’ is shown; note that this native code is not mixed with the
threaded code in memory, as you can see by comparing the addresses.

   If you want to understand the native code shown here: the
threaded-code instruction pointer is in ‘r13’, the data stack pointer in
‘r15’; the first data stack register is ‘r8’ (i.e., the top of stack
resides there if there is one data stack item in a register); the return
stack pointer is in ‘rbx’, the FP stack pointer in ‘r12’, and the top of
the floating-pont stack in ‘xmm15’.  Note that the register assignments
vary between engines, so you may see a different register assignment for
this code.

   The dynamic native code for ‘lit f@’ ends with a dispatch jump (aka
NEXT), because the code for the next word ‘fsin’ in the definition is
not dynamically generated.

   Next, you see the threaded-code cell for ‘fsin’.  There is no
dynamically-generated native code for this word, and ‘see-code’ does not
show the static native code for it (you can look at it with ‘see fsin’).
Like all words with static native code in ‘gforth-fast’, the effect on
the data stack representation is ‘1->1’ (for ‘gforth’, ‘0->0’), but this
is not shown.

   Next, you see the threaded-code cell for ‘drop’; the native-code
variant used here starts with one data stack item in registers, and ends
with zero data stack items in registers (‘1->0’).  This is followed by
the native code for this variant of ‘drop’.  There is no NEXT here,
because the native code falls through to the code for the next word.

   Next, you see the threaded-code cell for ‘over’ followed by the
dynamically-generated native code in the ‘0->1’ variant.

   Finally, you see the threaded and native code for ‘;s’ (the primitive
compiled for ‘;’ in ‘foo’).  ‘;s’ performs control flow (it returns), so
it has to end with a NEXT.


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

6.26.5 Examining data and code
------------------------------

The following words inspect the stack non-destructively:

‘...’ ( x1 .. xn – x1 .. xn  ) gforth-1.0 “...”
   smart version of ‘.s’

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

‘f.s-precision’ ( – u  ) gforth-1.0 “f.s-precision”
   A ‘value’.  U is the field width for f.s output.  Other precision
details are derived from that value.

‘maxdepth-.s’ ( – addr  ) gforth-0.2 “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::).

   The following words work on the stack as a whole, either by
determining the depth or by clearing them:

‘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  ) floating “f-depth”
   +n is the current number of (floating-point) values on the
floating-point stack.

‘clearstack’ ( ... –  ) gforth-0.2 “clear-stack”
   remove and discard all/any items from the data stack.

‘fclearstack’ ( r0 .. rn –  ) gforth-1.0 “f-clearstack”
   clear the floating point stack

‘clearstacks’ ( ... –  ) gforth-0.7 “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.


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

6.26.6 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

6.26.7 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-0.2 “tilde-tilde”
   Prints the source code location of the ‘~~’ and the stack contents
with ‘.debugline’.

‘printdebugdata’ ( –  ) gforth-0.2 “print-debug-data”

‘.debugline’ ( nfile nline –  ) gforth-0.6 “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’.

‘debug-fid’ ( – file-id  ) gforth-1.0 “File-id”
   debugging words for output.  By default it is the process’s ‘stderr’.

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

‘once’ ( –  ) gforth-1.0 “once”
   do the following up to THEN only once

‘~~bt’ ( –  ) gforth-1.0 “~~bt”
   print stackdump and backtrace

‘~~1bt’ ( –  ) gforth-1.0 “~~1bt”
   print stackdump and backtrace once

‘???’ ( –  ) gforth-0.2 “???”
   Open a debuging shell

‘WTF??’ ( –  ) gforth-1.0 “WTF??”
   Open a debugging shell with backtrace and stack dump

‘!!FIXME!!’ ( –  ) gforth-1.0 “!!FIXME!!”
   word that should never be reached

‘replace-word’ ( xt1 xt2 –  ) gforth-1.0 “replace-word”
   make xt2 do xt1, both need to be colon definitions

‘~~Variable’ ( "name" –  ) gforth-1.0 “~~Variable”
   Variable that will be watched on every access

‘~~Value’ ( n "name" –  ) gforth-1.0 “~~Value”
   Value that will be watched on every access

‘+ltrace’ ( –  ) gforth-1.0 “+ltrace”
   turn on line tracing

‘-ltrace’ ( –  ) gforth-1.0 “-ltrace”
   turn off line tracing

‘#loc’ ( nline nchar "file" –  ) gforth-1.0 “#loc”
   set next word’s location to NLINE NCHAR in "FILE"


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

6.26.8 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-0.2 “assert-zero”
   Important assertions that should always be turned on.

‘assert1(’ ( –  ) gforth-0.2 “assert-one”
   Normal assertions; turned on by default.

‘assert2(’ ( –  ) gforth-0.2 “assert-two”
   Debugging assertions.

‘assert3(’ ( –  ) gforth-0.2 “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-0.2 “assert(”
   Equivalent to ‘assert1(’

‘)’ ( –  ) gforth-0.2 “close-paren”
   End an assertion.  Generic end, can be used for other similar
purposes

   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-0.2 “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 Standard Forth for these assertion words are provided
in ‘compat/assert.fs’.


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

6.26.9 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-0.2 “dbg”

‘break:’ ( –  ) gforth-0.4 “break:”

‘break"’ ( ’ccc"’ –  ) gforth-0.4 “break"”


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

6.26.10 Code Coverage and Execution Frequency
---------------------------------------------

If you run extensive tests on your code, you often want to figure out if
the tests exercise all parts of the code.  This is called (test)
coverage.  The file ‘coverage.fs’ contains tools for measuring the
coverage as well as execution frequency.

   Code coverage inserts counting code in every basic block
(straight-line code sequence) loaded after ‘coverage.fs’.  Each time
that code is run, it increments the counter for that basic block.  Later
you can show the source file with the counts inserted in these basic
blocks.

‘nocov[’ ( –  ) gforth-1.0 “nocov-bracket”
   (Immediate) Turn coverage off temporarily.

‘]nocov’ ( –  ) gforth-1.0 “bracket-nocov”
   (Immediate) End of temporary turned off coverage.

‘coverage?’ ( – f  ) gforth-internal “coverage?”
   Value: Coverage check on/off

‘cov+’ ( –  ) gforth-experimental “cov+”
   (Immediate) Place a coverage counter here.

‘?cov+’ ( flag – flag  ) gforth-experimental “?cov+”
   (Immediate) A coverage counter for a flag; in the coverage output you
see three numbers behind ‘?cov’: The first is the number of executions
where the top-of-stack was non-zero; the second is the number of
executions where it was zero; the third is the total number of
executions.

‘.coverage’ ( –  ) gforth-experimental “.coverage”
   Show code with execution frequencies.

‘annotate-cov’ ( –  ) gforth-experimental “annotate-cov”
   For every file with coverage information, produce a ‘.cov’ file that
has the execution frequencies inserted.  We recommend to use ‘bw-cover’
first (with the default ‘color-cover’ you get escape sequences in the
files).

‘cov%’ ( –  ) gforth-experimental “cov-percent”
   Print the percentage of basic blocks loaded after ‘coverage.fs’ that
are executed at least once.

‘.cover-raw’ ( –  ) gforth-experimental “.cover-raw”
   Print raw execution counts.

   By default, the counts are shown in colour (using ANSI escape
sequences), but you can use ‘bw-cover’ to show them in parenthesized
form without escape sequences.

‘bw-cover’ ( –  ) gforth-1.0 “bw-cover”
   Print execution counts in parentheses (source-code compatible).

‘color-cover’ ( –  ) gforth-1.0 “color-cover”
   Print execution counts in colours (default).

   You can save and reload the coverage counters in binary format, to
aggregate coverage counters across several test runs.

‘save-cov’ ( –  ) gforth-experimental “save-cov”
   Save coverage counters.

‘load-cov’ ( –  ) gforth-experimental “load-cov”
   Load coverage counters.


File: gforth.info,  Node: Multitasker,  Next: C Interface,  Prev: Programming Tools,  Up: Words

6.27 Multitasker
================

* Menu:

* Pthreads::                    Native Unix multitasker
* Cilk::                        Implements Cilk-like spawn+sync

Gforth offers two multitaskers: a traditional, cooperative round-robin
multitasker, and a pthread-based multitasker which allows to run several
threads concurrently on multi-core machines.  The pthread-based is now
marked as experimental feature, as standardization of Forth multitaskers
will likely change the names of words without changing their semantics.


File: gforth.info,  Node: Pthreads,  Next: Cilk,  Prev: Multitasker,  Up: Multitasker

6.27.1 Pthreads
---------------

Posix threads can run in parallel on several cores, or with pre-emptive
multitasking on onecore.  However, many of the following words are the
same as in the traditional cooperative multi-tasker.

   In addition, there are words that allow you to make sure that only
one task at a time changes something, and for communicating between
tasks.  These words are necessary for pre-emptive and multi-core
multi-tasking, because the cooperative-multitasking way of performing
transactions between calls to ‘pause’ does not work in this environment.

* Menu:

* Basic multi-tasking::
* Task-local data::
* Semaphores::
* Hardware operations for multi-tasking::
* Message queues::


File: gforth.info,  Node: Basic multi-tasking,  Next: Task-local data,  Prev: Pthreads,  Up: Pthreads

6.27.1.1 Basic multi-tasking
............................

Tasks can be created with ‘newtask’ or ‘newtask4’ with a given amount of
stack space (either all the same or each stack’s size specified).

‘newtask’ ( stacksize – task  ) gforth-experimental “newtask”
   creates task; each stack (data, return, FP, locals) has size
stacksize.

‘task’ ( ustacksize "name" –  ) gforth-experimental “task”
   creates a task name; each stack (data, return, FP, locals) has size
ustacksize.
name execution: ( – task )

‘newtask4’ ( u-data u-return u-fp u-locals – task  ) gforth-experimental “newtask4”
   creates task with data stack size u-data, return stack size u-return,
FP stack size u-fp and locals stack size u-locals.

   If you don’t know which stack sizes to use for the task, you can use
the size(s) of the main task:

‘stacksize’ ( – u  ) gforth-experimental “stacksize”
   u is the data stack size of the main task.

‘stacksize4’ ( – u-data u-return u-fp u-locals  ) gforth-experimental “stacksize4”
   Pushes the data, return, FP, and locals stack sizes of the main task.

   A task is created in an inactive state.  To let it run, you have to
activate it with one of the following words:

‘initiate’ ( xt task –  ) gforth-experimental “initiate”
   Let task execute xt.  Upon return from the xt, the task terminates
itself (VFX compatible).  Use one-time executable closures to pass
arbitrary paramenters to a task.

   The following legacy words provide the same functionality as
‘initiate’, but with a different interface: Like ‘does>’, they split
their containing colon definition in two parts: The part before
‘activate’/‘pass’ runs in the activating task, and returns to its caller
after activating the task.  The part behind ‘activate’/‘pass’ is
executed in the activated target task.

‘activate’ ( run-time nest-sys1 task –  ) gforth-experimental “activate”
   Let task perform the code behind ‘activate’, and return to the caller
of the word containing ‘activate’.  When the task returns from the code
behind ‘activate’, it terminates itself.

‘pass’ ( x1 .. xn n task –  ) gforth-experimental “pass”
   Pull x1 ..  xn n from the current task’s data stack and push x1 ..
xn on task’s data stack.  Let task perform the code behind ‘pass’, and
return to the caller of the word containing ‘pass’.  When the task
returns from the code behind ‘pass’, it terminates itself.

   You can also do creation and activation in one step:

‘execute-task’ ( xt – task  ) gforth-experimental “execute-task”
   Create a new task TASK with the same stack sizes as the main task.
Let task execute xt.  Upon return from the xt, the task terminates
itself.

   Apart from terminating by running to the end, a task can terminate
itself with ‘kill-task’.  Other tasks can terminate it with ‘kill’.

‘kill-task’ ( –  ) gforth-experimental “kill-task”
   Terminate the current task.

‘kill’ ( task –  ) gforth-experimental “kill”
   Terminate task.

   Tasks can also temporarily stop themselves or be stopped:

‘halt’ ( task –  ) gforth-experimental “halt”
   Stop a task

‘stop’ ( –  ) gforth-experimental “stop”
   stops the current task, and waits for events (which may restart it)

‘stop-ns’ ( timeout –  ) gforth-experimental “stop-ns”
   Stop with timeout (in nanoseconds), better replacement for ms

   A task restarts when the timeout is over or when another task wakes
it with:

‘restart’ ( task –  ) gforth-experimental “restart”
   Wake a task

   There is also:

‘pause’ ( –  ) gforth-experimental “pause”
   voluntarily switch to the next waiting task (‘pause’ is the
traditional cooperative task switcher; in the pthread multitasker, you
don’t need ‘pause’ for cooperation, but you still can use it e.g.  when
you have to resort to polling for some reason).  This also checks for
events in the queue.


File: gforth.info,  Node: Task-local data,  Next: Semaphores,  Prev: Basic multi-tasking,  Up: Pthreads

6.27.1.2 Task-local data
........................

In Forth every task has essentially the same task-local data, called
“user” area (early Forth systems were multi-user systems and there often
was one user per task).  The task result of, e.g.  ‘newtask’ is the
start address of its user area.  Each task gets the user data defined by
the system (e.g., ‘base’).  You can define additional user data with:

‘User’ ( "name" –  ) gforth-0.2 “User”
   Name is a user variable (1 cell).
Name execution: ( – addr )
Addr is the address of the user variable in the current task.

‘AUser’ ( "name" –  ) gforth-0.2 “AUser”
   Name is a user variable containing an address (this only makes a
difference in the cross-compiler).

‘uallot’ ( n1 – n2  ) gforth-0.3 “uallot”
   Reserve n1 bytes of user data.  n2 is the offset of the start of the
reserved area within the user area.

‘UValue’ ( "name" –  ) gforth-1.0 “UValue”
   Name is a user value.
Name execution: ( – x )

‘UDefer’ ( "name" –  ) gforth-1.0 “UDefer”
   Name is a task-local deferred word.
Name execution: ( ...  – ...  )

   There are also the following words for dealing with user data.

‘up@’ ( – a-addr ) new “up-fetch”
   Addr is the start of the user area of the current task (addr also
serves as the task identifier of the current task).

‘user'’ ( "name" – u  ) gforth-experimental “user”’
   U is the offset of the user variable name in the user area of each
task.

‘'s’ ( addr1 task – addr2  ) gforth-experimental “’s”
   With addr1 being an address in the user data of the current task,
addr2 is the corresponding address in task’s user data.


File: gforth.info,  Node: Semaphores,  Next: Hardware operations for multi-tasking,  Prev: Task-local data,  Up: Pthreads

6.27.1.3 Semaphores
...................

A cooperative multitasker can ensure that there is no other task
interacting between two invocations of ‘pause’.  Pthreads however are
really concurrent tasks (at least on a multi-core CPU), and therefore,
several techniques to avoid conflicts when accessing the same resources.

   Semaphores can only be aquired by one thread, all other threads have
to wait until the semapohre is released.

‘semaphore’ ( "name" –  ) gforth-experimental “semaphore”
   create a named semaphore name
name execution: ( – semaphore )

‘lock’ ( semaphore –  ) gforth-experimental “lock”
   lock the semaphore

‘unlock’ ( semaphore –  ) gforth-experimental “unlock”
   unlock the semaphore

   The other approach to prevent concurrent access is the critical
section.  Here, we implement a critical section with a semaphore, so you
have to specify the semaphore which is used for the critical section.
Only those critical sections which use the same semaphore are mutually
exclusive.

‘critical-section’ ( xt semaphore –  ) gforth-experimental “critical-section”
   Execute xt while locking semaphore.  After leaving xt, semaphore is
unlocked even if an exception is thrown.


File: gforth.info,  Node: Hardware operations for multi-tasking,  Next: Message queues,  Prev: Semaphores,  Up: Pthreads

6.27.1.4 Hardware operations for multi-tasking
..............................................

Atomic hardware operations perform the whole operation, without any
other task seeing an intermediate state.  These operations can be used
to synchronize tasks without using slow OS primitives, but compared to
the non-atomic sequences of operations they tend to be slow.  Atomic
operations only work correctly on aligned addresses, even on hardware
that otherwise does not require alignment.

‘!@’ ( u1 a-addr – u2 ) gforth-experimental “store-fetch”
   load U2 from A_ADDR, and store U1 there, as atomic operation

‘+!@’ ( u1 a-addr – u2 ) gforth-experimental “add-store-fetch”
   load U2 from A_ADDR, and increment this location by U1, as atomic
operation

‘?!@’ ( unew uold a-addr – uprev ) gforth-experimental “question-store-fetch”
   load UPREV from A_ADDR, compare it to UOLD, and if equal, store UNEW
there, as atomic operation

   Another hardware operation is the memory barrier.  Unfortunately
modern hardware often can reorder memory operations relative to other
memory operations (as seen by a different core), and the memory barrier
suppresses this reordering for one point in the execution of the task.

‘barrier’ ( – ) gforth-experimental “barrier”
   All memory operations before the barrier are performed before any
memory operation after the barrier.


File: gforth.info,  Node: Message queues,  Prev: Hardware operations for multi-tasking,  Up: Pthreads

6.27.1.5 Message queues
.......................

Gforth’s message queues are a variant of the actor model.

   An event is an xt; the sending task tells the receiving task to run
an event, and the receiving task performs one event from its message
queue when it is ready.  Execute-once closures can be used for events
that pass parameters.

‘send-event’ ( xt task –  ) gforth-experimental “send-event”
   Task IPC: send XT to TASK.  The xt is executed there.  Use a one-shot
closure to pass parameters with the xt.

   When several tasks send event to one task, the events may arrive in
any order.  In order to receive events, you put one of the following
words in the receiving task:

‘?events’ ( –  ) gforth-experimental “question-events”
   Perform all event sequences in the current task’s message queue, one
event sequence at a time.

‘event-loop’ ( –  ) gforth-experimental “event-loop”
   Wait for event sequences, and execute any event sequences when they
arrive.  Return to waiting if no event sequences are in the queue.  This
word never returns.

   Alternatively, when a task is ‘stop’ped, it is also ready for
receiving event, and receiving an event will wake it up.


File: gforth.info,  Node: Cilk,  Prev: Pthreads,  Up: Multitasker

6.27.2 Cilk
-----------

Gforth’s Cilk is a framework for dividing work between multiple tasks
running on several cores, inspired by the programming language of the
same name.  Use ‘require cilk.fs’ if you want to use Cilk.

   The idea is that you identify subproblems that can be solved in
parallel, and the framework assigns worker tasks to these subproblems.
In particular, you use one of the ‘spawn’ words for each subtask.
Eventually you need to wait with ‘cilk-sync’ for the subproblems to be
solved.

   Currently all the spawning has to happen from one task, and
‘cilk-sync’ waits for all subproblems to complete, so using the current
Gforth Cilk for recursive algorithms is not straightforward.

   Do not divide the subproblems too finely, in order to avoid overhead;
how fine is too fine depends on how uniform the run-time for the
subproblems is, but for problems with substantial run-time, having
5*‘cores’ subproblems is probably a good starting point.

‘cores’ ( – u  ) cilk “cores”
   A value containing the number of worker tasks to use.  By default
this is the number of hardware threads (with SMT/HT), if we can
determine that, otherwise 1.  If you want to use a different number,
change ‘cores’ before calling ‘cilk-init’.

‘cilk-init’ ( –  ) cilk “cilk-init”
   Start the worker tasks if not already done.

‘spawn’ ( xt –  ) cilk “spawn”
   Execute xt ( – ) in a worker task.  Use one-time executable closures
to pass heap-allocated closures, allowing to pass arbitrary data from
the spawner to the code running in the worker.
E.g.: ‘( n r ) [{: n f: r :}h1 code ;] spawn’

‘spawn1’ ( x xt –  ) cilk “spawn1”
   Execute xt ( x – ) in a worker task.

‘spawn2’ ( x1 x2 xt –  ) cilk “spawn2”
   Execute xt ( x1 x2 – ) in a worker task.

‘cilk-sync’ ( –  ) cilk “cilk-sync”
   Wait for all subproblems to complete.

‘cilk-bye’ ( –  ) cilk “cilk-bye”
   Terminate all workers.


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

6.28 C Interface
================

Gforth’s C interface works by compiling a wrapper library that contains
C functions which take parameters from the Forth stacks and calls the C
functions.  This wrapper library is compiled by the C compiler.
Compilation results are cached, so that Gforth only needs to rerun the C
compilation if the wrapper library has to change.  This build process is
automatic, and done at the end of a interface declaration.  Gforth uses
libtool and GCC for that process.

   The C interface is now mostly complete, callbacks have been added,
but for structs, we use Forth2012 structs, which don’t have independent
scopes.  The offsets of those structs are extracted from header files
with a SWIG plugin.

* 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::
* Automated interface generation using SWIG::
* Migrating the C interface from earlier Gforth::


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

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

6.28.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.  You can add the C type cast in curly braces after the Forth
type.  This also allows to pass e.g.  structs to C functions, which in
Forth cannot live on the stack.

     c-function printfll printf a n{(long long)} -- n
     c-function pass-struct pass_struct a{*(struct foo *)} -- n

   This typecasting is not available to return values, as C does not
allow typecasts for lvalues.

‘\c’ ( "rest-of-line" –  ) gforth-0.7 “backslash-c”
   One line of C declarations for the C interface

‘c-function’ ( "forth-name" "c-name" "{type}" "—" "type" –  ) gforth-0.7 “c-function”
   Define a Forth word forth-name.  Forth-name has the specified stack
effect and calls the C function ‘c-name’.

‘c-value’ ( "forth-name" "c-name" "—" "type" –  ) gforth-1.0 “c-value”
   Define a Forth word forth-name.  Forth-name has the specified stack
effect and gives the C value of ‘c-name’.

‘c-variable’ ( "forth-name" "c-name" –  ) gforth-1.0 “c-variable”
   Define a Forth word forth-name.  Forth-name returns the address of
‘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

6.28.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 could use
the structures as described above by defining a macro.  Or you use
‘c-funptr’.

‘c-funptr’ ( "forth-name" <{>"c-typecast"<}> "{type}" "—" "type" –  ) gforth-1.0 “c-funptr”
   Define a Forth word forth-name.  Forth-name has the specified stack
effect plus the called pointer on top of stack, i.e.  ‘( {type} ptr --
type )’ and calls the C function pointer ‘ptr’ using the typecast or
struct access ‘c-typecast’.

   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-funptr call-func1 {((func1)ptr)} n -- n

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

     -5 func1a call-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

6.28.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 names
of 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.  The generated
file contains a 128 bit hash (not cryptographically safe, but good
enough for that purpose) of the source code, so changing the
declarations will cause a new compilation.  Normally these files are
cached in ‘$HOME/.gforth/’ARCHITECTURE‘/libcc-named’, so if you
experience problems or have other reasons to force a recompilation, you
can delete the files there.

   Note that you should use ‘c-library’ before everything else having
anything to do with that library, as it resets some setup stuff.  The
idea is that the typical use is to put each
‘c-library’...‘end-c-library’ unit in its own file, and to be able to
include these files in any order.  All other words dealing with the C
interface are hidden in the vocabulary ‘c-lib’, which is put on top o
the search stack by ‘c-library’ and removed by ‘end-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.  The name is also used as part of the C symbols, but characters
outside the legal C symbol names are replaced with underscores.  Also,
you shall 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.  The build system
of Gforth can even cross-compile these libraries, so that the libraries
are available for plattforms on which build tools aren’t installed.

‘c-library-name’ ( c-addr u –  ) gforth-0.7 “c-library-name”
   Start a C library interface with name c-addr u.

‘c-library’ ( "name" –  ) gforth-0.7 “c-library”
   Parsing version of ‘c-library-name’

‘end-c-library’ ( –  ) gforth-0.7 “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

6.28.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-0.7 “clear-libs”
   Clear the list of libs

‘add-lib’ ( c-addr u –  ) gforth-0.7 “add-lib”
   Add library libstring to the list of libraries, where string is
represented by c-addr u.

‘add-libpath’ ( c-addr u –  ) gforth-0.7 “add-libpath”
   Add path string to the list of library search pathes, where string is
represented by c-addr u.

‘add-framework’ ( c-addr u –  ) gforth-1.0 “add-framework”
   Add framework libstring to the list of frameworks, where string is
represented by c-addr u.

‘add-incdir’ ( c-addr u –  ) gforth-1.0 “add-incdir”
   Add path c-addr u to the list of include search pathes

‘add-cflags’ ( c-addr u –  ) gforth-1.0 “add-cflags”
   add any kind of cflags to compilation

‘add-ldflags’ ( c-addr u –  ) gforth-1.0 “add-ldflags”
   add flag to linker


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

6.28.6 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.  Then you need to
generate a callback as described below:

   You can generate C callbacks from Forth code with ‘c-callback’.

‘c-callback’ ( "forth-name" "{type}" "—" "type" –  ) gforth-1.0 “c-callback”
   Define a callback instantiator with the given signature.  The
callback instantiator forth-name ‘( xt -- addr )’ takes an XT, and
returns the ADDRess of the C function handling that callback.

‘c-callback-thread’ ( "forth-name" "{type}" "—" "type" –  ) gforth-1.0 “c-callback-thread”
   Define a callback instantiator with the given signature.  The
callback instantiator forth-name ‘( xt -- addr )’ takes an XT, and
returns the ADDRess of the C function handling that callback.  This
callback is safe when called from another thread

   This precompiles a number of callback functions (up to the value
‘callback#’).  The prototype of the C function is deduced from its Forth
signature.  If this is not sufficient, you can add types in curly braces
after the Forth type.

     c-callback vector4double: f f f f -- void
     c-callback vector4single: f{float} f{float} f{float} f{float} -- void


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

6.28.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,  Next: Automated interface generation using SWIG,  Prev: C interface internals,  Up: C Interface

6.28.8 Low-Level C Interface Words
----------------------------------

‘open-lib’ ( c-addr1 u1 – u2 ) gforth-0.4 “open-lib”

‘lib-sym’ ( c-addr1 u1 u2 – u3 ) gforth-0.4 “lib-sym”

‘lib-error’ ( – c-addr u ) gforth-0.7 “lib-error”
   Error message for last failed ‘open-lib’ or ‘lib-sym’.

‘call-c’ ( ... w – ... ) gforth-0.2 “call-c”
   Call the C function pointed to by w.  The C function has to access
the stack itself.  The stack pointers are exported into a ptrpair
structure passed to the C function, and returned in that form.


File: gforth.info,  Node: Automated interface generation using SWIG,  Next: Migrating the C interface from earlier Gforth,  Prev: Low-Level C Interface Words,  Up: C Interface

6.28.9 Automated interface generation using SWIG
------------------------------------------------

SWIG, the Simple Wrapper Interface Generator, is used to create C
interfaces for a lot of programming languages.  The SWIG version
extended with a Forth module can be found on github
(https://github.com/GeraldWodni/swig).

6.28.9.1 Basic operation
........................

C-headers are parsed and converted to Forth-Sourcecode which uses the
previously describe C interface functions.

6.28.9.2 Detailed operation:
............................

  1. Select a target, in this example we are using ‘example.h’
  2. Create an interface file for the header.  This can be used to pass
     options, switches and define variables.  In the simplest case it
     just instructs to translate all of ‘example.h’:
          %module example
          %insert("include")
          {
              #include "example.h"
          }
          %include "example.h"
  3. Use SWIG to create a ‘.fsi-c’ file.
     ‘swig -forth -stackcomments -use-structs -enumcomments -o
     example-fsi.c example.i’.
     FSI stands “Forth Source Independent” meaning it can be transferred
     to any host having a C-compiler.  SWIG is not required past this
     point.
  4. On the target machine compile the ‘.fsi-c’ file to a ‘.fsx’ (x
     stands for executable)
     ‘gcc -o example.fsx example-fsi.c’
     The compilation will resolve all constants to the values on the
     target.
  5. The last step is to run the executable and capture its output to a
     ‘.fs’ “Forth Source” file.
     ‘./example.fsx -gforth > example.fs’
     This code can now be used on the target platform.

6.28.9.3 Examples
.................

You can find some examples in SWIG’s Forth Example section
(https://github.com/GeraldWodni/swig/tree/master/Examples/forth).

   A lot of interface files can be found in Forth Posix C-Interface
(https://github.com/GeraldWodni/posix) and Forth C-Interface Modules
(https://github.com/GeraldWodni/forth-c-interfaces).

   Contribution to the Forth C-Interface Module repository
(https://github.com/GeraldWodni/forth-c-interfaces) is always welcome.


File: gforth.info,  Node: Migrating the C interface from earlier Gforth,  Prev: Automated interface generation using SWIG,  Up: C Interface

6.28.10 Migrating from Gforth 0.7
---------------------------------

In this version, you can use ‘\c’, ‘c-function’ and ‘add-lib’ only
inside ‘c-library’...‘end-c-library’.  ‘add-lib’ now always starts from
a clean slate inside a ‘c-library’, so you don’t need to use
‘clear-libs’ in most cases.

   If you have a program that uses these words outside
‘c-library’...‘end-c-library’, just wrap them in
‘c-library’...‘end-c-library’.  You may have to add some instances of
‘add-lib’, however.


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

6.29 Assembler and Code Words
=============================

* Menu:

* Assembler Definitions::       Definitions in assembly language
* Common Assembler::            Assembler Syntax
* Common Disassembler::
* 386 Assembler::               Deviations and special cases
* AMD64 Assembler::
* 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: Assembler Definitions,  Next: Common Assembler,  Prev: Assembler and Code Words,  Up: Assembler and Code Words

6.29.1 Definitions in assembly language
---------------------------------------

Gforth provides ways to implement words in assembly language (using
‘abi-code’...‘end-code’), and also ways to define defining words with
arbitrary run-time behaviour (like ‘does>’), where (unlike ‘does>’) the
behaviour is not defined in Forth, but in assembly language (with
‘;code’).

   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.  It does provide assemblers for several
of the architectures it runs on, though.  Moreover, you can use a
system-independent assembler in Gforth, or compile machine code directly
with ‘,’ and ‘c,’.

   Another problem is that the virtual machine registers of Gforth (the
stack pointers and the virtual machine instruction pointer) depend on
the installation and engine.  Also, which registers are free to use also
depend on the installation and engine.  So any code written to run in
the context of the Gforth virtual machine is essentially limited to the
installation and engine it was developed for (it may run elsewhere, but
you cannot rely on that).

   Fortunately, you can define ‘abi-code’ words in Gforth that are
portable to any Gforth running on a platform with the same calling
convention (ABI); typically this means portability to the same
architecture/OS combination, sometimes crossing OS boundaries).

‘assembler’ ( –  ) tools-ext “assembler”
   A vocubulary: Replaces the wordlist at the top of the search order
with the assembler wordlist.

‘init-asm’ ( –  ) gforth-0.2 “init-asm”
   Pushes the assembler wordlist on the search order.

‘abi-code’ ( "name" – colon-sys  ) gforth-1.0 “abi-code”
   Start a native code definition that is called using the platform’s
ABI conventions corresponding to the C-prototype:
     Cell *function(Cell *sp, Float **fpp);
   The FP stack pointer is passed in by providing a reference to a
memory location containing the FP stack pointer and is passed out by
storing the changed FP stack pointer there (if necessary).

‘;abi-code’ ( –  ) gforth-1.0 “semicolon-abi-code”
   Ends the colon definition, but at run-time also changes the last
defined word X (which must be a ‘create’d word) to call the following
native code using the platform’s ABI convention corresponding to the C
prototype:
      Cell *function(Cell *sp, Float **fpp, Address body);
   The FP stack pointer is passed in by providing a reference to a
memory location containing the FP stack pointer and is passed out by
storing the changed FP stack pointer there (if necessary).  The
parameter body is the body of X.

‘end-code’ ( colon-sys –  ) gforth-0.2 “end-code”
   End a code definition.  Note that you have to assemble the return
from the ABI call (for ‘abi-code’) or the dispatch to the next VM
instruction (for ‘code’ and ‘;code’) yourself.

‘code’ ( "name" – colon-sys  ) tools-ext “code”
   Start a native code definition that runs in the context of the Gforth
virtual machine (engine).  Such a definition is not portable between
Gforth installations, so we recommend using ‘abi-code’ instead of
‘code’.  You have to end a ‘code’ definition with a dispatch to the next
virtual machine instruction.

‘;code’ ( compilation. colon-sys1 – colon-sys2  ) tools-ext “semicolon-code”
   The code after ‘;code’ becomes the behaviour of the last defined word
(which must be a ‘create’d word).  The same caveats apply as for ‘code’,
so we recommend using ‘;abi-code’ instead.

‘flush-icache’ ( c-addr u – ) gforth-0.2 “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, ‘abi-code’ words etc.
will not work (reliably), either.

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

     : foo                              abi-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

   For using ‘abi-code’, take a look at the ABI documentation of your
platform to see how the parameters are passed (so you know where you get
the stack pointers) and how the return value is passed (so you know
where the data stack pointer is returned).  The ABI documentation also
tells you which registers are saved by the caller (caller-saved), so you
are free to destroy them in your code, and which registers have to be
preserved by the called word (callee-saved), so you have to save them
before using them, and restore them afterwards.  For some architectures
and OSs we give short summaries of the parts of the calling convention
in the appropriate sections.  More reverse-engineering oriented people
can also find out about the passing and returning of the stack pointers
through ‘see abi-call’.

   Most ABIs pass the parameters through registers, but some (in
particular the most common 386 (aka IA-32) calling conventions) pass
them on the architectural stack.  The common ABIs all pass the return
value in a register.

   Other things you need to know for using ‘abi-code’ is that both the
data and the FP stack grow downwards (towards lower addresses) in
Gforth, with ‘1 cells’ size per cell, and ‘1 floats’ size per FP value.

   Here’s an example of using ‘abi-code’ on the 386 architecture:

     abi-code my+ ( n1 n2 -- n )
     4 sp d) ax mov \ sp into return reg
     ax )    cx mov \ tos
     4 #     ax add \ update sp (pop)
     cx    ax ) add \ sec = sec+tos
     ret            \ return from my+
     end-code

   An AMD64 variant of this example can be found in *note AMD64
Assembler::.

   Here’s a 386 example that deals with FP values:

     abi-code my-f+ ( r1 r2 -- r )
     8 sp d) cx mov  \ load address of fp
     cx )    dx mov  \ load fp
     .fl dx )   fld  \ r2
     8 #     dx add  \ update fp
     .fl dx )   fadd \ r1+r2
     .fl dx )   fstp \ store r
     dx    cx ) mov  \ store new fp
     4 sp d) ax mov  \ sp into return reg
     ret             \ return from my-f+
     end-code


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

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

   The rest of this section is of interest mainly for those who want to
define ‘code’ words (instead of the more portable ‘abi-code’ words).

   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).  If you
are using ‘CODE’ instead of ‘ABI-CODE’, and 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 adapt to a changed register assignment.

   The most common use of these registers is to end a ‘code’ definition
with a 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).
When using ‘ABI-CODE’, you can just assemble a normal subroutine return
(but make sure you return the data stack pointer).

   Another difference between Gforth versions is that the top of stack
is kept in memory in ‘gforth’ and, on most platforms, in a register in
‘gforth-fast’.  For ‘ABI-CODE’ definitions, any stack caching registers
are guaranteed to be flushed to the stack, allowing you to reliably
access the top of stack in memory.


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

6.29.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-0.2 “discode”
   hook for the disassembler: disassemble u bytes of code at addr

   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: AMD64 Assembler,  Prev: Common Disassembler,  Up: Assembler and Code Words

6.29.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 AT&T-style parameter order
(i.e., destination last).

   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 default is ‘.fx’, so you need
to specify ‘.fl’ explicitly when dealing with Gforth FP values.

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

   Based on the Intel ABI (used in Linux), ‘abi-code’ words can find the
data stack pointer at ‘4 sp d)’, and the address of the FP stack pointer
at ‘8 sp d)’; the data stack pointer is returned in ‘ax’; ‘Ax’, ‘cx’,
and ‘dx’ are caller-saved, so you do not need to preserve their values
inside the word.  You can return from the word with ‘ret’, the
parameters are cleaned up by the caller.

   For examples of 386 ‘abi-code’ words, see *note Assembler
Definitions::.


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

6.29.5 AMD64 (x86_64) Assembler
-------------------------------

The AMD64 assembler is a slightly modified version of the 386 assembler,
and as such shares most of the syntax.  Two new prefixes, ‘.q’ and
‘.qa’, are provided to select 64-bit operand and address sizes
respectively.  64-bit sizes are the default, so normally you only have
to use the other prefixes.  Also there are additional register operands
‘R8’-‘R15’.

   The registers lack the ’e’ or ’r’ prefix; even in 64 bit mode, ‘rax’
is called ‘ax’.  Additional register operands are available to refer to
the lowest-significant byte of all registers: ‘R8L’-‘R15L’, ‘SPL’,
‘BPL’, ‘SIL’, ‘DIL’.

   The Linux-AMD64 calling convention is to pass the first 6 integer
parameters in rdi, rsi, rdx, rcx, r8 and r9 and to return the result in
rax and rdx; to pass the first 8 FP parameters in xmm0–xmm7 and to
return FP results in xmm0–xmm1.  So ‘abi-code’ words get the data stack
pointer in ‘di’ and the address of the FP stack pointer in ‘si’, and
return the data stack pointer in ‘ax’.  The other caller-saved registers
are: r10, r11, xmm8-xmm15.  This calling convention reportedly is also
used in other non-Microsoft OSs.

   Windows x64 passes the first four integer parameters in rcx, rdx, r8
and r9 and return the integer result in rax.  The other caller-saved
registers are r10 and r11.

   On the Linux platform, according to
<https://uclibc.org/docs/psABI-x86_64.pdf> page 21 the registers AX CX
DX SI DI R8 R9 R10 R11 are available for scratch.

   The addressing modes for the AMD64 are:

     \ running word A produces a memory error as the registers are not initialised ;-)
     ABI-CODE A  ( -- )
         500        #               AX  MOV     \ immediate
             DX              AX  MOV     \ register
             200             AX  MOV     \ direct addressing
             DX  )           AX  MOV     \ indirect addressing
         40  DX  D)          AX  MOV     \ base with displacement
             DX  CX      I)  AX  MOV     \ scaled index
             DX  CX  *4  I)  AX  MOV     \ scaled index
         40  DX  CX  *4  DI) AX  MOV     \ scaled index with displacement

             DI              AX  MOV     \ SP Out := SP in
                                 RET
     END-CODE

   Here are a few examples of an AMD64 ‘abi-code’ words:

     abi-code my+  ( n1 n2 -- n3 )
     \ SP passed in di, returned in ax,  address of FP passed in si
     8 di d) ax lea        \ compute new sp in result reg
     di )    dx mov        \ get old tos
     dx    ax ) add        \ add to new tos
     ret
     end-code

     \ Do nothing
     ABI-CODE aNOP  ( -- )
            DI  )       AX      LEA          \ SP out := SP in
                                RET
     END-CODE

     \ Drop TOS
     ABI-CODE aDROP  ( n -- )
        8   DI  D)      AX      LEA          \ SPout := SPin - 1
                                RET
     END-CODE

     \ Push 5 on the data stack
     ABI-CODE aFIVE   ( -- 5 )
        -8  DI  D)      AX      LEA          \ SPout := SPin + 1
        5   #           AX  )   MOV          \ TOS := 5
                                RET
     END-CODE

     \ Push 10 and 20 into data stack
     ABI-CODE aTOS2  ( -- n n )
        -16 DI  D)      AX      LEA          \ SPout := SPin + 2
        10  #       8   AX  D)  MOV          \ TOS - 1 := 10
        20  #           AX  )   MOV          \ TOS := 20
                                RET
     END-CODE

     \ Get Time Stamp Counter as two 32 bit integers
     \ The TSC is incremented every CPU clock pulse
     ABI-CODE aRDTSC   ( -- TSCl TSCh )
                                RDTSC        \ DX:AX := TSC
        $FFFFFFFF #     AX      AND          \ Clear upper 32 bit AX
       0xFFFFFFFF #     DX      AND          \ Clear upper 32 bit DX
            AX          R8      MOV          \ Tempory save AX
        -16 DI  D)      AX      LEA          \ SPout := SPin + 2
            R8      8   AX  D)  MOV          \ TOS-1 := saved AX = TSC low
            DX          AX  )   MOV          \ TOS := Dx = TSC high
                                RET
     END-CODE

     \ Get Time Stamp Counter as 64 bit integer
     ABI-CODE RDTSC   ( -- TSC )
                                RDTSC        \ DX:AX := TSC
        $FFFFFFFF #     AX      AND          \ Clear upper 32 bit AX
        32  #           DX      SHL          \ Move lower 32 bit DX to upper 32 bit
            AX          DX      OR           \ Combine AX wit DX in DX
        -8  DI  D)      AX      LEA          \ SPout := SPin + 1
            DX          AX  )   MOV          \ TOS := DX
                                RET
     END-CODE

     VARIABLE V

     \ Assign 4 to variable V
     ABI-CODE V=4 ( -- )
            BX                  PUSH         \ Save BX, used by gforth
        V   #           BX      MOV          \ BX := address of V
        4   #           BX )    MOV          \ Write 4 to V
            BX                  POP          \ Restore BX
            DI  )       AX      LEA          \ SPout := SPin
                                RET
     END-CODE

     VARIABLE V

     \ Assign 5 to variable V
     ABI-CODE V=5 ( -- )
        V   #           CX      MOV          \ CX := address of V
        5   #           CX )    MOV          \ Write 5 to V
        DI )            AX      LEA          \ SPout := SPin
                                RET
     END-CODE

     ABI-CODE TEST2  ( -- n n )
        -16 DI  D)  AX          LEA          \ SPout := SPin + 2
        5   #       CX          MOV          \ CX := 5
        5   #       CX          CMP
        0= IF
            1   #   8   AX  D)      MOV      \ If CX = 5 then TOS - 1 := 1  <--
        ELSE
            2   #   8   AX  D)      MOV      \ else TOS - 1 := 2
        THEN
        6   #       CX          CMP
        0= IF
            3   #       AX  )       MOV      \ If CX = 6 then TOS := 3
        ELSE
            4   #       AX  )       MOV      \ else TOS := 4  <--
        THEN
                                RET
     END-CODE

     \ Do four loops. Expect : ( 4 3 2 1 -- )
     ABI-CODE LOOP4  ( -- n n n n )
            DI          AX      MOV          \ SPout := SPin
        4   #           DX      MOV          \ DX := 4  loop counter
        BEGIN
            8   #           AX      SUB      \ SP := SP + 1
                DX          AX  )   MOV      \ TOS := DX
            1   #           DX      SUB      \ DX := DX - 1
        0= UNTIL
                                RET
     END-CODE

   Here’s a AMD64 example that deals with FP values:

     abi-code my-f+  ( r1 r2 -- r )
     \ SP passed in di, returned in ax,  address of FP passed in si
     si )       dx mov         \ load fp
     8 dx d)  xmm0 movsd       \ r2
     dx )     xmm0 addsd       \ r1+r2
     xmm0  8 dx d) movsd       \ store r
     8 #      si ) add         \ update fp
     di         ax mov         \ sp into return reg
     ret
     end-code


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

6.29.6 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

6.29.7 MIPS assembler
---------------------

The MIPS assembler was originally written by Christian Pirker.

   Currently the assembler and disassembler covers most of the MIPS32
architecture and doesn’t support FP instructions.

   The register names ‘$a0’–‘$a3’ are not available to avoid shadowing
hex numbers.  Use register numbers ‘$4’–‘$7’ instead.

   Nothing distinguishes registers from immediate values.  Use explicit
opcode names with the ‘i’ suffix for instructions with immediate
argument.  E.g.  ‘addiu,’ in place of ‘addu,’.

   Where the architecture manual specifies several formats for the
instruction (e.g., for ‘jalr,’),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 manually (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.  For branches the argument specifying the target is a relative
address.  Add the address of the delay slot to get the absolute address.

   Note that you must not put branches nor jumps (nor control-flow
instructions) into the delay slot.  Also it is a bad idea to put
pseudo-ops such as ‘li,’ into a delay slot, as these may expand to
several instructions.  The MIPS I architecture also had load delay
slots, and newer MIPSes still have restrictions on using ‘mfhi,’ and
‘mflo,’.  Be careful to satisfy these restrictions, the assembler does
not do it for you.

   Some example of instructions are:

     $ra  12 $sp  sw,         \ sw    ra,12(sp)
     $4    8 $s0  lw,         \ lw    a0,8(s0)
     $v0  $0  lui,            \ lui   v0,0x0
     $s0  $s4  $12  addiu,    \ addiu s0,s4,0x12
     $s0  $s4  $4  addu,      \ addu  s0,s4,$a0
     $ra  $t9  jalr,          \ jalr  t9

   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,

   The calling conventions for 32-bit MIPS machines is to pass the first
4 arguments in registers ‘$4’..‘$7’, and to use ‘$v0’-‘$v1’ for return
values.  In addition to these registers, it is ok to clobber registers
‘$t0’-‘$t8’ without saving and restoring them.

   If you use ‘jalr,’ to call into dynamic library routines, you must
first load the called function’s address into ‘$t9’, which is used by
position-indirect code to do relative memory accesses.

   Here is an example of a MIPS32 ‘abi-code’ word:

     abi-code my+  ( n1 n2 -- n3 )
       \ SP passed in $4, returned in $v0
       $t0  4 $4  lw,         \ load n1, n2 from stack
       $t1  0 $4  lw,
       $t0  $t0  $t1  addu,   \ add n1+n2, result in $t0
       $t0  4 $4  sw,         \ store result (overwriting n1)
       $ra  jr,               \ return to caller
       $v0  $4  4  addiu,     \ (delay slot) return uptated SP in $v0
     end-code


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

6.29.8 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

6.29.9 ARM Assembler
--------------------

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

   The assembler uses a postfix syntax with the same operand order as
used in the ARM Architecture Reference Manual.  Mnemonics are suffixed
by a comma.

   Registers are specified by their names ‘r0’ through ‘r15’, with the
aliases ‘pc’, ‘lr’, ‘sp’, ‘ip’ and ‘fp’ provided for convenience.  Note
that ‘ip’ refers to the“intra procedure call scratch register” (‘r12’)
and does not refer to an instruction pointer.  ‘sp’ refers to the ARM
ABI stack pointer (‘r13’) and not the Forth stack 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 ‘}’ respectively.  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 like an addressing mode, Use
one of ‘DA’, ‘IA’, ‘DB’, ‘IB’, ‘DA!’, ‘IA!’, ‘DB!’ or ‘IB!’.

   The following table gives some examples:

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

   Control structure words typical for Forth assemblers are available:
‘if,’ ‘ahead,’ ‘then,’ ‘else,’ ‘begin,’ ‘until,’ ‘again,’ ‘while,’
‘repeat,’ ‘repeat-until,’.  Conditions are specified in front of these
words:

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

   Example of a definition using the ARM assembler:

     abi-code my+ ( n1 n2 --  n3 )
        \ arm abi: r0=SP, r1=&FP, r2,r3,r12 saved by caller
        r0 IA!  { r2 r3 }  ldm,     \ pop r2 = n2, r3 = n1
        r3  r2  r3         add,     \ r3 = n1+n1
        r3  r0 -4 #]!      str,     \ push r3
        pc  lr             mov,     \ return to caller, new SP in r0
     end-code


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

6.29.10 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: Carnal words,  Next: Passing Commands to the OS,  Prev: Assembler and Code Words,  Up: Words

6.30 Carnal words
=================

These words deal with the mechanics of Gforth (in Forth circles called
“carnal knowledge” of a Forth system), but we consider them stable
enough to document them.

* Menu:

* Header fields::
* Header methods::
* Threading Words::


File: gforth.info,  Node: Header fields,  Next: Header methods,  Prev: Carnal words,  Up: Carnal words

6.30.1 Header fields
--------------------

In Gforth 1.0 we switched to a new word header layout.  For a detailed
description, read: Bernd Paysan and M. Anton Ertl.  ‘The new Gforth
header (http://www.euroforth.org/ef19/papers/paysan.pdf)’.  In 35th
EuroForth Conference, pages 5-20, 2019.  Since this paper was published,
xt and nt have been changed to point to the parameter field, like the
body, but otherwise it is still up-to-date.

   This section explains just the data structure and the words used to
access it.  A header has the following fields:

     name
     >f+c
     >link
     >cfa
     >namehm
     >body

   Currently Gforth has the names shown above for getting from the
xt/nt/body to the field, but apart from the standard ‘>body’ they are
not stable Gforth words.  Instead, we provide access words.  Note that
the documented access words have survived the reorganization of the
header layout.

   Some of the words expect an nt, some expect an xt.  Given that both
nt and xt point to the body of a word, what is the difference?  For most
words, the xt and nt use the same header, and with nt=xt, they point to
the same place.  However, for a synonym (*note Aliases::) there is a
difference; consider the example

     create x
     synonym y x
     synonym z y

   In this case the nt of ‘z’ points to the body of ‘z’, while the xt of
‘z’ points to the body of ‘x’.  Words defined with ‘alias’ or ‘forward’
(*note Forward::) also have different nts and xts.

   The name field is variable-length and is accessed with ‘name>string’
(*note Name token::).

   The ‘>f+c’ field contains flags and the name length (count).  You
read the count with ‘name>string’, and the flags with

‘compile-only?’ ( nt – flag  ) gforth-1.0 “compile-only?”
   true if nt is marked as compile-only.

   The ‘>link’ field contains a link to the previous word in the same
word list.  You can read it with ‘name>link’ (*note Name token::).

   The name, ‘>f+c’ and ‘>link’ fields are not present for ‘noname’
words, but ‘name>string’ and ‘name>link’ work nevertheless, producing 0
0 and 0, respectively.

   The ‘>cfa’ field (aka code field) contains the code address used for
‘execute’ing the word; you can read it with ‘>code-address’ and write it
with ‘code-address!’ (*note Threading Words::).

   The ‘>namehm’ field contains the address of the header methods table,
described below.  You access it by performing or accessing header
methods (*note Header methods::).

   The ‘>body’ (aka parameter) field contains data or threaded code
specific to the word type; its length depends on the word type.  E.g.,
for a ‘constant’ it contains a cell with the value of the constant.  You
can access it through ‘>body’ (*note CREATE..DOES> details::), but this
is only standard for words you defined with ‘create’.


File: gforth.info,  Node: Header methods,  Next: Threading Words,  Prev: Header fields,  Up: Carnal words

6.30.2 Header methods
---------------------

The new Gforth word header is object-oriented and supports the following
methods (method selectors):

     .hm label method          overrider        field
               execute         set-execute      >cfa
     opt:      opt-compile,    set-optimizer    >hmcompile,
     to:       defer!          set-to           >hmto
     defer@:   defer@          set-defer@       >hmdefer@
     extra:                                     >hmextra
     >int:     name>interpret  set->int         >hm>int
     >comp:    name>compile    set->comp        >hm>comp
     >string:  name>string     set-name>string  >hm>string
     >link:    name>link       set-name>link    >hm>link

   Many of these words are not stable Gforth words, but Gforth has
stable higher-level words that we mention below.

   You can look at the header methods of a word with

‘.hm’ ( nt –  ) gforth-1.0 “dot-h-m”
   print the header methods of nt

   Overrider (setter) words change the method implementation for the
most recent definition.  Quotations or closures restore the previous
most recent definition when they are completed, so they are not
considered most recent, and you can do things like:

     : my2dup over over ;
     [: drop ]] over over [[ ;] set-optimizer

   The ‘execute’ method is actually stored in the ‘>cfa’ field in the
header rather than in the header-methods table for performance reasons;
also it is implemented through a native-code address, while the other
methods are implemented by calling an xt.  The high-level way to set
this method is

‘set-execute’ ( ca –  ) gforth-1.0 “set-execute”
   Changes the current word such that it jumps to the native code at ca.
Also changes the ‘compile,’ implementation to the most general (and
slowest) one.  Call ‘set-optimizer’ afterwards if you want a more
efficient ‘compile,’ implementation.

   To get a code address for use with ‘set-execute’, you can use words
like ‘docol:’ or ‘>code-address’, *Note Threading Words::.

   As an alternative to ‘set-execute’, there is also ‘set-does>’ (*note
User-defined Defining Words::), which takes an xt.

   Moreover, there are the low-level ‘code-address!’ and ‘definer!’
(*note Threading Words::).

   The ‘opt-compile,’ method is what ‘compile,’ does on most Gforth
engines (‘gforth-itc’ uses ‘,’ instead).  You can define a more
efficient implementation of ‘compile,’ for the current word with
‘set-optimizer’ (*note User-defined compile-comma::).  Note that the end
result must be equivalent to ‘postpone literal postpone execute’.

   As an example of the use of ‘set-optimizer’, consider the following
definition of ‘constant’:

     : constant ( n "name" -- ; name: -- n )
       create ,
       ['] @ set-does>
     ;

     5 constant five
     : foo five ; see foo

   The Forth system does not know that the value of a constant must not
be changed, and just sees a ‘create’d word (which can be changed with
‘>body’), and ‘foo’ first pushes the body address of ‘five’ and then
fetches from there.  With ‘set-optimizer’ the definition of ‘constant’
can be optimized as follows:

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

   Now ‘foo’ contains the literal 5 rather than a call to ‘five’.

   Note that ‘set-execute’ and ‘set-does>’ perform ‘set-optimizer’
themselves in order to ensure that ‘execute’ and ‘compile,’ agree, so if
you want to add your own optimizer, you should add it afterwards.

   The ‘defer!’ (aka ‘(to)’ method (*note User-defined TO and DEFER@::)
implements ‘defer!’ for words defined with ‘defer’ and similar words,
but it is also the core of ‘to’.  The general stack effect of the
‘defer!’/‘(to)’ method is ‘( val xt -- )’, where xt identifies the word
stored into, and val is the value (of appropriate type) stored there.

   E.g., one can implement ‘fvalue’ as follows:

     : fvalue-to ( r xt -- ) >body f! ;

     : fvalue ( r -- )
       create f,
       ['] f@ set-does>
       ['] fvalue-to set-to ;

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

   You can improve the generated code with ‘set-optimizer’:

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

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

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

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

   In practice Gforth has a few additional twists to implement, e.g.,
‘+TO’.

   ‘Set-defer@’ (*note User-defined TO and DEFER@::) allows to implement
variants of the ‘defer@’ (*note Deferred Words::) method for
‘defer’-like words.

   The ‘>hmextra’ field is used for cases where additional data needs to
be stored in the header methods table.  In particular, it stores the xt
passed to ‘set-does>’ (and ‘does>’ calls ‘set-does>’) and the code
address behind ‘;abi-code’.

   The methods above all consume an xt, not an nt, but the override
words work on the most recent definition.  This means that if you use,
e.g., ‘set-optimizer’ on a synonym, the effect will probably not be what
you intended: When ‘compile,’ing the xt of the word, the ‘opt-compile,’
implementation of the original word will be used, not the freshly-set
one of the synonym.

   The following methods consume an nt.

   The ‘name>interpret’ method is implemented as noop for most words,
except synonyms and similar words.

‘set->int’ ( xt –  ) gforth-1.0 “set-to-int”
   Sets the implementation of the ‘name>interpret ( nt -- xt2 )’ method
of the current word to xt.

   The ‘name>compile’ method produces the compilation semantics of the
nt.  By changing it with ‘set->comp’, you can change the compilation
semantics, but it’s not as simple as just pushing the xt of the desired
compilation semantics, because of the stack effect of ‘name>compile’.
Generally you should avoid changing the compilation semantics, and if
you do, use a higher-level word like ‘immediate’ or
‘interpret/compile:’, *Note Combined words::.

‘set->comp’ ( xt –  ) gforth-1.0 “set-to-comp”
   Sets the implementation of the ‘name>compile ( nt -- w xt2 )’ method
of the current word to xt.

‘immediate?’ ( nt – flag  ) gforth-1.0 “immediate?”
   true if the word nt has non-default compilation semantics (that’s not
quite according to the definition of immediacy, but many people mean
that when they call a word “immediate”).

   ‘Name>string’ and ‘Name>link’ are methods in order to make it
possible to eliminate the name, ‘>f+c’ and ‘link’ fields from noname
headers, but still produce meaningful results when using these words.
You will typically not change the implementations of these methods
except with ‘noname’, but we still have

‘set-name>string’ ( xt –  ) gforth-1.0 “set-name-to-string”
   Sets the implementation of the ‘name>string ( nt -- addr u )’ method
of the current word to xt.

‘set-name>link’ ( xt –  ) gforth-1.0 “set-name-to-link”
   Sets the implementation of the ‘name>link ( nt1 -- nt2|0 )’ method of
the current word to xt.


File: gforth.info,  Node: Threading Words,  Prev: Header methods,  Up: Carnal words

6.30.3 Threading Words
----------------------

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

   These words provide access to code fields, code addresses and other
threading stuff in Gforth.  It more or less abstracts away the
differences between direct and indirect threading.

   Up to and including Gforth 0.7, the code address (plus, for
‘does>’-defined words, the address returned by ‘>does-code’) was
sufficient to know the type of the word.  However, since Gforth-1.0 the
behaviour or at least implementation of words like ‘compile,’ and
‘name>compile’ can be determined independently as described in *note
Header methods::.

   The following words for create a code field and at the same time
initialize the header methods:

‘hmcopy,’ ( xt –  ) gforth-experimental “hmcopy-comma”
   While constructing a header, allocate the code field, and use xt as
prototype for setting the code field and the header methods.

‘docol,’ ( –  ) gforth-1.0 “docol,”
   The code address of a colon definition.

‘docon,’ ( –  ) gforth-1.0 “docon,”
   The code address of a ‘CONSTANT’.

‘dovar,’ ( –  ) gforth-1.0 “dovar,”
   The code address of a ‘CREATE’d word.

‘douser,’ ( –  ) gforth-1.0 “douser,”
   The code address of a ‘USER’ variable.

‘dodefer,’ ( –  ) gforth-1.0 “dodefer,”
   The code address of a ‘defer’ed word.

‘dofield,’ ( –  ) gforth-1.0 “dofield,”
   The code address of a ‘field’.

‘dovalue,’ ( –  ) gforth-1.0 “dovalue,”
   The code address of a ‘CONSTANT’.

‘doabicode,’ ( –  ) gforth-1.0 “doabicode,”
   The code address of a ‘ABI-CODE’ definition.

   For ‘does>’-defined words, use ‘hmcopy,’.

   Or you use a higher-level word like ‘create-from’ (*note Creating
from a prototype::).

   The following words were designed before the introduction of header
methods, and are therefore not the best (and recommended) way to deal
with different word types in Gforth.

   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-0.2 “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-0.2 “>code-address”
   c-addr is the code address of the word xt.

‘code-address!’ ( c_addr xt –  ) gforth-obsolete “code-address!”
   Change a code field with code address c-addr at xt.

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

‘docol:’ ( – addr  ) gforth-0.2 “docol:”
   The code address of a colon definition.

‘docon:’ ( – addr  ) gforth-0.2 “docon:”
   The code address of a ‘CONSTANT’.

‘dovar:’ ( – addr  ) gforth-0.2 “dovar:”
   The code address of a ‘CREATE’d word.

‘douser:’ ( – addr  ) gforth-0.2 “douser:”
   The code address of a ‘USER’ variable.

‘dodefer:’ ( – addr  ) gforth-0.2 “dodefer:”
   The code address of a ‘defer’ed word.

‘dofield:’ ( – addr  ) gforth-0.2 “dofield:”
   The code address of a ‘field’.

‘dovalue:’ ( – addr  ) gforth-0.7 “dovalue:”
   The code address of a ‘CONSTANT’.

‘dodoes:’ ( – addr  ) gforth-0.6 “dodoes:”
   The code address of a ‘DOES>’-defined word.

‘doabicode:’ ( – addr  ) gforth-1.0 “doabicode:”
   The code address of a ‘ABI-CODE’ definition.

   For a word X defined with ‘set-does>’, the code address points to
‘dodoes:’, and the ‘>hmextra’ field of the header methods contains the
xt of the word that is called after pushing the body addres of X.

   If you want to know whether a word is a ‘DOES>’-defined word, and
what Forth code it executes, ‘>does-code’ tells you that:

‘>does-code’ ( xt1 – xt2  ) gforth-0.2 “>does-code”
   If xt1 is the execution token of a child of a ‘set-does>’-defined
word, xt2 is the xt passed to ‘set-does>’, i.e, the xt of the word that
is executed when executing xt1 (but first the body address of xt1 is
pushed).  If xt1 does not belong to a ‘set-does>’-defined word, xt2 is
0.

   You can use the resulting xt2 with ‘set-does>’ (preferred) to change
the latest word or with

‘does-code!’ ( xt2 xt1 –  ) gforth-0.2 “does-code!”
   Change xt1 to be a ‘xt2 set-does>’-defined word.

   to change an arbitrary word.

   The following two words generalize ‘>code-address’, ‘>does-code’,
‘code-address!’, and ‘does-code!’:

‘>definer’ ( xt – definer  ) gforth-0.2 “>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-obsolete “definer!”
   The word represented by XT changes its behaviour to the behaviour
associated with DEFINER.

   ‘Code-address!’, ‘does-code!’, and ‘definer!’ update the
‘opt-compile,’ method to a somewhat generic compiler for that word type
(in particular, primitives get the slow ‘general-compile,’ method rather
than the primitive-specific ‘peephole-compile,’).


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

6.31 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-0.2 “sh”
   Execute the rest of the command line as shell command(s).
Afterwards, ‘$?’ produces the exit status of the command.

‘system’ ( c-addr u –  ) gforth-0.2 “system”
   Pass the string specified by C-ADDR U to the host operating system
for execution in a sub-shell.  Afterwards, ‘$?’ produces the exit status
of the command.  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::).

‘sh-get’ ( c-addr u – c-addr2 u2  ) gforth-1.0 “sh-get”
   Run the shell command addr u; c-addr2 u2 is the output of the
command.  The exit code is in ‘$?’, the output also in ‘sh$ 2@’.

‘$?’ ( – n  ) gforth-0.2 “dollar-question”
   ‘Value’ – the exit status returned by the most recently executed
‘system’ command.

‘getenv’ ( c-addr1 u1 – c-addr2 u2 ) gforth-0.2 “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

6.32 Keeping track of Time
==========================

‘ms’ ( n –  ) facility-ext “ms”

‘ns’ ( d –  ) gforth-1.0 “ns”

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

‘>time&date&tz’ ( udtime – nsec nmin nhour nday nmonth nyear fdst ndstoff c-addrtz utz ) gforth-1.0 “to-time-and-date”
   Convert time in seconds since 1.1.1970 0:00Z to the current time of
day.  Seconds, minutes and hours are numbered from 0.  Months are
numbered from 1.

‘utime’ ( – dtime ) gforth-0.5 “utime”
   Report the current time in microseconds since some epoch.  Use
‘#1000000 um/mod nip’ to convert to seconds

‘ntime’ ( – dtime ) gforth-1.0 “ntime”
   Report the current time in nanoseconds since some epoch.

‘cputime’ ( – duser dsystem ) gforth-0.5 “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

6.33 Miscellaneous Words
========================

This section lists the Standard 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 Standard Forth words are not currently supported by
Gforth (*note Standard conformance::):

   ‘EDITOR’ ‘EMIT?’ ‘FORGET’


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

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

   ‘gforth-fast’ also does not attempt to differentiate between division
by zero and division overflow, because that costs time in every
division.


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

8 Tools
*******

* Menu:

* Standard 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: Standard Report,  Next: Stack depth changes,  Prev: Tools,  Up: Tools

8.1 ‘ans-report.fs’: Report the words used, sorted by wordset
=============================================================

If you want to label a Forth program as Standard Program, you must
document which wordsets the program uses.

   The ‘ans-report.fs’ tool makes it easy for you to determine which
words from which wordset and which non-standard 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 :
     (

   ‘ans-report.fs’ reports both Forth-94 and Forth-2012 wordsets.  For
words that are in both standards, it reports the wordset without suffix
(e.g., ‘CORE-EXT’).  For Forth-2012-only words, it reports the wordset
with a ‘-2012’ suffix (e.g., ‘CORE-EXT-2012’); and likewise for the
words that are Forth-94-only (i.e., that have been removed in
Forth-2012).

8.1.1 Caveats
-------------

Note that ‘ans-report.fs’ just checks which words are used, not whether
they are used in a standard-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: Standard Report,  Up: Tools

8.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: Standard conformance,  Next: Standard vs Extensions,  Prev: Tools,  Up: Top

9 Standard conformance
**********************

To the best of our knowledge, Gforth is a

   ANS Forth System and a Forth-2012 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 the Facility Extensions word set, except ‘EMIT?’
   • 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
   • providing the Programming-Tools word set
   • providing the Programming-Tools Extensions word set, except
     ‘EDITOR’ and ‘FORGET’
   • providing the Search-Order word set
   • providing the Search-Order Extensions word set
   • providing the String word set
   • providing the String Extensions word set
   • providing the Extended-Character wordset

   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 instead of
     performing QUIT.

   • When an ‘throw’ is performed after a ‘query’, Gforth does not
     always restore the input source specification in effect at the
     corresponding catch.

   In addition, Standard Forth systems are required to document certain
implementation choices.  This chapter tries to meet these requirements
for the Forth-94 standard.  For the Forth-2012 standard, we decided to
produce the additional documentation only if there is demand.  So if you
are really missing this documentation, please let us know.

   In many cases, the following documentation 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: Standard conformance,  Up: Standard conformance

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

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

9.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:
     The execution token represents the interpretation semantics of the
     word.  Gforth defines interpretation semantics for all words; for
     words where the standard does not define interpretation semantics,
     but defines the execution semantics (except ‘LEAVE’), the
     interpretation semantics are to perform the execution semantics.
     For words where the standard defines no interprtation semantics,
     but defined compilation semantics (plus ‘LEAVE’), the
     interpretation semantics are to perform the compilation semantics.
     Some words are marked as compile-only, and ‘'’ gives a warning for
     these words.

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:
     Gforth defines interpretation semantics for all words; for words
     where the standard defines execution semantics (except ‘LEAVE’),
     the interpretation semantics are to perform the execution
     semantics.  For words where the standard defines no interprtation
     semantics, but defined compilation semantics (plus ‘LEAVE’), the
     interpretation semantics are to perform the compilation semantics.
     Some words are marked as compile-only, and text-interpreting them
     gives a warning.

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 code after ‘DOES>’.

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

9.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: Standard conformance

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

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

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

9.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: Standard conformance

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

9.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: Standard conformance

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

9.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: Standard conformance

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

9.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’, ‘k-winch’,
     ‘k-eof’.

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

9.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: Standard conformance

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

9.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"’:
     As many as memory available; the strings are stored in memory
     blocks allocated with ALLOCATE indefinitely.

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

9.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: Standard conformance

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

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

9.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: Standard conformance

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

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

9.8.2 Ambiguous conditions
--------------------------

executing a named local in interpretation state:
     Compiles the local into the current definition (just as in compile
     state); in addition text-interpreting a local in interpretation
     state gives an “is compile-only” warning.

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: Standard conformance

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

9.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: Standard conformance

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

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

9.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: Standard conformance

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

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

9.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: Standard conformance,  Up: Top

10 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 Standard
     Forth.  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 Standard
     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
     Standard Forth compliant; just include the appropriate compat files
     with your program.

   • The tool ‘ans-report.fs’ (*note Standard 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 Standard 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 considerations, 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
(https://forth-standard.org/standard/words).  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

11 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

12 Integrating Gforth into C programs
*************************************

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 Standard 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’ or ‘libgforth.so’ (give the compiler the option
‘-lgforth’, or for one of the other engines ‘-lgforth-fast’,
‘-lgforth-itc’, or ‘-lgforth-ditc’).  All global symbols in this library
that belong to the interface, have the prefix ‘gforth_’; if a common
interface emerges, the functions may also be available through
‘#define’s with the prefix ‘forth_’.

   You can include the declarations of Forth types, the functions and
variables of the interface with ‘#include <gforth.h>’.

   You can now run a Gforth session by either calling ‘gforth_main’ or
using the components:

     Cell gforth_main(int argc, char **argv, char **env)
     {
       Cell retvalue=gforth_start(argc, argv);

       if(retvalue == -56) { /* throw-code for quit */
         retvalue = gforth_bootmessage();     // show boot message
         if(retvalue == -56)
           retvalue = gforth_quit(); // run quit loop
       }
       gforth_cleanup();
       gforth_printmetrics();
       // gforth_free_dict(); // if you want to restart, do this

       return retvalue;
     }

   To interact with the Forth interpreter, there’s ‘Xt gforth_find(Char
* name)’ and ‘Cell gforth_execute(Xt xt)’.

   More documentation needs to be put here.

12.1 Types
==========

‘Cell’, ‘UCell’: data stack elements.

   ‘Float’: float stack element.

   ‘Address’, ‘Xt’, ‘Label’: pointer typies to memory, Forth words, and
Forth instructions inside the VM.

12.2 Variables
==============

Data and FP Stack pointer.  Area sizes.  Accessing the Stacks

   ‘gforth_SP’, ‘gforth_FP’.

12.3 Functions
==============

     void *gforth_engine(Xt *, stackpointers *);
     Cell gforth_main(int argc, char **argv, char **env);
     int gforth_args(int argc, char **argv, char **path, char **imagename);
     ImageHeader* gforth_loader(char* imagename, char* path);
     user_area* gforth_stacks(Cell dsize, Cell rsize, Cell fsize, Cell lsize);
     void gforth_free_stacks(user_area* t);
     void gforth_setstacks(user_area * t);
     void gforth_free_dict();
     Cell gforth_go(Xt* ip0);
     Cell gforth_boot(int argc, char** argv, char* path);
     void gforth_bootmessage();
     Cell gforth_start(int argc, char ** argv);
     Cell gforth_quit();
     Xt gforth_find(Char * name);
     Cell gforth_execute(Xt xt);
     void gforth_cleanup();
     void gforth_printmetrics();
     void gforth_setwinch();

12.4 Signals
============

Gforth sets up signal handlers to catch exceptions and window size
changes.  This may interfere with your C program.


File: gforth.info,  Node: Emacs and Gforth,  Next: Image Files,  Prev: Integrating Gforth,  Up: Top

13 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

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

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

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

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

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

14 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

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

14.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 default image file is ‘gforth.fi’ (in the ‘GFORTHPATH’).  You can
use a different image by using the ‘-i’, ‘--image-file’ or
‘--appl-image’ options (*note Invoking Gforth::), e.g.:

     gforth-fast -i myimage.fi

   There are different variants of image files, and they 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) and makes it difficult to pass
addresses between Forth and library calls or other programs.

   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

14.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).  Indeed, on OSs
with (enabled) address-space randomization non-relocatable images are
unlikely to work.

   You can create a non-relocatable image file with ‘savesystem’, e.g.:

     gforth app.fs -e "savesystem app.fi bye"

‘savesystem’ ( "image" –  ) gforth-0.2 “savesystem”


File: gforth.info,  Node: Data-Relocatable Image Files,  Next: Fully Relocatable Image Files,  Prev: Non-Relocatable Image Files,  Up: Image Files

14.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.  Also, they disable dynamic
native code generation (typically a factor of 2 in speed).  You get a
data-relocatable image, if you pass the engine you want to use through
the ‘GFORTHD’ environment variable to ‘gforthmi’ (*note gforthmi::),
e.g.

     GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs

   Note that the ‘--no-dynamic’ is required here for the image to work
(otherwise it will contain references to dynamically generated code that
is not saved in the image).


File: gforth.info,  Node: Fully Relocatable Image Files,  Next: Stack and Dictionary Sizes,  Prev: Data-Relocatable Image Files,  Up: Image Files

14.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),
and they work with dynamic native code generation.  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

14.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 (*note Data-Relocatable Image Files::), 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

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

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

14.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 ‘#!
/’).

   Most Unix systems (including Linux) support exactly one option after
the binary name.  If that is not enough, you can use the following
trick:

     #! /bin/sh
     : ## ; 0 [if]
     exec gforth -m 10M -d 1M $0 "$@"
     [then]
     ." Hello, world" cr
     bye \ caution: this prevents (further) processing of "$@"

   First this script is interpreted as shell script, which treats the
first two lines as (mostly) comments, then performs the third line,
which invokes gforth with this script (‘$0’) as parameter and its
parameters as additional parameters (‘"$@"’).  Then this script is
interpreted as Forth script, which first defines a colon definition
‘##’, then ignores everything up to ‘[then]’ and finally processes the
following Forth code.  You can also use

     #0 [if]

   in the second line, but this works only in Gforth-0.7.0 and later.

   The ‘gforthmi’ approach is the fastest one, the shell-based one is
slowest (needs to start an additional shell).  An additional advantage
of the shell approach is that it is unnecessary to know where the Gforth
binary resides, as long as it is in the ‘$PATH’.

‘#!’ ( –  ) gforth-0.2 “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

14.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
several 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, but specify your own command-line options, hook into
     ‘process-option’.

   • If you want to have more options in addition to the ones that come
     with Gforth, define words into the ‘options’ vocabulary.

   • If you want to display your own boot message, 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-0.2 “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-0.4 “bootmessage”
   Hook (deferred word) executed right after interpreting the OS
command-line arguments.  Normally prints the Gforth startup message.

   doc-’quit
‘process-option’ ( addr u – true / addr u false  ) gforth-0.7 “process-option”
   Process an option ADDR U, return true, if the option is processed;
unprocessed options are loaded as files throu ‘required’.


File: gforth.info,  Node: Engine,  Next: Cross Compiler,  Prev: Image Files,  Up: Top

15 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
(https://www.complang.tuwien.ac.at/papers/ertl93.ps.Z)’, EuroForth ’93;
M. Anton Ertl, ‘Threaded code variations and optimizations (extended
version) (https://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

15.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)C Extensions.).  Its
labels as values feature (*note Labels as Values: (gcc)Labels as
Values.) makes direct and indirect threading possible, its ‘long long’
type (*note Double-Word Integers: (gcc)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)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

15.2 Threading
==============

GNU C’s labels as values extension (available since ‘gcc-2.0’, *note
Labels as Values: (gcc)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 Standard Forth’s
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

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

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

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

   Use ‘simple-see’ (*note Examining compiled code::) to see the
threaded code of a colon definition.

   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.

   ‘See-code’ (*note Examining compiled code::) shows the threaded code
intermingled with the native code of dynamic superinstructions.  These
days some additional optimizations are applied for the
dynamically-generated native code, so the output of ‘see-code squared’
on ‘gforth-fast’ on one particular AMD64 installation looks like this:

     $7FB689C678C8 dup    1->2
     7FB68990C1B2:   mov     r15,r8
     $7FB689C678D0 *    2->1
     7FB68990C1B5:   imul    r8,r15
     $7FB689C678D8 ;s    1->1
     7FB68990C1B9:   mov     rbx,[r14]
     7FB68990C1BC:   add     r14,$08
     7FB68990C1C0:   mov     rax,[rbx]
     7FB68990C1C3:   jmp     eax

   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

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

15.3 Primitives
===============

* Menu:

* Automatic Generation::
* TOS Optimization::
* Produced code::


File: gforth.info,  Node: Automatic Generation,  Next: TOS Optimization,  Prev: Primitives,  Up: Primitives

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

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

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

15.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)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
(https://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
<https://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: MINOS2,  Prev: Engine,  Up: Top

16 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::


File: gforth.info,  Node: Using the Cross Compiler,  Next: How the Cross Compiler Works,  Prev: Cross Compiler,  Up: Cross Compiler

16.1 Using the Cross Compiler
=============================

The cross compiler uses a language that resembles Forth, but isn’t.  The
main difference is that you can execute Forth code after definition,
while you usually can’t execute the code compiled by cross, because the
code you are compiling is typically for a different computer than the
one you are compiling on.

   The Makefile is already set up to allow you to create kernels for new
architectures with a simple make command.  The generic kernels using the
GCC compiled virtual machine are created in the normal build process
with ‘make’.  To create a embedded Gforth executable for e.g.  the 8086
processor (running on a DOS machine), type

     make kernl-8086.fi

   This will use the machine description from the ‘arch/8086’ directory
to create a new kernel.  A machine file may look like that:

     \ Parameter for target systems                         06oct92py

         4 Constant cell             \ cell size in bytes
         2 Constant cell<<           \ cell shift to bytes
         5 Constant cell>bit         \ cell shift to bits
         8 Constant bits/char        \ bits per character
         8 Constant bits/byte        \ bits per byte [default: 8]
         8 Constant float            \ bytes per float
         8 Constant /maxalign        \ maximum alignment in bytes
     false Constant bigendian        \ byte order
     ( true=big, false=little )

     include machpc.fs               \ feature list

   This part is obligatory for the cross compiler itself, the feature
list is used by the kernel to conditionally compile some features in and
out, depending on whether the target supports these features.

   There are some optional features, if you define your own primitives,
have an assembler, or need special, nonstandard preparation to make the
boot process work.  ‘asm-include’ includes an assembler, ‘prims-include’
includes primitives, and ‘>boot’ prepares for booting.

     : asm-include    ." Include assembler" cr
       s" arch/8086/asm.fs" included ;

     : prims-include  ." Include primitives" cr
       s" arch/8086/prim.fs" included ;

     : >boot          ." Prepare booting" cr
       s" ' boot >body into-forth 1+ !" evaluate ;

   These words are used as sort of macro during the cross compilation in
the file ‘kernel/main.fs’.  Instead of using these macros, it would be
possible — but more complicated — to write a new kernel project file,
too.

   ‘kernel/main.fs’ expects the machine description file name on the
stack; the cross compiler itself (‘cross.fs’) assumes that either
‘mach-file’ leaves a counted string on the stack, or ‘machine-file’
leaves an address, count pair of the filename on the stack.

   The feature list is typically controlled using ‘SetValue’, generic
files that are used by several projects can use ‘DefaultValue’ instead.
Both functions work like ‘Value’, when the value isn’t defined, but
‘SetValue’ works like ‘to’ if the value is defined, and ‘DefaultValue’
doesn’t set anything, if the value is defined.

     \ generic mach file for pc gforth                       03sep97jaw

     true DefaultValue NIL  \ relocating

     >ENVIRON

     true DefaultValue file          \ controls the presence of the
                                     \ file access wordset
     true DefaultValue OS            \ flag to indicate a operating system

     true DefaultValue prims         \ true: primitives are c-code

     true DefaultValue floating      \ floating point wordset is present

     true DefaultValue glocals       \ gforth locals are present
                                     \ will be loaded
     true DefaultValue dcomps        \ double number comparisons

     true DefaultValue hash          \ hashing primitives are loaded/present

     true DefaultValue xconds        \ used together with glocals,
                                     \ special conditionals supporting gforths'
                                     \ local variables
     true DefaultValue header        \ save a header information

     true DefaultValue backtrace     \ enables backtrace code

     false DefaultValue ec
     false DefaultValue crlf

     cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size

     &16 KB          DefaultValue stack-size
     &15 KB &512 +   DefaultValue fstack-size
     &15 KB          DefaultValue rstack-size
     &14 KB &512 +   DefaultValue lstack-size


File: gforth.info,  Node: How the Cross Compiler Works,  Prev: Using the Cross Compiler,  Up: Cross Compiler

16.2 How the Cross Compiler Works
=================================


File: gforth.info,  Node: MINOS2,  Next: Bugs,  Prev: Cross Compiler,  Up: Top

17 MINOS2, a GUI library
************************

* Menu:

* MINOS2 object framework::
* MINOS2 tutorial::


File: gforth.info,  Node: MINOS2 object framework,  Next: MINOS2 tutorial,  Prev: MINOS2,  Up: MINOS2

17.1 MINOS2 object framework
============================

* Menu:

* actor methods::
* widget methods::

MINOS2 is a GUI library, written in ‘mini-oof2.fs’’s object model.  It
has two main class hierarchies:

‘actor’ ( – class  ) minos2 “actor”
   class for the actions bound to a component.

‘widget’ ( – class  ) minos2 “widget”
   class for visual components


File: gforth.info,  Node: actor methods,  Next: widget methods,  Prev: MINOS2 object framework,  Up: MINOS2 object framework

17.1.1 ‘actor’ methods:
-----------------------

‘caller-w’ ( – optr  ) minos2 “caller-w”
   pointer back to the widget embedding the actor

‘active-w’ ( – optr  ) minos2 “active-w”
   pointer to the active subwidget embedding the actor

‘act-name$’ ( – addr u  ) minos2 “act-name-string”
   Debugging aid: name of the actor

‘clicked’ ( rx ry bmask n –  ) minos2 “clicked”
   processed clicks

‘scrolled’ ( axis dir –  ) minos2 “scrolled”
   process scrolling

‘touchdown’ ( $rxy*n bmask –  ) minos2 “touchdown”
   raw click down

‘touchup’ ( $rxy*n bmask –  ) minos2 “touchup”
   raw click up

‘ukeyed’ ( addr u –  ) minos2 “ukeyed”
   key event, string of printable unicode characters

‘ekeyed’ ( ekey –  ) minos2 “ekeyed”
   key event, non-printable key

‘?inside’ ( rx ry – act / 0  ) minos2 “query-inside”
   check if coordinates are inside the widget

‘focus’ ( –  ) minos2 “focus”
   put widget into focus

‘defocus’ ( –  ) minos2 “defocus”
   put widget out of focus

‘entered’ ( –  ) minos2 “entered”
   react on cursor entering the widget area

‘left’ ( –  ) minos2 “left”
   react on cursor leaving the widget area

‘show’ ( –  ) minos2 “show”
   widget is shown

‘hide’ ( –  ) minos2 “hide”
   widget is hidden

‘get’ ( – something  ) minos2 “get”
   getter for the value behind the widget

‘set’ ( something –  ) minos2 “set”
   setter for the value behind the widget

‘show-you’ ( –  ) minos2 “show-you”
   make widget visible


File: gforth.info,  Node: widget methods,  Prev: actor methods,  Up: MINOS2 object framework

17.1.2 ‘widget’ methods:
------------------------

‘parent-w’ ( – optr  ) minos2 “parent-w”
   pointer to parent widget

‘act’ ( – optr  ) minos2 “act”
   pointer to actor

‘name$’ ( – addr u  ) minos2 “name-string”
   Widget name for debugging and searching

‘x’ ( – r  ) minos2 “x”
   widget x coordinate

‘y’ ( – r  ) minos2 “y”
   widget y coordinate

‘w’ ( – r  ) minos2 “w”
   widget width

‘h’ ( – r  ) minos2 “h”
   widget height above baseline

‘d’ ( – r  ) minos2 “d”
   widget depth below baseline

‘gap’ ( – r  ) minos2 “gap”
   gap between lines

‘baseline’ ( – r  ) minos2 “baseline”
   minimun skip per line

‘kerning’ ( – r  ) minos2 “kerning”
   add kerning

‘raise’ ( – r  ) minos2 “raise”
   raise/lower box

‘border’ ( – r  ) minos2 “border”
   surrounding border, all directions

‘borderv’ ( – r  ) minos2 “borderv”
   vertical border offset

‘bordert’ ( – r  ) minos2 “bordert”
   top border offset

‘borderl’ ( – r  ) minos2 “borderl”
   left border offset

‘w-color’ ( – r  ) minos2 “w-color”
   widget color index (into color map), if any

‘draw-init’ ( –  ) minos2 “draw-init”
   init draw

‘draw’ ( –  ) minos2 “draw”
   draw widget

‘split’ ( firstflag rstart1 rx – o rstart2  ) minos2 “split”
   split a widget into parts for typesetting paragraphs

‘lastfit’ ( –  ) minos2 “lastfit”
   fit last widget element in a box

‘hglue’ ( – rtyp rsub radd  ) minos2 “hglue”
   calculate horizontal glue

‘dglue’ ( – rtyp rsub radd  ) minos2 “dglue”
   calculate vertical glue below baseline

‘vglue’ ( – rtyp rsub radd  ) minos2 “vglue”
   calculate vertical glue above baseline

‘hglue@’ ( – rtyp rsub radd  ) minos2 “hglue-fetch”
   cached variant of ‘hglue’

‘dglue@’ ( – rtyp rsub radd  ) minos2 “dglue-fetch”
   cached variant of ‘dglue’

‘vglue@’ ( – rtyp rsub radd  ) minos2 “vglue-fetch”
   cached variant of ‘vglue’

‘xywh’ ( – rx0 ry0 rw rh  ) minos2 “xywh”
   widget bounding box, starting at the top left corner

‘xywhd’ ( – rx ry rw rh rd  ) minos2 “xywhd”
   widget bounding box, starting at the left baseline point

‘!resize’ ( rx ry rw rh rd –  ) minos2 “store-resize”
   resize a widget

‘!size’ ( –  ) minos2 “store-size”
   let the widget self-determine its size

‘dispose-widget’ ( –  ) minos2 “dispose-widget”
   get rid of a widget

‘.widget’ ( –  ) minos2 “print-widget”
   debugging: Print informations about the widget

‘par-split’ ( rw –  ) minos2 “par-split”
   split a paragraph by width RW

‘resized’ ( –  ) minos2 “resized”
   widget is resized

   Components are composed using a boxes&glue model similar to LaTeX,
including paragraph breaking.  For the sake of simplicity and
portability, MINOS2 only supports a single window, and uses OpenGL for
rendering.

   MINOS2 furthermore supports animations with the ‘animation’ class.  A
color index texture is used for different color schemes, and transition
between neighboring schemes can also be animated.

‘>animate’ ( rdelta addr xt –  ) minos2 “to-animate”
   create a new animation, calling XT with stack effect ‘( addr r0..1 --
)’ repeatedly, until the RDELTA timeout expired; last call is always
with argument 1E for the time.

   You can create named color indexes and assign them color values for
the currently active color scheme.

‘color:’ ( rgba "name" –  ) minos2 “color:”
   Create a (possibly shared) color index initialized with RGBA

‘new-color:’ ( rgba "name" –  ) minos2 “new-color:”
   Create a unique color index initialized with RGBA

‘text-color:’ ( rgba "name" –  ) minos2 “text-color:”
   Create a unique text color index initialized with RGBA, the
corresponding emoji color is set to white.

‘text-emoji-color:’ ( rgbatext rgbaemoji "name" –  ) minos2 “text-emoji-color:”
   Create a unique text color index initialized with RGBATEXT, the
corresponding emoji color is set to RGBAEMOJI.

‘fade-color:’ ( rgba1 rgba2 "name" –  ) minos2 “fade-color:”
   Create a unique pair of text color index initialized with RGBA1 and
RGBA2, the corresponding emoji color is set to white.  By slowly
shifting the index from one to the next index, the object will shift its
color using a linear interpolation when redrawn.

‘text-emoji-fade-color:’ ( rgbatext1 ~2 rgbaemoji1 ~2 "name" –  ) minos2 “text-emoji-fade-color:”
   Create a unique pair of text color index initialized with RGBATEXT1
and ~2, the corresponding emoji color pair is set to RGBAEMOJI1 to ~2.
By slowly shifting the index from one to the next index, the object will
shift its color using a linear interpolation when redrawn.

‘re-color’ ( rgba "name" –  ) minos2 “re-color”
   assign the named color index "NAME" in the current color scheme with
the value RGBA.

‘re-text-color’ ( rgba "name" –  ) minos2 “re-text-color”
   assign the named text color index "NAME" in the current color scheme
with the value RGBA.

‘re-emoji-color’ ( rgbatext rgbaemoji "name" –  ) minos2 “re-emoji-color”
   assign the named text and emoji color index "NAME" in the current
color scheme with the value RGBATEXT and RGBAEMOJI.

‘re-fade-color’ ( rgba1 rgba2 "name" –  ) minos2 “re-fade-color”
   assign the named color index pair "NAME" in the current color scheme
with the value RGBA1 and RGBA2.

‘re-text-emoji-fade-color’ ( rgbatext1 ~2 rgbaemoji1 ~2 "name" –  ) minos2 “re-text-emoji-fade-color”
   assign the named color index pair "NAME" in the current color scheme
with the value RGBATEXT1 and ~2 resp.  RGBAEMOJI1 and ~2.

   For a number of specific objects, there are early bound methods, that
only work on these objects

   • Viewport

     ‘vp-top’ ( o:vp –  ) minos2 “vp-top”
     scroll viewport to top

     ‘vp-bottom’ ( o:vp –  ) minos2 “vp-bottom”
     scroll viewport to bottom

     ‘vp-left’ ( o:vp –  ) minos2 “vp-left”
     scroll viewport to left

     ‘vp-right’ ( o:vp –  ) minos2 “vp-right”
     scroll viewport to right

     ‘vp-reslide’ ( o:vp –  ) minos2 “vp-reslide”
     Adjust the sliders of a viewport after scrolling

     ‘vp-needed’ ( xt –  ) minos2 “vp-needed”
     collect needs in viewport’s vp-need


File: gforth.info,  Node: MINOS2 tutorial,  Prev: MINOS2 object framework,  Up: MINOS2

17.2 MINOS2 tutorial
====================

Tutorials are small files, each showing a bit of MINOS2.  For the common
framework, the file ‘minos2/tutorial/tutorial.fs’ needs to be loaded
first; all other tutorials in the command line argument are included
from within that file.  Scroll wheel or previous/next mouse buttons as
well as clicking on the left or right edge of the window allow
navigation between the different tutorials loaded.

   I.e.  to load the buttons tutorial, you start Gforth with

     gforth minos2/tutorial/tutorial.fs buttons.fs

   Available tutorials:

   • ‘buttons.fs’: Clickable buttons

   • ‘plots.fs’: Plot functions

   • ‘markdown.fs’: Markdown document viewer

   • ‘screenshot.fs’: Screenshot function


File: gforth.info,  Node: Bugs,  Next: Origin,  Prev: MINOS2,  Up: Top

Appendix A Bugs
***************

Known bugs are described in the file ‘BUGS’ in the Gforth distribution.

   If you find a bug, please submit a bug report through
<https://savannah.gnu.org/bugs/?func=addbug&group=gforth>.

   • A program (or a sequence of keyboard commands) that reproduces the
     bug.
   • A description of what you think constitutes the buggy behaviour.
   • The Gforth version used (it is announced at the start of an
     interactive Gforth session).
   • The machine and operating system (on Unix systems ‘uname -a’ will
     report this information).
   • The installation options (you can find the configure options at the
     start of ‘config.status’) and configuration (‘configure’ output or
     ‘config.cache’).
   • A complete list of changes (if any) you (or your installer) have
     made to the Gforth sources.

   For a thorough guide on reporting bugs read *note How to Report Bugs:
(gcc)Bug Reporting.


File: gforth.info,  Node: Origin,  Next: Forth-related information,  Prev: Bugs,  Up: Top

Appendix B Authors and Ancestors of Gforth
******************************************

B.1 Authors and Contributors
============================

The Gforth project was started in mid-1992 by Bernd Paysan and Anton
Ertl.  The third major author was Jens Wilke.  Neal Crook contributed a
lot to the manual.  Assemblers and disassemblers were contributed by
Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
Lennart Benschop (who was one of Gforth’s first users, in mid-1993) and
Stuart Ramsden inspired us with their continuous feedback.  Lennart
Benshop contributed ‘glosgen.fs’, while Stuart Ramsden has been working
on automatic support for calling C libraries.  Helpful comments also
came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel
Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce
Hoyt, Robert Epprecht, Dennis Ruffer and David N. Williams.  Since the
release of Gforth-0.2.1 there were also helpful comments from many
others; thank you all, sorry for not listing you here (but digging
through my mailbox to extract your names is on my to-do list).

   Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
and autoconf, among others), and to the creators of the Internet: Gforth
was developed across the Internet, and its authors did not meet
physically for the first 4 years of development.

B.2 Pedigree
============

Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
significant part of the design of Gforth was prescribed by Standard
Forth.

   Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an
unreleased 32 bit native code version of VolksForth for the Atari ST,
written mostly by Dietrich Weineck.

   VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
the mid-80s and ported to the Atari ST in 1986.  It descends from
fig-Forth.

   A team led by Bill Ragsdale implemented fig-Forth on many processors
in 1979.  Robert Selzer and Bill Ragsdale developed the original
implementation of fig-Forth for the 6502 based on microForth.

   The principal architect of microForth was Dean Sanderson.  microForth
was FORTH, Inc.’s first off-the-shelf product.  It was developed in 1976
for the 1802, and subsequently implemented on the 8080, the 6800 and the
Z80.

   All earlier Forth systems were custom-made, usually by Charles Moore,
who discovered (as he puts it) Forth during the late 60s.  The first
full Forth existed in 1971.

   A part of the information in this section comes from ‘The Evolution
of Forth (https://www.forth.com/resources/evolution/index.html)’ by
Elizabeth D. Rather, Donald R. Colburn and Charles H. Moore, presented
at the HOPL-II conference and preprinted in SIGPLAN Notices 28(3), 1993.
You can find more historical and genealogical information about Forth
there.  For a more general (and graphical) Forth family tree look see
‘<https://www.complang.tuwien.ac.at/forth/family-tree/>, Forth Family
Tree and Timeline’.


File: gforth.info,  Node: Forth-related information,  Next: Licenses,  Prev: Origin,  Up: Top

Appendix C Other Forth-related information
******************************************

There is an active news group (comp.lang.forth) discussing Forth
(including Gforth) and Forth-related issues.  Its FAQs
(https://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html)
(frequently asked questions and their answers) contains a lot of
information on Forth.  You should read it before posting to
comp.lang.forth.

   The Forth standard is most usable in its HTML form
(https://forth-standard.org/).


File: gforth.info,  Node: Licenses,  Next: Word Index,  Prev: Forth-related information,  Up: Top

Appendix D Licenses
*******************

* Menu:

* GNU Free Documentation License::  License for copying this manual.
* Copying::                     GPL (for copying this software).


File: gforth.info,  Node: GNU Free Documentation License,  Next: Copying,  Prev: Licenses,  Up: Licenses

D.1 GNU Free Documentation License
==================================

                      Version 1.2, November 2002

     Copyright © 2000,2001,2002 Free Software Foundation, Inc.
     59 Temple Place, Suite 330, Boston, MA  02111-1307, USA

     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.

  0. PREAMBLE

     The purpose of this License is to make a manual, textbook, or other
     functional and useful document “free” in the sense of freedom: to
     assure everyone the effective freedom to copy and redistribute it,
     with or without modifying it, either commercially or
     noncommercially.  Secondarily, this License preserves for the
     author and publisher a way to get credit for their work, while not
     being considered responsible for modifications made by others.

     This License is a kind of “copyleft”, which means that derivative
     works of the document must themselves be free in the same sense.
     It complements the GNU General Public License, which is a copyleft
     license designed for free software.

     We have designed this License in order to use it for manuals for
     free software, because free software needs free documentation: a
     free program should come with manuals providing the same freedoms
     that the software does.  But this License is not limited to
     software manuals; it can be used for any textual work, regardless
     of subject matter or whether it is published as a printed book.  We
     recommend this License principally for works whose purpose is
     instruction or reference.

  1. APPLICABILITY AND DEFINITIONS

     This License applies to any manual or other work, in any medium,
     that contains a notice placed by the copyright holder saying it can
     be distributed under the terms of this License.  Such a notice
     grants a world-wide, royalty-free license, unlimited in duration,
     to use that work under the conditions stated herein.  The
     “Document”, below, refers to any such manual or work.  Any member
     of the public is a licensee, and is addressed as “you”.  You accept
     the license if you copy, modify or distribute the work in a way
     requiring permission under copyright law.

     A “Modified Version” of the Document means any work containing the
     Document or a portion of it, either copied verbatim, or with
     modifications and/or translated into another language.

     A “Secondary Section” is a named appendix or a front-matter section
     of the Document that deals exclusively with the relationship of the
     publishers or authors of the Document to the Document’s overall
     subject (or to related matters) and contains nothing that could
     fall directly within that overall subject.  (Thus, if the Document
     is in part a textbook of mathematics, a Secondary Section may not
     explain any mathematics.)  The relationship could be a matter of
     historical connection with the subject or with related matters, or
     of legal, commercial, philosophical, ethical or political position
     regarding them.

     The “Invariant Sections” are certain Secondary Sections whose
     titles are designated, as being those of Invariant Sections, in the
     notice that says that the Document is released under this License.
     If a section does not fit the above definition of Secondary then it
     is not allowed to be designated as Invariant.  The Document may
     contain zero Invariant Sections.  If the Document does not identify
     any Invariant Sections then there are none.

     The “Cover Texts” are certain short passages of text that are
     listed, as Front-Cover Texts or Back-Cover Texts, in the notice
     that says that the Document is released under this License.  A
     Front-Cover Text may be at most 5 words, and a Back-Cover Text may
     be at most 25 words.

     A “Transparent” copy of the Document means a machine-readable copy,
     represented in a format whose specification is available to the
     general public, that is suitable for revising the document
     straightforwardly with generic text editors or (for images composed
     of pixels) generic paint programs or (for drawings) some widely
     available drawing editor, and that is suitable for input to text
     formatters or for automatic translation to a variety of formats
     suitable for input to text formatters.  A copy made in an otherwise
     Transparent file format whose markup, or absence of markup, has
     been arranged to thwart or discourage subsequent modification by
     readers is not Transparent.  An image format is not Transparent if
     used for any substantial amount of text.  A copy that is not
     “Transparent” is called “Opaque”.

     Examples of suitable formats for Transparent copies include plain
     ASCII without markup, Texinfo input format, LaTeX input format,
     SGML or XML using a publicly available DTD, and standard-conforming
     simple HTML, PostScript or PDF designed for human modification.
     Examples of transparent image formats include PNG, XCF and JPG.
     Opaque formats include proprietary formats that can be read and
     edited only by proprietary word processors, SGML or XML for which
     the DTD and/or processing tools are not generally available, and
     the machine-generated HTML, PostScript or PDF produced by some word
     processors for output purposes only.

     The “Title Page” means, for a printed book, the title page itself,
     plus such following pages as are needed to hold, legibly, the
     material this License requires to appear in the title page.  For
     works in formats which do not have any title page as such, “Title
     Page” means the text near the most prominent appearance of the
     work’s title, preceding the beginning of the body of the text.

     A section “Entitled XYZ” means a named subunit of the Document
     whose title either is precisely XYZ or contains XYZ in parentheses
     following text that translates XYZ in another language.  (Here XYZ
     stands for a specific section name mentioned below, such as
     “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.)
     To “Preserve the Title” of such a section when you modify the
     Document means that it remains a section “Entitled XYZ” according
     to this definition.

     The Document may include Warranty Disclaimers next to the notice
     which states that this License applies to the Document.  These
     Warranty Disclaimers are considered to be included by reference in
     this License, but only as regards disclaiming warranties: any other
     implication that these Warranty Disclaimers may have is void and
     has no effect on the meaning of this License.

  2. VERBATIM COPYING

     You may copy and distribute the Document in any medium, either
     commercially or noncommercially, provided that this License, the
     copyright notices, and the license notice saying this License
     applies to the Document are reproduced in all copies, and that you
     add no other conditions whatsoever to those of this License.  You
     may not use technical measures to obstruct or control the reading
     or further copying of the copies you make or distribute.  However,
     you may accept compensation in exchange for copies.  If you
     distribute a large enough number of copies you must also follow the
     conditions in section 3.

     You may also lend copies, under the same conditions stated above,
     and you may publicly display copies.

  3. COPYING IN QUANTITY

     If you publish printed copies (or copies in media that commonly
     have printed covers) of the Document, numbering more than 100, and
     the Document’s license notice requires Cover Texts, you must
     enclose the copies in covers that carry, clearly and legibly, all
     these Cover Texts: Front-Cover Texts on the front cover, and
     Back-Cover Texts on the back cover.  Both covers must also clearly
     and legibly identify you as the publisher of these copies.  The
     front cover must present the full title with all words of the title
     equally prominent and visible.  You may add other material on the
     covers in addition.  Copying with changes limited to the covers, as
     long as they preserve the title of the Document and satisfy these
     conditions, can be treated as verbatim copying in other respects.

     If the required texts for either cover are too voluminous to fit
     legibly, you should put the first ones listed (as many as fit
     reasonably) on the actual cover, and continue the rest onto
     adjacent pages.

     If you publish or distribute Opaque copies of the Document
     numbering more than 100, you must either include a machine-readable
     Transparent copy along with each Opaque copy, or state in or with
     each Opaque copy a computer-network location from which the general
     network-using public has access to download using public-standard
     network protocols a complete Transparent copy of the Document, free
     of added material.  If you use the latter option, you must take
     reasonably prudent steps, when you begin distribution of Opaque
     copies in quantity, to ensure that this Transparent copy will
     remain thus accessible at the stated location until at least one
     year after the last time you distribute an Opaque copy (directly or
     through your agents or retailers) of that edition to the public.

     It is requested, but not required, that you contact the authors of
     the Document well before redistributing any large number of copies,
     to give them a chance to provide you with an updated version of the
     Document.

  4. MODIFICATIONS

     You may copy and distribute a Modified Version of the Document
     under the conditions of sections 2 and 3 above, provided that you
     release the Modified Version under precisely this License, with the
     Modified Version filling the role of the Document, thus licensing
     distribution and modification of the Modified Version to whoever
     possesses a copy of it.  In addition, you must do these things in
     the Modified Version:

       A. Use in the Title Page (and on the covers, if any) a title
          distinct from that of the Document, and from those of previous
          versions (which should, if there were any, be listed in the
          History section of the Document).  You may use the same title
          as a previous version if the original publisher of that
          version gives permission.

       B. List on the Title Page, as authors, one or more persons or
          entities responsible for authorship of the modifications in
          the Modified Version, together with at least five of the
          principal authors of the Document (all of its principal
          authors, if it has fewer than five), unless they release you
          from this requirement.

       C. State on the Title page the name of the publisher of the
          Modified Version, as the publisher.

       D. Preserve all the copyright notices of the Document.

       E. Add an appropriate copyright notice for your modifications
          adjacent to the other copyright notices.

       F. Include, immediately after the copyright notices, a license
          notice giving the public permission to use the Modified
          Version under the terms of this License, in the form shown in
          the Addendum below.

       G. Preserve in that license notice the full lists of Invariant
          Sections and required Cover Texts given in the Document’s
          license notice.

       H. Include an unaltered copy of this License.

       I. Preserve the section Entitled “History”, Preserve its Title,
          and add to it an item stating at least the title, year, new
          authors, and publisher of the Modified Version as given on the
          Title Page.  If there is no section Entitled “History” in the
          Document, create one stating the title, year, authors, and
          publisher of the Document as given on its Title Page, then add
          an item describing the Modified Version as stated in the
          previous sentence.

       J. Preserve the network location, if any, given in the Document
          for public access to a Transparent copy of the Document, and
          likewise the network locations given in the Document for
          previous versions it was based on.  These may be placed in the
          “History” section.  You may omit a network location for a work
          that was published at least four years before the Document
          itself, or if the original publisher of the version it refers
          to gives permission.

       K. For any section Entitled “Acknowledgements” or “Dedications”,
          Preserve the Title of the section, and preserve in the section
          all the substance and tone of each of the contributor
          acknowledgements and/or dedications given therein.

       L. Preserve all the Invariant Sections of the Document, unaltered
          in their text and in their titles.  Section numbers or the
          equivalent are not considered part of the section titles.

       M. Delete any section Entitled “Endorsements”.  Such a section
          may not be included in the Modified Version.

       N. Do not retitle any existing section to be Entitled
          “Endorsements” or to conflict in title with any Invariant
          Section.

       O. Preserve any Warranty Disclaimers.

     If the Modified Version includes new front-matter sections or
     appendices that qualify as Secondary Sections and contain no
     material copied from the Document, you may at your option designate
     some or all of these sections as invariant.  To do this, add their
     titles to the list of Invariant Sections in the Modified Version’s
     license notice.  These titles must be distinct from any other
     section titles.

     You may add a section Entitled “Endorsements”, provided it contains
     nothing but endorsements of your Modified Version by various
     parties—for example, statements of peer review or that the text has
     been approved by an organization as the authoritative definition of
     a standard.

     You may add a passage of up to five words as a Front-Cover Text,
     and a passage of up to 25 words as a Back-Cover Text, to the end of
     the list of Cover Texts in the Modified Version.  Only one passage
     of Front-Cover Text and one of Back-Cover Text may be added by (or
     through arrangements made by) any one entity.  If the Document
     already includes a cover text for the same cover, previously added
     by you or by arrangement made by the same entity you are acting on
     behalf of, you may not add another; but you may replace the old
     one, on explicit permission from the previous publisher that added
     the old one.

     The author(s) and publisher(s) of the Document do not by this
     License give permission to use their names for publicity for or to
     assert or imply endorsement of any Modified Version.

  5. COMBINING DOCUMENTS

     You may combine the Document with other documents released under
     this License, under the terms defined in section 4 above for
     modified versions, provided that you include in the combination all
     of the Invariant Sections of all of the original documents,
     unmodified, and list them all as Invariant Sections of your
     combined work in its license notice, and that you preserve all
     their Warranty Disclaimers.

     The combined work need only contain one copy of this License, and
     multiple identical Invariant Sections may be replaced with a single
     copy.  If there are multiple Invariant Sections with the same name
     but different contents, make the title of each such section unique
     by adding at the end of it, in parentheses, the name of the
     original author or publisher of that section if known, or else a
     unique number.  Make the same adjustment to the section titles in
     the list of Invariant Sections in the license notice of the
     combined work.

     In the combination, you must combine any sections Entitled
     “History” in the various original documents, forming one section
     Entitled “History”; likewise combine any sections Entitled
     “Acknowledgements”, and any sections Entitled “Dedications”.  You
     must delete all sections Entitled “Endorsements.”

  6. COLLECTIONS OF DOCUMENTS

     You may make a collection consisting of the Document and other
     documents released under this License, and replace the individual
     copies of this License in the various documents with a single copy
     that is included in the collection, provided that you follow the
     rules of this License for verbatim copying of each of the documents
     in all other respects.

     You may extract a single document from such a collection, and
     distribute it individually under this License, provided you insert
     a copy of this License into the extracted document, and follow this
     License in all other respects regarding verbatim copying of that
     document.

  7. AGGREGATION WITH INDEPENDENT WORKS

     A compilation of the Document or its derivatives with other
     separate and independent documents or works, in or on a volume of a
     storage or distribution medium, is called an “aggregate” if the
     copyright resulting from the compilation is not used to limit the
     legal rights of the compilation’s users beyond what the individual
     works permit.  When the Document is included in an aggregate, this
     License does not apply to the other works in the aggregate which
     are not themselves derivative works of the Document.

     If the Cover Text requirement of section 3 is applicable to these
     copies of the Document, then if the Document is less than one half
     of the entire aggregate, the Document’s Cover Texts may be placed
     on covers that bracket the Document within the aggregate, or the
     electronic equivalent of covers if the Document is in electronic
     form.  Otherwise they must appear on printed covers that bracket
     the whole aggregate.

  8. TRANSLATION

     Translation is considered a kind of modification, so you may
     distribute translations of the Document under the terms of section
     4.  Replacing Invariant Sections with translations requires special
     permission from their copyright holders, but you may include
     translations of some or all Invariant Sections in addition to the
     original versions of these Invariant Sections.  You may include a
     translation of this License, and all the license notices in the
     Document, and any Warranty Disclaimers, provided that you also
     include the original English version of this License and the
     original versions of those notices and disclaimers.  In case of a
     disagreement between the translation and the original version of
     this License or a notice or disclaimer, the original version will
     prevail.

     If a section in the Document is Entitled “Acknowledgements”,
     “Dedications”, or “History”, the requirement (section 4) to
     Preserve its Title (section 1) will typically require changing the
     actual title.

  9. TERMINATION

     You may not copy, modify, sublicense, or distribute the Document
     except as expressly provided for under this License.  Any other
     attempt to copy, modify, sublicense or distribute the Document is
     void, and will automatically terminate your rights under this
     License.  However, parties who have received copies, or rights,
     from you under this License will not have their licenses terminated
     so long as such parties remain in full compliance.

  10. FUTURE REVISIONS OF THIS LICENSE

     The Free Software Foundation may publish new, revised versions of
     the GNU Free Documentation License from time to time.  Such new
     versions will be similar in spirit to the present version, but may
     differ in detail to address new problems or concerns.  See
     <http://www.gnu.org/copyleft/>.

     Each version of the License is given a distinguishing version
     number.  If the Document specifies that a particular numbered
     version of this License “or any later version” applies to it, you
     have the option of following the terms and conditions either of
     that specified version or of any later version that has been
     published (not as a draft) by the Free Software Foundation.  If the
     Document does not specify a version number of this License, you may
     choose any version ever published (not as a draft) by the Free
     Software Foundation.

D.1.1 ADDENDUM: How to use this License for your documents
----------------------------------------------------------

To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and license
notices just after the title page:

       Copyright (C)  YEAR  YOUR NAME.
       Permission is granted to copy, distribute and/or modify this document
       under the terms of the GNU Free Documentation License, Version 1.2
       or any later version published by the Free Software Foundation;
       with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
       Texts.  A copy of the license is included in the section entitled ``GNU
       Free Documentation License''.

   If you have Invariant Sections, Front-Cover Texts and Back-Cover
Texts, replace the “with...Texts.” line with this:

         with the Invariant Sections being LIST THEIR TITLES, with
         the Front-Cover Texts being LIST, and with the Back-Cover Texts
         being LIST.

   If you have Invariant Sections without Cover Texts, or some other
combination of the three, merge those two alternatives to suit the
situation.

   If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of free
software license, such as the GNU General Public License, to permit
their use in free software.


File: gforth.info,  Node: Copying,  Prev: GNU Free Documentation License,  Up: Licenses

D.2 GNU GENERAL PUBLIC LICENSE
==============================

                        Version 3, 29 June 2007

     Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>

     Everyone is permitted to copy and distribute verbatim copies of this
     license document, but changing it is not allowed.

Preamble
========

The GNU General Public License is a free, copyleft license for software
and other kinds of works.

   The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program—to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

   When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

   To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

   For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

   Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

   For the developers’ and authors’ protection, the GPL clearly explains
that there is no warranty for this free software.  For both users’ and
authors’ sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

   Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users’ freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

   Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

   The precise terms and conditions for copying, distribution and
modification follow.

TERMS AND CONDITIONS
====================

  0. Definitions.

     “This License” refers to version 3 of the GNU General Public
     License.

     “Copyright” also means copyright-like laws that apply to other
     kinds of works, such as semiconductor masks.

     “The Program” refers to any copyrightable work licensed under this
     License.  Each licensee is addressed as “you”.  “Licensees” and
     “recipients” may be individuals or organizations.

     To “modify” a work means to copy from or adapt all or part of the
     work in a fashion requiring copyright permission, other than the
     making of an exact copy.  The resulting work is called a “modified
     version” of the earlier work or a work “based on” the earlier work.

     A “covered work” means either the unmodified Program or a work
     based on the Program.

     To “propagate” a work means to do anything with it that, without
     permission, would make you directly or secondarily liable for
     infringement under applicable copyright law, except executing it on
     a computer or modifying a private copy.  Propagation includes
     copying, distribution (with or without modification), making
     available to the public, and in some countries other activities as
     well.

     To “convey” a work means any kind of propagation that enables other
     parties to make or receive copies.  Mere interaction with a user
     through a computer network, with no transfer of a copy, is not
     conveying.

     An interactive user interface displays “Appropriate Legal Notices”
     to the extent that it includes a convenient and prominently visible
     feature that (1) displays an appropriate copyright notice, and (2)
     tells the user that there is no warranty for the work (except to
     the extent that warranties are provided), that licensees may convey
     the work under this License, and how to view a copy of this
     License.  If the interface presents a list of user commands or
     options, such as a menu, a prominent item in the list meets this
     criterion.

  1. Source Code.

     The “source code” for a work means the preferred form of the work
     for making modifications to it.  “Object code” means any non-source
     form of a work.

     A “Standard Interface” means an interface that either is an
     official standard defined by a recognized standards body, or, in
     the case of interfaces specified for a particular programming
     language, one that is widely used among developers working in that
     language.

     The “System Libraries” of an executable work include anything,
     other than the work as a whole, that (a) is included in the normal
     form of packaging a Major Component, but which is not part of that
     Major Component, and (b) serves only to enable use of the work with
     that Major Component, or to implement a Standard Interface for
     which an implementation is available to the public in source code
     form.  A “Major Component”, in this context, means a major
     essential component (kernel, window system, and so on) of the
     specific operating system (if any) on which the executable work
     runs, or a compiler used to produce the work, or an object code
     interpreter used to run it.

     The “Corresponding Source” for a work in object code form means all
     the source code needed to generate, install, and (for an executable
     work) run the object code and to modify the work, including scripts
     to control those activities.  However, it does not include the
     work’s System Libraries, or general-purpose tools or generally
     available free programs which are used unmodified in performing
     those activities but which are not part of the work.  For example,
     Corresponding Source includes interface definition files associated
     with source files for the work, and the source code for shared
     libraries and dynamically linked subprograms that the work is
     specifically designed to require, such as by intimate data
     communication or control flow between those subprograms and other
     parts of the work.

     The Corresponding Source need not include anything that users can
     regenerate automatically from other parts of the Corresponding
     Source.

     The Corresponding Source for a work in source code form is that
     same work.

  2. Basic Permissions.

     All rights granted under this License are granted for the term of
     copyright on the Program, and are irrevocable provided the stated
     conditions are met.  This License explicitly affirms your unlimited
     permission to run the unmodified Program.  The output from running
     a covered work is covered by this License only if the output, given
     its content, constitutes a covered work.  This License acknowledges
     your rights of fair use or other equivalent, as provided by
     copyright law.

     You may make, run and propagate covered works that you do not
     convey, without conditions so long as your license otherwise
     remains in force.  You may convey covered works to others for the
     sole purpose of having them make modifications exclusively for you,
     or provide you with facilities for running those works, provided
     that you comply with the terms of this License in conveying all
     material for which you do not control copyright.  Those thus making
     or running the covered works for you must do so exclusively on your
     behalf, under your direction and control, on terms that prohibit
     them from making any copies of your copyrighted material outside
     their relationship with you.

     Conveying under any other circumstances is permitted solely under
     the conditions stated below.  Sublicensing is not allowed; section
     10 makes it unnecessary.

  3. Protecting Users’ Legal Rights From Anti-Circumvention Law.

     No covered work shall be deemed part of an effective technological
     measure under any applicable law fulfilling obligations under
     article 11 of the WIPO copyright treaty adopted on 20 December
     1996, or similar laws prohibiting or restricting circumvention of
     such measures.

     When you convey a covered work, you waive any legal power to forbid
     circumvention of technological measures to the extent such
     circumvention is effected by exercising rights under this License
     with respect to the covered work, and you disclaim any intention to
     limit operation or modification of the work as a means of
     enforcing, against the work’s users, your or third parties’ legal
     rights to forbid circumvention of technological measures.

  4. Conveying Verbatim Copies.

     You may convey verbatim copies of the Program’s source code as you
     receive it, in any medium, provided that you conspicuously and
     appropriately publish on each copy an appropriate copyright notice;
     keep intact all notices stating that this License and any
     non-permissive terms added in accord with section 7 apply to the
     code; keep intact all notices of the absence of any warranty; and
     give all recipients a copy of this License along with the Program.

     You may charge any price or no price for each copy that you convey,
     and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

     You may convey a work based on the Program, or the modifications to
     produce it from the Program, in the form of source code under the
     terms of section 4, provided that you also meet all of these
     conditions:

       a. The work must carry prominent notices stating that you
          modified it, and giving a relevant date.

       b. The work must carry prominent notices stating that it is
          released under this License and any conditions added under
          section 7.  This requirement modifies the requirement in
          section 4 to “keep intact all notices”.

       c. You must license the entire work, as a whole, under this
          License to anyone who comes into possession of a copy.  This
          License will therefore apply, along with any applicable
          section 7 additional terms, to the whole of the work, and all
          its parts, regardless of how they are packaged.  This License
          gives no permission to license the work in any other way, but
          it does not invalidate such permission if you have separately
          received it.

       d. If the work has interactive user interfaces, each must display
          Appropriate Legal Notices; however, if the Program has
          interactive interfaces that do not display Appropriate Legal
          Notices, your work need not make them do so.

     A compilation of a covered work with other separate and independent
     works, which are not by their nature extensions of the covered
     work, and which are not combined with it such as to form a larger
     program, in or on a volume of a storage or distribution medium, is
     called an “aggregate” if the compilation and its resulting
     copyright are not used to limit the access or legal rights of the
     compilation’s users beyond what the individual works permit.
     Inclusion of a covered work in an aggregate does not cause this
     License to apply to the other parts of the aggregate.

  6. Conveying Non-Source Forms.

     You may convey a covered work in object code form under the terms
     of sections 4 and 5, provided that you also convey the
     machine-readable Corresponding Source under the terms of this
     License, in one of these ways:

       a. Convey the object code in, or embodied in, a physical product
          (including a physical distribution medium), accompanied by the
          Corresponding Source fixed on a durable physical medium
          customarily used for software interchange.

       b. Convey the object code in, or embodied in, a physical product
          (including a physical distribution medium), accompanied by a
          written offer, valid for at least three years and valid for as
          long as you offer spare parts or customer support for that
          product model, to give anyone who possesses the object code
          either (1) a copy of the Corresponding Source for all the
          software in the product that is covered by this License, on a
          durable physical medium customarily used for software
          interchange, for a price no more than your reasonable cost of
          physically performing this conveying of source, or (2) access
          to copy the Corresponding Source from a network server at no
          charge.

       c. Convey individual copies of the object code with a copy of the
          written offer to provide the Corresponding Source.  This
          alternative is allowed only occasionally and noncommercially,
          and only if you received the object code with such an offer,
          in accord with subsection 6b.

       d. Convey the object code by offering access from a designated
          place (gratis or for a charge), and offer equivalent access to
          the Corresponding Source in the same way through the same
          place at no further charge.  You need not require recipients
          to copy the Corresponding Source along with the object code.
          If the place to copy the object code is a network server, the
          Corresponding Source may be on a different server (operated by
          you or a third party) that supports equivalent copying
          facilities, provided you maintain clear directions next to the
          object code saying where to find the Corresponding Source.
          Regardless of what server hosts the Corresponding Source, you
          remain obligated to ensure that it is available for as long as
          needed to satisfy these requirements.

       e. Convey the object code using peer-to-peer transmission,
          provided you inform other peers where the object code and
          Corresponding Source of the work are being offered to the
          general public at no charge under subsection 6d.

     A separable portion of the object code, whose source code is
     excluded from the Corresponding Source as a System Library, need
     not be included in conveying the object code work.

     A “User Product” is either (1) a “consumer product”, which means
     any tangible personal property which is normally used for personal,
     family, or household purposes, or (2) anything designed or sold for
     incorporation into a dwelling.  In determining whether a product is
     a consumer product, doubtful cases shall be resolved in favor of
     coverage.  For a particular product received by a particular user,
     “normally used” refers to a typical or common use of that class of
     product, regardless of the status of the particular user or of the
     way in which the particular user actually uses, or expects or is
     expected to use, the product.  A product is a consumer product
     regardless of whether the product has substantial commercial,
     industrial or non-consumer uses, unless such uses represent the
     only significant mode of use of the product.

     “Installation Information” for a User Product means any methods,
     procedures, authorization keys, or other information required to
     install and execute modified versions of a covered work in that
     User Product from a modified version of its Corresponding Source.
     The information must suffice to ensure that the continued
     functioning of the modified object code is in no case prevented or
     interfered with solely because modification has been made.

     If you convey an object code work under this section in, or with,
     or specifically for use in, a User Product, and the conveying
     occurs as part of a transaction in which the right of possession
     and use of the User Product is transferred to the recipient in
     perpetuity or for a fixed term (regardless of how the transaction
     is characterized), the Corresponding Source conveyed under this
     section must be accompanied by the Installation Information.  But
     this requirement does not apply if neither you nor any third party
     retains the ability to install modified object code on the User
     Product (for example, the work has been installed in ROM).

     The requirement to provide Installation Information does not
     include a requirement to continue to provide support service,
     warranty, or updates for a work that has been modified or installed
     by the recipient, or for the User Product in which it has been
     modified or installed.  Access to a network may be denied when the
     modification itself materially and adversely affects the operation
     of the network or violates the rules and protocols for
     communication across the network.

     Corresponding Source conveyed, and Installation Information
     provided, in accord with this section must be in a format that is
     publicly documented (and with an implementation available to the
     public in source code form), and must require no special password
     or key for unpacking, reading or copying.

  7. Additional Terms.

     “Additional permissions” are terms that supplement the terms of
     this License by making exceptions from one or more of its
     conditions.  Additional permissions that are applicable to the
     entire Program shall be treated as though they were included in
     this License, to the extent that they are valid under applicable
     law.  If additional permissions apply only to part of the Program,
     that part may be used separately under those permissions, but the
     entire Program remains governed by this License without regard to
     the additional permissions.

     When you convey a copy of a covered work, you may at your option
     remove any additional permissions from that copy, or from any part
     of it.  (Additional permissions may be written to require their own
     removal in certain cases when you modify the work.)  You may place
     additional permissions on material, added by you to a covered work,
     for which you have or can give appropriate copyright permission.

     Notwithstanding any other provision of this License, for material
     you add to a covered work, you may (if authorized by the copyright
     holders of that material) supplement the terms of this License with
     terms:

       a. Disclaiming warranty or limiting liability differently from
          the terms of sections 15 and 16 of this License; or

       b. Requiring preservation of specified reasonable legal notices
          or author attributions in that material or in the Appropriate
          Legal Notices displayed by works containing it; or

       c. Prohibiting misrepresentation of the origin of that material,
          or requiring that modified versions of such material be marked
          in reasonable ways as different from the original version; or

       d. Limiting the use for publicity purposes of names of licensors
          or authors of the material; or

       e. Declining to grant rights under trademark law for use of some
          trade names, trademarks, or service marks; or

       f. Requiring indemnification of licensors and authors of that
          material by anyone who conveys the material (or modified
          versions of it) with contractual assumptions of liability to
          the recipient, for any liability that these contractual
          assumptions directly impose on those licensors and authors.

     All other non-permissive additional terms are considered “further
     restrictions” within the meaning of section 10.  If the Program as
     you received it, or any part of it, contains a notice stating that
     it is governed by this License along with a term that is a further
     restriction, you may remove that term.  If a license document
     contains a further restriction but permits relicensing or conveying
     under this License, you may add to a covered work material governed
     by the terms of that license document, provided that the further
     restriction does not survive such relicensing or conveying.

     If you add terms to a covered work in accord with this section, you
     must place, in the relevant source files, a statement of the
     additional terms that apply to those files, or a notice indicating
     where to find the applicable terms.

     Additional terms, permissive or non-permissive, may be stated in
     the form of a separately written license, or stated as exceptions;
     the above requirements apply either way.

  8. Termination.

     You may not propagate or modify a covered work except as expressly
     provided under this License.  Any attempt otherwise to propagate or
     modify it is void, and will automatically terminate your rights
     under this License (including any patent licenses granted under the
     third paragraph of section 11).

     However, if you cease all violation of this License, then your
     license from a particular copyright holder is reinstated (a)
     provisionally, unless and until the copyright holder explicitly and
     finally terminates your license, and (b) permanently, if the
     copyright holder fails to notify you of the violation by some
     reasonable means prior to 60 days after the cessation.

     Moreover, your license from a particular copyright holder is
     reinstated permanently if the copyright holder notifies you of the
     violation by some reasonable means, this is the first time you have
     received notice of violation of this License (for any work) from
     that copyright holder, and you cure the violation prior to 30 days
     after your receipt of the notice.

     Termination of your rights under this section does not terminate
     the licenses of parties who have received copies or rights from you
     under this License.  If your rights have been terminated and not
     permanently reinstated, you do not qualify to receive new licenses
     for the same material under section 10.

  9. Acceptance Not Required for Having Copies.

     You are not required to accept this License in order to receive or
     run a copy of the Program.  Ancillary propagation of a covered work
     occurring solely as a consequence of using peer-to-peer
     transmission to receive a copy likewise does not require
     acceptance.  However, nothing other than this License grants you
     permission to propagate or modify any covered work.  These actions
     infringe copyright if you do not accept this License.  Therefore,
     by modifying or propagating a covered work, you indicate your
     acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

     Each time you convey a covered work, the recipient automatically
     receives a license from the original licensors, to run, modify and
     propagate that work, subject to this License.  You are not
     responsible for enforcing compliance by third parties with this
     License.

     An “entity transaction” is a transaction transferring control of an
     organization, or substantially all assets of one, or subdividing an
     organization, or merging organizations.  If propagation of a
     covered work results from an entity transaction, each party to that
     transaction who receives a copy of the work also receives whatever
     licenses to the work the party’s predecessor in interest had or
     could give under the previous paragraph, plus a right to possession
     of the Corresponding Source of the work from the predecessor in
     interest, if the predecessor has it or can get it with reasonable
     efforts.

     You may not impose any further restrictions on the exercise of the
     rights granted or affirmed under this License.  For example, you
     may not impose a license fee, royalty, or other charge for exercise
     of rights granted under this License, and you may not initiate
     litigation (including a cross-claim or counterclaim in a lawsuit)
     alleging that any patent claim is infringed by making, using,
     selling, offering for sale, or importing the Program or any portion
     of it.

  11. Patents.

     A “contributor” is a copyright holder who authorizes use under this
     License of the Program or a work on which the Program is based.
     The work thus licensed is called the contributor’s “contributor
     version”.

     A contributor’s “essential patent claims” are all patent claims
     owned or controlled by the contributor, whether already acquired or
     hereafter acquired, that would be infringed by some manner,
     permitted by this License, of making, using, or selling its
     contributor version, but do not include claims that would be
     infringed only as a consequence of further modification of the
     contributor version.  For purposes of this definition, “control”
     includes the right to grant patent sublicenses in a manner
     consistent with the requirements of this License.

     Each contributor grants you a non-exclusive, worldwide,
     royalty-free patent license under the contributor’s essential
     patent claims, to make, use, sell, offer for sale, import and
     otherwise run, modify and propagate the contents of its contributor
     version.

     In the following three paragraphs, a “patent license” is any
     express agreement or commitment, however denominated, not to
     enforce a patent (such as an express permission to practice a
     patent or covenant not to sue for patent infringement).  To “grant”
     such a patent license to a party means to make such an agreement or
     commitment not to enforce a patent against the party.

     If you convey a covered work, knowingly relying on a patent
     license, and the Corresponding Source of the work is not available
     for anyone to copy, free of charge and under the terms of this
     License, through a publicly available network server or other
     readily accessible means, then you must either (1) cause the
     Corresponding Source to be so available, or (2) arrange to deprive
     yourself of the benefit of the patent license for this particular
     work, or (3) arrange, in a manner consistent with the requirements
     of this License, to extend the patent license to downstream
     recipients.  “Knowingly relying” means you have actual knowledge
     that, but for the patent license, your conveying the covered work
     in a country, or your recipient’s use of the covered work in a
     country, would infringe one or more identifiable patents in that
     country that you have reason to believe are valid.

     If, pursuant to or in connection with a single transaction or
     arrangement, you convey, or propagate by procuring conveyance of, a
     covered work, and grant a patent license to some of the parties
     receiving the covered work authorizing them to use, propagate,
     modify or convey a specific copy of the covered work, then the
     patent license you grant is automatically extended to all
     recipients of the covered work and works based on it.

     A patent license is “discriminatory” if it does not include within
     the scope of its coverage, prohibits the exercise of, or is
     conditioned on the non-exercise of one or more of the rights that
     are specifically granted under this License.  You may not convey a
     covered work if you are a party to an arrangement with a third
     party that is in the business of distributing software, under which
     you make payment to the third party based on the extent of your
     activity of conveying the work, and under which the third party
     grants, to any of the parties who would receive the covered work
     from you, a discriminatory patent license (a) in connection with
     copies of the covered work conveyed by you (or copies made from
     those copies), or (b) primarily for and in connection with specific
     products or compilations that contain the covered work, unless you
     entered into that arrangement, or that patent license was granted,
     prior to 28 March 2007.

     Nothing in this License shall be construed as excluding or limiting
     any implied license or other defenses to infringement that may
     otherwise be available to you under applicable patent law.

  12. No Surrender of Others’ Freedom.

     If conditions are imposed on you (whether by court order, agreement
     or otherwise) that contradict the conditions of this License, they
     do not excuse you from the conditions of this License.  If you
     cannot convey a covered work so as to satisfy simultaneously your
     obligations under this License and any other pertinent obligations,
     then as a consequence you may not convey it at all.  For example,
     if you agree to terms that obligate you to collect a royalty for
     further conveying from those to whom you convey the Program, the
     only way you could satisfy both those terms and this License would
     be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

     Notwithstanding any other provision of this License, you have
     permission to link or combine any covered work with a work licensed
     under version 3 of the GNU Affero General Public License into a
     single combined work, and to convey the resulting work.  The terms
     of this License will continue to apply to the part which is the
     covered work, but the special requirements of the GNU Affero
     General Public License, section 13, concerning interaction through
     a network will apply to the combination as such.

  14. Revised Versions of this License.

     The Free Software Foundation may publish revised and/or new
     versions of the GNU General Public License from time to time.  Such
     new versions will be similar in spirit to the present version, but
     may differ in detail to address new problems or concerns.

     Each version is given a distinguishing version number.  If the
     Program specifies that a certain numbered version of the GNU
     General Public License “or any later version” applies to it, you
     have the option of following the terms and conditions either of
     that numbered version or of any later version published by the Free
     Software Foundation.  If the Program does not specify a version
     number of the GNU General Public License, you may choose any
     version ever published by the Free Software Foundation.

     If the Program specifies that a proxy can decide which future
     versions of the GNU General Public License can be used, that
     proxy’s public statement of acceptance of a version permanently
     authorizes you to choose that version for the Program.

     Later license versions may give you additional or different
     permissions.  However, no additional obligations are imposed on any
     author or copyright holder as a result of your choosing to follow a
     later version.

  15. Disclaimer of Warranty.

     THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
     APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE
     COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS”
     WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE
     RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.
     SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
     NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

     IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
     WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES
     AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR
     DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
     CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
     THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA
     BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
     PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
     PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF
     THE POSSIBILITY OF SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

     If the disclaimer of warranty and limitation of liability provided
     above cannot be given local legal effect according to their terms,
     reviewing courts shall apply local law that most closely
     approximates an absolute waiver of all civil liability in
     connection with the Program, unless a warranty or assumption of
     liability accompanies a copy of the Program in return for a fee.

END OF TERMS AND CONDITIONS
===========================

How to Apply These Terms to Your New Programs
=============================================

If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.

   To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least the
“copyright” line and a pointer to where the full notice is found.

     ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
     Copyright (C) YEAR NAME OF AUTHOR

     This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
     the Free Software Foundation, either version 3 of the License, or (at
     your option) any later version.

     This program is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this program.  If not, see <http://www.gnu.org/licenses/>.

   Also add information on how to contact you by electronic and paper
mail.

   If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

     PROGRAM Copyright (C) YEAR NAME OF AUTHOR
     This program comes with ABSOLUTELY NO WARRANTY; for details type ‘show w’.
     This is free software, and you are welcome to redistribute it
     under certain conditions; type ‘show c’ for details.

   The hypothetical commands ‘show w’ and ‘show c’ should show the
appropriate parts of the General Public License.  Of course, your
program’s commands might be different; for a GUI interface, you would
use an “about box”.

   You should also get your employer (if you work as a programmer) or
school, if any, to sign a “copyright disclaimer” for the program, if
necessary.  For more information on this, and how to apply and follow
the GNU GPL, see <http://www.gnu.org/licenses/>.

   The GNU General Public License does not permit incorporating your
program into proprietary programs.  If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library.  If this is what you want to do, use the
GNU Lesser General Public License instead of this License.  But first,
please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

