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

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

   This file documents Gforth 0.4.0

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

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

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

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


File: gforth.info,  Node: Objects Glossary,  Prev: Comparison with other object models,  Up: Objects

`objects.fs' Glossary
.....................

`bind'       ... "class" "selector" - ...         objects       ``bind''
   execute the method for `selector' in `class'.

`<bind>'       class selector-xt - xt         objects       ``<bind>''
   `xt' is the method for the selector `selector-xt' in `class'.

`bind''       "class" "selector" - xt         objects       ``bind'''
   `xt' is the method for `selector' in `class'.

`[bind]'       compile-time: "class" "selector" - ; run-time: ... object - ...         objects       ``[bind]''
   compile the method for `selector' in `class'.

`class'       parent-class - align offset         objects       ``class''
   start a new class definition as a child of `parent-class'. `align
offset' are for use by `field' etc.

`class->map'       class - map         objects       ``class->map''
   `map' is the pointer to `class''s method map; it points to the place
in the map to which the selector offsets refer (i.e., where
`object-map's point to).

`class-inst-size'       class - addr         objects       ``class-inst-size''
   used as `class-inst-size 2 ( class -- align size )', gives the size
specification for an instance (i.e. an object) of `class'.

`class-override!'       xt sel-xt class-map -         objects       ``class-override!''
   `xt' is the new method for the selector `sel-xt' in `class-map'.

`construct'       ... object -         objects       ``construct''
   initializes the data fields of `object'. The method for the class
`object' just does nothing `( object -- )'.

`current''       "selector" - xt         objects       ``current'''
   `xt' is the method for `selector' in the current class.

`[current]'       compile-time: "selector" - ; run-time: ... object - ...         objects       ``[current]''
   compile the method for `selector' in the current class.

`current-interface'       - addr         objects       ``current-interface''
   this variable contains the class or interface currently being
defined.

`dict-new'       ... class - object         objects       ``dict-new''
   `allot' and initialize an object of class `class' in the dictionary.

`drop-order'       class -         objects       ``drop-order''
   drops `class''s wordlists from the search order. No checking is made
whether `class''s wordlists are actually on the search order.

`end-class'       align offset "name" -         objects       ``end-class''
   `name' execution: `-- class'
ends a class definition. The resulting class is `class'.

`end-class-noname'       align offset - class         objects       ``end-class-noname''
   ends a class definition. The resulting class is `class'.

`end-interface'       "name" -         objects       ``end-interface''
   `name' execution: `-- interface'
ends an interface definition. The resulting interface is `interface'.

`end-interface-noname'       - interface         objects       ``end-interface-noname''
   ends an interface definition. The resulting interface is `interface'.

`exitm'       -         objects       ``exitm''
   `exit' from a method; restore old `this'.

`heap-new'       ... class - object         objects       ``heap-new''
   `allocate' and initialize an object of class `class'.

`implementation'       interface -         objects       ``implementation''
   the current class implements `interface'. I.e., you can use all
selectors of the interface in the current class and its descendents.

`init-object'       ... class object -         objects       ``init-object''
   initializes a chunk of memory (`object') to an object of class
`class'; then performs `construct'.

`inst-value'       align1 offset1 "name" - align2 offset2         objects       ``inst-value''
   `name' execution: `-- w'
`w' is the value of the field `name' in `this' object.

`inst-var'       align1 offset1 align size "name" - align2 offset2         objects       ``inst-var''
   `name' execution: `-- addr'
`addr' is the address of the field `name' in `this' object.

`interface'       -         objects       ``interface''
   starts an interface definition.

`;m'       colon-sys -; run-time: -         objects       ``;m''
   end a method definition; restore old `this'.

`m:'       - xt colon-sys; run-time: object -         objects       ``m:''
   start a method definition; `object' becomes new `this'.

`method'       xt "name" -         objects       ``method''
   `name' execution: `... object -- ...'
creates selector `name' and makes `xt' its method in the current class.

`object'       - class         objects       ``object''
   the ancestor of all classes.

`overrides'       xt "selector" -         objects       ``overrides''
   replace default method for `selector' in the current class with
`xt'. `overrides' must not be used during an interface definition.

`[parent]'       compile-time: "selector" - ; run-time: ... object - ...         objects       ``[parent]''
   compile the method for `selector' in the parent of the current class.

`print'       object -         objects       ``print''
   prints the object. The method for the class `object' prints the
address of the object and the address of its class.

`protected'       -         objects       ``protected''
   set the compilation wordlist to the current class's wordlist

`public'       -         objects       ``public''
   restore the compilation wordlist that was in effect before the last
`protected' that actually changed the compilation wordlist.

`push-order'       class -         objects       ``push-order''
   add `class''s wordlists to the search-order (in front)

`selector'       "name" -         objects       ``selector''
   `name' execution: `... object -- ...'
creates selector `name' for the current class and its descendents; you
can set a method for the selector in the current class with `overrides'.

`this'       - object         objects       ``this''
   the receiving object of the current method (aka active object).

`<to-inst>'       w xt -         objects       ``<to-inst>''
   store `w' into the field `xt' in `this' object.

`[to-inst]'       compile-time: "name" - ; run-time: w -         objects       ``[to-inst]''
   store `w' into field `name' in `this' object.

`to-this'       object -         objects       ``to-this''
   sets `this' (used internally, but useful when debugging).

`xt-new'       ... class xt - object         objects       ``xt-new''
   makes a new object, using `xt ( align size -- addr )' to get memory.


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

OOF
---

   This section describes the `oof.fs' packet. This section uses the
same rationale why using object-oriented programming, and the same
terminology.

   The packet described in this section is used in bigFORTH since 1991,
and used for two large applications: a chromatographic system used to
create new medicaments, and a graphic user interface library (MINOS).

   You can find a description (in German) of `oof.fs' in `Object
oriented bigFORTH' by Bernd Paysan, published in `Vierte Dimension'
10(2), 1994.

* Menu:

* Properties of the OOF model::
* Basic OOF Usage::
* The base class object::
* Class Declaration::
* Class Implementation::


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

Properties of the OOF model
...........................

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

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

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

   * Late binding is efficient and easy to use.

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

   * An implementation in ANS Forth is available.


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

Basic OOF Usage
...............

   Here, I use the same example as for `objects' (*note Basic Objects
Usage::.).

   You can define a class for graphical objects like this:

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

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

     100 100 t-rex draw

   where `t-rex' is an object or object pointer, created with e.g.
`graphical : t-rex'.

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

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

     graphical class circle \ "graphical" is the parent class
       cell var circle-radius
     how:
       : draw ( x y -- )
         circle-radius @ draw-circle ;
     
       : init ( n-radius -- (
         circle-radius ! ;
     class;

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

   Now we can create a circle in the dictionary with

     50 circle : my-circle

   `:' invokes `init', thus initializing the field `circle-radius' with
50. We can draw this new circle at (100,100) with

     100 100 my-circle draw

   Note: You can invoke a selector only if the receiving object belongs
to the class where the selector was defined or one of its descendents;
e.g., you can invoke `draw' only for objects belonging to `graphical'
or its descendents (e.g., `circle'). The scoping mechanism will check
if you try to invoke a selector that is not defined in this class
hierarchy, so you'll get an error at compilation time.


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

The base class `object'
.......................

   When you define a class, you have to specify a parent class.  So how
do you start defining classes? There is one class available from the
start: `object'. You have to use it as ancestor for all classes. It is
the only class that has no parent. Classes are also objects, except that
they don't have instance variables; class manipulation such as
inheritance or changing definitions of a class is handled through
selectors of the class `object'.

   `object' provides a number of selectors:

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

     `definitions'       -         oof       ``definitions''

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

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

     `dispose'       -         oof       ``dispose''

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

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

     `:'       "name" -         oof       ``define''

     `ptr'       "name" -         oof       ``ptr''

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

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

   * `::' and `super' for expicit scoping. You should use expicit
     scoping only for super classes or classes with the same set of
     instance variables. Explicit scoped selectors use early binding.
     `::'       "name" -         oof       ``scope''

     `super'       "name" -         oof       ``super''

   * `self' to get the address of the object
     `self'       - o         oof       ``self''

   * `bind', `bound', `link', and `is' to assign object pointers and
     instance defers.
     `bind'       o "name" -         oof       ``bind''

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

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

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

   * `'' to obtain selector tokens, `send' to invocate selectors form
     the stack, and `postpone' to generate selector invocation code.
     `''       "name" - xt         oof       ``tick''

     `postpone'       "name" -         oof       ``postpone''

   * `with' and `endwith' to select the active object from the stack,
     and enabling it's scope. Using `with' and `endwith' also allows to
     create code using selector `postpone' without being trapped bye
     the state-smart objects.
     `with'       o -         oof       ``with''

     `endwith'       -         oof       ``endwith''


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

Class Declaration
.................

   * Instance variables
     `var'       size -         oof       ``var''
     Create an instance variable

   * Object pointers
     `ptr'       -         oof       ``ptr''
     Create an instance pointer

     `asptr'       class -         oof       ``asptr''
     Create an alias to an instance pointer, casted to another class

   * Instance defers
     `defer'       -         oof       ``defer''
     Create an instance defer

   * Method selectors
     `early'       -         oof       ``early''
     Create a method selector for early binding

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

   * Class wide variables
     `static'       -         oof       ``static''
     Create a class-wide cell sized variable

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

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


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

Class Implementation
....................


File: gforth.info,  Node: Mini-OOF,  Prev: OOF,  Up: Object-oriented Forth

Mini-OOF
--------

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

* Menu:

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


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

Usage
.....

   Basically, there are seven words, to define a method, a variable, a
class; to end a class, to define a method, to allocate an object, to
resolve binding, and the base class (which allocates one cell for the
object pointer).

`method'       m v - m' v         unknown       ``method''

   Defines a method

`var'       m v size - m v'         unknown       ``var''

   Defines a variable with size bytes

`class'       class - class methods vars         unknown       ``class''

   Starts the definition of a sub-class

`end-class'       class methods vars -         unknown       ``end-class''

   Ends the definition of a class

`defines'       xt class "name" -         unknown       ``defines''

   Binds the xt to the method name in the class

`new'       class - o         unknown       ``new''

   Creates a new incarnation of the class

`::'       class "name" -         unknown       ``::''

   Compiles the method name of the class (not immediate!)

`object'              unknown       ``object''

   Is the base class of all objects


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

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

   A short example shows how to use this package.

     object class
       method init
       method draw
     end-class graphical

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

     100 100 t-rex draw

   where `t-rex' is an object or object pointer, created with e.g.
`graphical new Constant t-rex'.

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

     graphical class
       cell var circle-radius
     end-class circle \ "graphical" is the parent class
     
     :noname ( x y -- )
       circle-radius @ draw-circle ; circle defines draw
     :noname ( r -- )
       circle-radius ! ; circle defines init

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

     circle new Constant my-circle
     50 my-circle init

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

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

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

     100 100 my-circle draw


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

Mini-OOF Implementation
.......................

   Object oriented system with late binding typically use a
"vtable"-approach: the first variable in each object is a pointer to a
table, which contains the methods as function pointers. This vtable may
contain some other informations, too.

   So first, let's declare methods:

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

   During method declaration, the number of methods and instance
variables is on the stack (in address units). `method' creates one
method and increments the method number. To execute a method, it takes
the object, fetches the vtable pointer, adds the offset, and executes
the xt stored there. Each method takes the object it is invoked from as
top of stack parameter. The method itself should consume that object.

   Now, we also have to declare instance variables

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

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

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

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

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

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

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

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

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

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

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

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

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

   <H2>An Example</H2>

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

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

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

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

   For inheritance, we define a class `bold-button', with no new data
and no new methods.

     button class
     end-class bold-button
     
     : bold   27 emit ." [1m" ;
     : normal 27 emit ." [0m" ;
     
     :noname bold [ button :: draw ] normal ; bold-button defines draw

   And finally, some code to demonstrate how to create objects and
apply methods:

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


File: gforth.info,  Node: Tokens for Words,  Next: Wordlists,  Prev: Object-oriented Forth,  Up: Words

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

   This chapter describes the creation and use of tokens that represent
words on the stack (and in data space).

   Named words have interpretation and compilation semantics. Unnamed
words just have execution semantics.

   An "execution token" represents the execution semantics of an
unnamed word. An execution token occupies one cell. As explained in
section *Note Supplying names::, the execution token of the last words
defined can be produced with

`lastxt'       - xt         gforth       ``lastxt''

   You can perform the semantics represented by an execution token with
`execute'       xt -       core       ``execute''

   You can compile the word with
`compile,'       xt -         core-ext       ``compile-comma''

   In Gforth, the abstract data type *execution token* is implemented
as CFA (code field address).

   The interpretation semantics of a named word are also represented by
an execution token. You can get it with

`[']'       compilation. "name" - ; run-time. - xt         core       ``bracket-tick''
   XT represents NAME's interpretation semantics. Performs `-14 throw'
if the word has no interpretation semantics.

`''       "name" - xt         core       ``tick''
   XT represents NAME's interpretation semantics. Performs `-14 throw'
if the word has no interpretation semantics.

   For literals, you use `'' in interpreted code and `[']' in compiled
code. Gforth's `'' and `[']' behave somewhat unusual by complaining
about compile-only words. To get an execution token for a compiling
word X, use `COMP' X drop' or `[COMP'] X drop'.

   The compilation semantics are represented by a "compilation token"
consisting of two cells: W XT. The top cell XT is an execution token.
The compilation semantics represented by the compilation token can be
performed with `execute', which consumes the whole compilation token,
with an additional stack effect determined by the represented
compilation semantics.

`[COMP']'       compilation "name" - ; run-time - w xt         gforth       ``bracket-comp-tick''
   W XT represents NAME's compilation semantics.

`COMP''       "name" - w xt         gforth       ``comp-tick''
   W XT represents NAME's compilation semantics.

   You can compile the compilation semantics with `postpone,'. I.e.,
`COMP' WORD POSTPONE,' is equivalent to `POSTPONE WORD'.

`postpone,'       w xt -         gforth       ``postpone-comma''
   Compiles the compilation semantics represented by W XT.

   At present, the W part of a compilation token is an execution token,
and the XT part represents either `execute' or `compile,'. However,
don't rely on that knowledge, unless necessary; we may introduce
unusual compilation tokens in the future (e.g., compilation tokens
representing the compilation semantics of literals).

   Named words are also represented by the "name token". The abstract
data type *name token* is implemented as NFA (name field address).

`find-name'       c-addr u - nt/0         gforth       ``find-name''
   Find the name C-ADDR U in the current search order. Return its nt,
if found, otherwise 0.

`name>int'       nt - xt         gforth       ``name>int''
   XT represents the interpretation semantics of the word NT. Produces
`' compile-only-error' if NT is compile-only.

`name?int'       nt - xt         gforth       ``name?int''
   Like name>int, but throws an error if compile-only.

`name>comp'       nt - w xt         gforth       ``name>comp''
   W XT is the compilation token for the word NT.

`name>string'       nt - addr count         gforth       ``head-to-string''
   ADDR COUNT is the name of the word represented by NT.


File: gforth.info,  Node: Wordlists,  Next: Files,  Prev: Tokens for Words,  Up: Words

Wordlists
=========


File: gforth.info,  Node: Files,  Next: Including Files,  Prev: Wordlists,  Up: Words

Files
=====

   This chapter describes how to operate on files from Forth.

   Files have the following types for opening and creating:

`r/o'       - fam         file       ``r-o''

`r/w'       - fam         file       ``r-w''

`w/o'       - fam         file       ``w-o''

`bin'       fam1 - fam2         file       ``bin''

   Files are opened/created by name and type, and return a file
identifier.

`open-file'       c-addr u ntype - w2 wior       file       ``open-file''

`create-file'       c-addr u ntype - w2 wior       file       ``create-file''

   This identifier is used for all other file commands.

`close-file'       wfileid - wior       file       ``close-file''

`delete-file'       c-addr u - wior       file       ``delete-file''

`rename-file'       c-addr1 u1 c-addr2 u2 - wior       file-ext       ``rename-file''
   rename file c_addr1 u1 to new name c_addr2 u2

`read-file'       c-addr u1 wfileid - u2 wior       file       ``read-file''

`read-line'       c-addr u1 wfileid - u2 flag wior       file       ``read-line''

`write-file'       c-addr u1 wfileid - wior       file       ``write-file''

`emit-file'       c wfileid - wior       gforth       ``emit-file''

`flush-file'       wfileid - wior       file-ext       ``flush-file''

`file-status'       c-addr u - ntype wior       file-ext       ``file-status''

`file-position'       wfileid - ud wior       file       ``file-position''

`reposition-file'       ud wfileid - wior       file       ``reposition-file''

`file-size'       wfileid - ud wior       file       ``file-size''

`resize-file'       ud wfileid - wior       file       ``resize-file''


File: gforth.info,  Node: Including Files,  Next: Blocks,  Prev: Files,  Up: Words

Including Files
===============

* Menu:

* Words for Including::
* Search Path::
* Changing the Search Path::
* General Search Paths::


File: gforth.info,  Node: Words for Including,  Next: Search Path,  Prev: Including Files,  Up: Including Files

Words for Including
-------------------

`include-file'       i*x fid - j*x         file       ``include-file''
   interpret (process using the text interpreter) the contents of the
file FID.

`included'       i*x addr u - j*x         file       ``included''
   `include-file' the file whose name is given by the string ADDR U.

`include'       ... "file" - ...         gforth       ``include''
   includes FILE

   Usually you want to include a file only if it is not included already
(by, say, another source file):

`required'       i*x addr u - j*x         gforth       ``required''
   include the file with the name given by ADDR U, if it is not
`included' (or `required') already. Currently this works by comparing
the name of the file (with path) against the names of earlier included
files.

`require'       ... "file" - ...         gforth       ``require''
   includes FILE only if it is not included already

`needs'       ... "name" - ...         gforth       ``needs''
   an alias for `require'; exists on other systems (e.g., Win32Forth).

   I recommend that you write your source files such that interpreting
them does not change the stack. This allows using these files with
`required' and friends without complications. E.g.,

     1 require foo.fs drop


File: gforth.info,  Node: Search Path,  Next: Changing the Search Path,  Prev: Words for Including,  Up: Including Files

Search Path
-----------

   If you specify an absolute filename (i.e., a filename starting with
`/' or `~', or with `:' in the second position (as in `C:...')) for
`included' and friends, that file is included just as you would expect.

   For relative filenames, Gforth uses a search path similar to Forth's
search order (*note Wordlists::.). It tries to find the given filename
in the directories present in the path, and includes the first one it
finds.

   If the search path contains the directory `.' (as it should), this
refers to the directory that the present file was `included' from. This
allows files to include other files relative to their own position
(irrespective of the current working directory or the absolute
position).  This feature is essential for libraries consisting of
several files, where a file may include other files from the library.
It corresponds to `#include "..."' in C. If the current input source is
not a file, `.' refers to the directory of the innermost file being
included, or, if there is no file being included, to the current
working directory.

   Use `~+' to refer to the current working directory (as in the
`bash').

   If the filename starts with `./', the search path is not searched
(just as with absolute filenames), and the `.' has the same meaning as
described above.


File: gforth.info,  Node: Changing the Search Path,  Next: General Search Paths,  Prev: Search Path,  Up: Including Files

Changing the Search Path
------------------------

   The search path is initialized when you start Gforth (*note Invoking
Gforth::.). You can display it with

`.fpath'       -         gforth       ``.fpath''
   displays the contents of the forth search patch

   You can change it later with the following words:

`fpath+'       "dir"         gforth       ``fpath+''
   adds a directory to the forth search path

`fpath='       "dir1|dir2|dir3"         gforth       ``fpath=''
   makes complete new searchpath, serpeator is |

   Using fpath and require would look like:

     fpath= /usr/lib/forth/|./
     
     require timer.fs

   If you have the need to look for a file in the Forth search path,
you could use this Gforth feature in your application.

`open-fpath-file'       adr len - fd adr1 len2 0 | ior         gforth       ``open-fpath-file''
   looks in the forth search path for the file specified by adr len
when found the resulting path and an open file descriptor is returned.
If the file is not found ior is non zero


File: gforth.info,  Node: General Search Paths,  Prev: Changing the Search Path,  Up: Including Files

General Search Paths
--------------------

   Your application may need to search files in sevaral directories,
like `included' does. For this purpose you can define and use your own
search paths. Create a search path like this:


     Make a buffer for the path:
     create mypath   100 chars ,     \ maximum length (is checked)
                     0 ,             \ real len
                     100 chars allot \ space for path

   You have the same functions for the forth search path in a generic
version for different paths.

`path+'       path-addr  "dir" -         gforth       ``path+''
   adds a directory to the search path path-addr

`path='       path-addr "dir1|dir2|dir3"         gforth       ``path=''
   makes complete new searchpath, seperator is |

`.path'       path-addr -         gforth       ``.path''
   displays the contents of the search path path-addr

`open-path-file'       adr len path-addr - fd adr1 len2 0 | ior         gforth       ``open-path-file''
   looks in path path-addr for the file specified by adr len when found
the resulting path and an open file descriptor is returned. If the file
is not found ior is non zero


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

Blocks
======

   This chapter describes how to use block files within Gforth.

   Block files are traditionally means of data and source storage in
Forth. They have been very important in resource-starved computers
without OS in the past. Gforth doesn't encourage to use blocks as
source, and provides blocks only for backward compatibility. The ANS
standard requires blocks to be available when files are.

`open-blocks'       addr u -         gforth       ``open-blocks''
   use the file, whose name is given by ADDR U, as blocks file

`use'       "file" -         gforth       ``use''
   use FILE as blocks file

`get-block-fid'       - fid         gforth       ``get-block-fid''

`block-position'       u -         block       ``block-position''
   positions the block file to the start of block u

`update'       -         block       ``update''

`save-buffer'       buffer -         gforth       ``save-buffer''

`empty-buffer'       buffer -         gforth       ``empty-buffer''

`flush'       -         block       ``flush''

`get-buffer'       n - a-addr         gforth       ``get-buffer''

`block'              unknown       ``block''

`buffer'       u - a-addr         block       ``buffer''

`updated?'       n - f         gforth       ``updated?''

`list'       u -         block       ``list''

`load'       i*x n - j*x         block       ``load''

`thru'       i*x n1 n2 - j*x         block       ``thru''

`+load'       i*x n - j*x         block       ``+load''

`+thru'       i*x n1 n2 - j*x         block       ``+thru''

`-->'       -         block       ``-->''

`block-included'       addr u -         gforth       ``block-included''


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

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


File: gforth.info,  Node: Programming Tools,  Next: Assembler and Code Words,  Prev: Other I/O,  Up: Words

Programming Tools
=================

* Menu:

* Debugging::                   Simple and quick.
* Assertions::                  Making your programs self-checking.
* Singlestep Debugger::		Executing your program word by word.


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

Debugging
---------

   The simple debugging aids provided in `debugs.fs' are meant to
support a different style of debugging than the tracing/stepping
debuggers used in languages with long turn-around times.

   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 word `~~' is easy to insert. It just prints debugging
information (by default the source location and the stack contents). It
is also easy to remove (`C-x ~' in the Emacs Forth mode to
query-replace them with nothing). The deferred words `printdebugdata'
and `printdebugline' 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).

   Note that the default actions clobber the contents of the pictured
numeric output string, so you should not use `~~', e.g., between `<#'
and `#>'.

`~~'       compilation  - ; run-time  -         gforth       ``tilde-tilde''

`printdebugdata'       -         gforth       ``printdebugdata''

`printdebugline'       addr -         gforth       ``printdebugline''


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

Assertions
----------

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

     assert( FLAG )

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

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

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

`assert0('       -         gforth       ``assert-zero''
   important assertions that should always be turned on

`assert1('       -         gforth       ``assert-one''
   normal assertions; turned on by default

`assert2('       -         gforth       ``assert-two''
   debugging assertions

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

`assert('       -         gforth       ``assert(''
   equivalent to assert1(

`)'       -         gforth       ``close-paren''
   end an assertion

   `Assert(' is the same as `assert1('. 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.

   Note that the `assert-level' is evaluated at compile-time, not at
run-time. I.e., 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 several pieces of code at several
`assert-level's (e.g., a trusted library at level 1 and newly written
code at level 3).

`assert-level'       - a-addr         gforth       ``assert-level''
   all assertions above this level are turned off

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


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

Singlestep Debugger
-------------------

   When a new word is created there's often the need to check whether
it behaves correctly or not. You can do this by typing `dbg badword'.
This might look like:
     : 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:

<return>
     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
     Stopp; Abort immediately.

   Debugging large application with this mechanism is very difficult,
because you have to nest very deep 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.


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

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

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

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

`assembler'       -         tools-ext       ``assembler''

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

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

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

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

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

   These words are rarely used. Therefore they reside in `code.fs',
which is usually not loaded (except `flush-icache', which is always
present). You can load them with `require code.fs'.

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

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

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

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

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


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

Threading Words
===============

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

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

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

`code-address!'       c-addr xt -       gforth       ``code-address-store''
   Creates a code field with code address c_addr at xt

`does-code!'       a-addr xt -       gforth       ``does-code-store''
   creates a code field at xt for a defining-word-defined word; a_addr
is the start of the Forth code after DOES>

`does-handler!'       a-addr -       gforth       ``does-handler-store''
   creates a DOES>-handler at address a_addr. a_addr usually points
just behind a DOES>.

`/does-handler'       - n       gforth       ``slash-does-handler''
   the size of a does-handler (includes possible padding)

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

`docol:'       - addr         gforth       ``docol:''
   the code address of a colon definition

`docon:'       - addr         gforth       ``docon:''
   the code address of a `CONSTANT'

`dovar:'       - addr         gforth       ``dovar:''
   the code address of a `CREATE'd word

`douser:'       - addr         gforth       ``douser:''
   the code address of a `USER' variable

`dodefer:'       - addr         gforth       ``dodefer:''
   the code address of a `defer'ed word

`dofield:'       - addr         gforth       ``dofield:''
   the code address of a `field'

   You can recognize words defined by a `CREATE'...`DOES>' word with
`>DOES-CODE'. If the word was defined in that way, the value returned
is different from 0 and identifies the `DOES>' used by the defining
word.


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

Tools
*****

* Menu:

* ANS Report::                  Report the words used, sorted by wordset.

   See also *Note Emacs and Gforth::.


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

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

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

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

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

Caveats
-------

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

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

