| |
|
| @comment %**end of header (This is for running Texinfo on a region.) |
@comment %**end of header (This is for running Texinfo on a region.) |
| @copying |
@copying |
| This manual is for Gforth |
This manual is for Gforth (version @value{VERSION}, @value{UPDATED}), |
| (version @value{VERSION}, @value{UPDATED}), |
a fast and portable implementation of the ANS Forth language. It |
| a fast and portable implementation of the ANS Forth language |
serves as reference manual, but it also contains an introduction to |
| |
Forth and a Forth tutorial. |
| |
|
| Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc. |
Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006 Free Software Foundation, Inc. |
| |
|
| @quotation |
@quotation |
| Permission is granted to copy, distribute and/or modify this document |
Permission is granted to copy, distribute and/or modify this document |
| * Files:: |
* Files:: |
| * Blocks:: |
* Blocks:: |
| * Other I/O:: |
* Other I/O:: |
| |
* OS command line arguments:: |
| * Locals:: |
* Locals:: |
| * Structures:: |
* Structures:: |
| * Object-oriented Forth:: |
* Object-oriented Forth:: |
| * Programming Tools:: |
* Programming Tools:: |
| |
* C Interface:: |
| * Assembler and Code Words:: |
* Assembler and Code Words:: |
| * Threading Words:: |
* Threading Words:: |
| * Passing Commands to the OS:: |
* Passing Commands to the OS:: |
| * Anonymous Definitions:: Definitions without names |
* Anonymous Definitions:: Definitions without names |
| * Supplying names:: Passing definition names as strings |
* Supplying names:: Passing definition names as strings |
| * User-defined Defining Words:: |
* User-defined Defining Words:: |
| * Deferred words:: Allow forward references |
* Deferred Words:: Allow forward references |
| * Aliases:: |
* Aliases:: |
| |
|
| User-defined Defining Words |
User-defined Defining Words |
| * CREATE..DOES> applications:: |
* CREATE..DOES> applications:: |
| * CREATE..DOES> details:: |
* CREATE..DOES> details:: |
| * Advanced does> usage example:: |
* Advanced does> usage example:: |
| * @code{Const-does>}:: |
* Const-does>:: |
| |
|
| Interpretation and Compilation Semantics |
Interpretation and Compilation Semantics |
| |
|
| |
|
| * Forth source files:: |
* Forth source files:: |
| * General files:: |
* General files:: |
| |
* Redirection:: |
| * Search Paths:: |
* Search Paths:: |
| |
|
| Search Paths |
Search Paths |
| * Formatted numeric output:: Formatted (pictured) output |
* Formatted numeric output:: Formatted (pictured) output |
| * String Formats:: How Forth stores strings in memory |
* String Formats:: How Forth stores strings in memory |
| * Displaying characters and strings:: Other stuff |
* Displaying characters and strings:: Other stuff |
| * Input:: Input |
* Terminal output:: Cursor positioning etc. |
| |
* Single-key input:: |
| |
* Line input and conversion:: |
| * Pipes:: How to create your own pipes |
* Pipes:: How to create your own pipes |
| |
* Xchars and Unicode:: Non-ASCII characters |
| |
|
| Locals |
Locals |
| |
|
| * Structure Naming Convention:: |
* Structure Naming Convention:: |
| * Structure Implementation:: |
* Structure Implementation:: |
| * Structure Glossary:: |
* Structure Glossary:: |
| |
* Forth200x Structures:: |
| |
|
| Object-oriented Forth |
Object-oriented Forth |
| |
|
| |
|
| Programming Tools |
Programming Tools |
| |
|
| * Examining:: |
* Examining:: Data and Code. |
| * Forgetting words:: |
* Forgetting words:: Usually before reloading. |
| * Debugging:: Simple and quick. |
* Debugging:: Simple and quick. |
| * Assertions:: Making your programs self-checking. |
* Assertions:: Making your programs self-checking. |
| * Singlestep Debugger:: Executing your program word by word. |
* Singlestep Debugger:: Executing your program word by word. |
| |
|
| |
C Interface |
| |
|
| |
* Calling C Functions:: |
| |
* Declaring C Functions:: |
| |
* Calling C function pointers:: |
| |
* Callbacks:: |
| |
* C interface internals:: |
| |
* Low-Level C Interface Words:: |
| |
|
| Assembler and Code Words |
Assembler and Code Words |
| |
|
| * Code and ;code:: |
* Code and ;code:: |
| * 386 Assembler:: Deviations and special cases |
* 386 Assembler:: Deviations and special cases |
| * Alpha Assembler:: Deviations and special cases |
* Alpha Assembler:: Deviations and special cases |
| * MIPS assembler:: Deviations and special cases |
* MIPS assembler:: Deviations and special cases |
| |
* PowerPC assembler:: Deviations and special cases |
| * Other assemblers:: How to write them |
* Other assemblers:: How to write them |
| |
|
| Tools |
Tools |
| |
|
| * ANS Report:: Report the words used, sorted by wordset. |
* ANS Report:: Report the words used, sorted by wordset. |
| |
* Stack depth changes:: Where does this stack item come from? |
| |
|
| ANS conformance |
ANS conformance |
| |
|
| In addition to the @command{gforth} engine, there is also an engine |
In addition to the @command{gforth} engine, there is also an engine |
| called @command{gforth-fast}, which is faster, but gives less |
called @command{gforth-fast}, which is faster, but gives less |
| informative error messages (@pxref{Error messages}) and may catch some |
informative error messages (@pxref{Error messages}) and may catch some |
| stack underflows later or not at all. You should use it for debugged, |
errors (in particular, stack underflows and integer division errors) |
| |
later or not at all. You should use it for debugged, |
| performance-critical programs. |
performance-critical programs. |
| |
|
| Moreover, there is an engine called @command{gforth-itc}, which is |
Moreover, there is an engine called @command{gforth-itc}, which is |
| Allocate @i{size} space for the locals stack instead of using the |
Allocate @i{size} space for the locals stack instead of using the |
| default specified in the image (typically 14.5K). |
default specified in the image (typically 14.5K). |
| |
|
| |
@cindex --vm-commit, command-line option |
| |
@cindex overcommit memory for dictionary and stacks |
| |
@cindex memory overcommit for dictionary and stacks |
| |
@item --vm-commit |
| |
Normally, Gforth tries to start up even if there is not enough virtual |
| |
memory for the dictionary and the stacks (using @code{MAP_NORESERVE} |
| |
on OSs that support it); so you can ask for a really big dictionary |
| |
and/or stacks, and as long as you don't use more virtual memory than |
| |
is available, everything will be fine (but if you use more, processes |
| |
get killed). With this option you just use the default allocation |
| |
policy of the OS; for OSs that don't overcommit (e.g., Solaris), this |
| |
means that you cannot and should not ask for as big dictionary and |
| |
stacks, but once Gforth successfully starts up, out-of-memory won't |
| |
kill it. |
| |
|
| @cindex -h, command-line option |
@cindex -h, command-line option |
| @cindex --help, command-line option |
@cindex --help, command-line option |
| @item --help |
@item --help |
| severely broken (such that it causes another signal before recovering |
severely broken (such that it causes another signal before recovering |
| from the first); this option avoids endless loops in such cases. |
from the first); this option avoids endless loops in such cases. |
| |
|
| |
@cindex --no-dynamic, command-line option |
| |
@cindex --dynamic, command-line option |
| @item --no-dynamic |
@item --no-dynamic |
| @item --dynamic |
@item --dynamic |
| Disable or enable dynamic superinstructions with replication |
Disable or enable dynamic superinstructions with replication |
| (@pxref{Dynamic Superinstructions}). |
(@pxref{Dynamic Superinstructions}). |
| |
|
| |
@cindex --no-super, command-line option |
| @item --no-super |
@item --no-super |
| Disable dynamic superinstructions, use just dynamic replication; this is |
Disable dynamic superinstructions, use just dynamic replication; this is |
| useful if you want to patch threaded code (@pxref{Dynamic |
useful if you want to patch threaded code (@pxref{Dynamic |
| Superinstructions}). |
Superinstructions}). |
| |
|
| |
@cindex --ss-number, command-line option |
| |
@item --ss-number=@var{N} |
| |
Use only the first @var{N} static superinstructions compiled into the |
| |
engine (default: use them all; note that only @code{gforth-fast} has |
| |
any). This option is useful for measuring the performance impact of |
| |
static superinstructions. |
| |
|
| |
@cindex --ss-min-..., command-line options |
| |
@item --ss-min-codesize |
| |
@item --ss-min-ls |
| |
@item --ss-min-lsu |
| |
@item --ss-min-nexts |
| |
Use specified metric for determining the cost of a primitive or static |
| |
superinstruction for static superinstruction selection. @code{Codesize} |
| |
is the native code size of the primive or static superinstruction, |
| |
@code{ls} is the number of loads and stores, @code{lsu} is the number of |
| |
loads, stores, and updates, and @code{nexts} is the number of dispatches |
| |
(not taking dynamic superinstructions into account), i.e. every |
| |
primitive or static superinstruction has cost 1. Default: |
| |
@code{codesize} if you use dynamic code generation, otherwise |
| |
@code{nexts}. |
| |
|
| |
@cindex --ss-greedy, command-line option |
| |
@item --ss-greedy |
| |
This option is useful for measuring the performance impact of static |
| |
superinstructions. By default, an optimal shortest-path algorithm is |
| |
used for selecting static superinstructions. With @option{--ss-greedy} |
| |
this algorithm is modified to assume that anything after the static |
| |
superinstruction currently under consideration is not combined into |
| |
static superinstructions. With @option{--ss-min-nexts} this produces |
| |
the same result as a greedy algorithm that always selects the longest |
| |
superinstruction available at the moment. E.g., if there are |
| |
superinstructions AB and BCD, then for the sequence A B C D the optimal |
| |
algorithm will select A BCD and the greedy algorithm will select AB C D. |
| |
|
| |
@cindex --print-metrics, command-line option |
| |
@item --print-metrics |
| |
Prints some metrics used during static superinstruction selection: |
| |
@code{code size} is the actual size of the dynamically generated code. |
| |
@code{Metric codesize} is the sum of the codesize metrics as seen by |
| |
static superinstruction selection; there is a difference from @code{code |
| |
size}, because not all primitives and static superinstructions are |
| |
compiled into dynamically generated code, and because of markers. The |
| |
other metrics correspond to the @option{ss-min-...} options. This |
| |
option is useful for evaluating the effects of the @option{--ss-...} |
| |
options. |
| |
|
| @end table |
@end table |
| |
|
| @cindex loading files at startup |
@cindex loading files at startup |
| default image @file{gforth.fi} consist of a sequence of filenames and |
default image @file{gforth.fi} consist of a sequence of filenames and |
| @code{-e @var{forth-code}} options that are interpreted in the sequence |
@code{-e @var{forth-code}} options that are interpreted in the sequence |
| in which they are given. The @code{-e @var{forth-code}} or |
in which they are given. The @code{-e @var{forth-code}} or |
| @code{--evaluate @var{forth-code}} option evaluates the Forth |
@code{--evaluate @var{forth-code}} option evaluates the Forth code. This |
| code. This option takes only one argument; if you want to evaluate more |
option takes only one argument; if you want to evaluate more Forth |
| Forth words, you have to quote them or use @code{-e} several times. To exit |
words, you have to quote them or use @code{-e} several times. To exit |
| after processing the command line (instead of entering interactive mode) |
after processing the command line (instead of entering interactive mode) |
| append @code{-e bye} to the command line. |
append @code{-e bye} to the command line. You can also process the |
| |
command-line arguments with a Forth program (@pxref{OS command line |
| |
arguments}). |
| |
|
| @cindex versions, invoking other versions of Gforth |
@cindex versions, invoking other versions of Gforth |
| If you have several versions of Gforth installed, @code{gforth} will |
If you have several versions of Gforth installed, @code{gforth} will |
| for Forth source-code files. |
for Forth source-code files. |
| |
|
| @item |
@item |
| |
@cindex @code{LANG} -- environment variable |
| |
@code{LANG} -- see @code{LC_CTYPE} |
| |
|
| |
@item |
| |
@cindex @code{LC_ALL} -- environment variable |
| |
@code{LC_ALL} -- see @code{LC_CTYPE} |
| |
|
| |
@item |
| |
@cindex @code{LC_CTYPE} -- environment variable |
| |
@code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth |
| |
startup, Gforth uses the UTF-8 encoding for strings internally and |
| |
expects its input and produces its output in UTF-8 encoding, otherwise |
| |
the encoding is 8bit (see @pxref{Xchars and Unicode}). If this |
| |
environment variable is unset, Gforth looks in @code{LC_ALL}, and if |
| |
that is unset, in @code{LANG}. |
| |
|
| |
@item |
| |
@cindex @code{GFORTHSYSTEMPREFIX} -- environment variable |
| |
|
| |
@code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument |
| |
of @code{system} before passing it to C's @code{system()}. Default: |
| |
@code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix |
| |
and the command are directly concatenated, so if a space between them is |
| |
necessary, append it to the prefix. |
| |
|
| |
@item |
| @cindex @code{GFORTH} -- environment variable |
@cindex @code{GFORTH} -- environment variable |
| @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}. |
@code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}. |
| |
|
| @section Syntax |
@section Syntax |
| @cindex syntax tutorial |
@cindex syntax tutorial |
| |
|
| A @dfn{word} is a sequence of arbitrary characters (expcept white |
A @dfn{word} is a sequence of arbitrary characters (except white |
| space). Words are separated by white space. E.g., each of the |
space). Words are separated by white space. E.g., each of the |
| following lines contains exactly one word: |
following lines contains exactly one word: |
| |
|
| In general, words consume their stack arguments (@code{.s} is an |
In general, words consume their stack arguments (@code{.s} is an |
| exception). |
exception). |
| |
|
| @assignment |
@quotation Assignment |
| What does the stack contain after @code{5 6 7 .}? |
What does the stack contain after @code{5 6 7 .}? |
| @endassignment |
@end quotation |
| |
|
| |
|
| @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial |
@node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial |
| 3 4 5 * + . |
3 4 5 * + . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| What are the infix expressions corresponding to the Forth code above? |
What are the infix expressions corresponding to the Forth code above? |
| Write @code{6-7*8+9} in Forth notation@footnote{This notation is also |
Write @code{6-7*8+9} in Forth notation@footnote{This notation is also |
| known as Postfix or RPN (Reverse Polish Notation).}. |
known as Postfix or RPN (Reverse Polish Notation).}. |
| @endassignment |
@end quotation |
| |
|
| To change the sign, use @code{negate}: |
To change the sign, use @code{negate}: |
| |
|
| 2 negate . |
2 negate . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Convert -(-3)*4-5 to Forth. |
Convert -(-3)*4-5 to Forth. |
| @endassignment |
@end quotation |
| |
|
| @code{/mod} performs both @code{/} and @code{mod}. |
@code{/mod} performs both @code{/} and @code{mod}. |
| |
|
| 1 2 .s tuck .s 2drop drop |
1 2 .s tuck .s 2drop drop |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Replace @code{nip} and @code{tuck} with combinations of other stack |
Replace @code{nip} and @code{tuck} with combinations of other stack |
| manipulation words. |
manipulation words. |
| |
|
| 1 2 3 1 2 3 4 |
1 2 3 1 2 3 4 |
| 1 2 3 1 3 |
1 2 3 1 3 |
| @end example |
@end example |
| @endassignment |
@end quotation |
| |
|
| @example |
@example |
| 5 dup * . |
5 dup * . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write 17^3 and 17^4 in Forth, without writing @code{17} more than once. |
Write 17^3 and 17^4 in Forth, without writing @code{17} more than once. |
| Write a piece of Forth code that expects two numbers on the stack |
Write a piece of Forth code that expects two numbers on the stack |
| (@var{a} and @var{b}, with @var{b} on top) and computes |
(@var{a} and @var{b}, with @var{b} on top) and computes |
| @code{(a-b)(a+1)}. |
@code{(a-b)(a+1)}. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Stack Manipulation}. |
Reference: @ref{Stack Manipulation}. |
| |
|
| 3 fourth-power . |
3 fourth-power . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and |
Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and |
| @code{/mod} in terms of other Forth words, and check if they work (hint: |
@code{/mod} in terms of other Forth words, and check if they work (hint: |
| test your tests on the originals first). Don't let the |
test your tests on the originals first). Don't let the |
| @samp{redefined}-Messages spook you, they are just warnings. |
@samp{redefined}-Messages spook you, they are just warnings. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Colon Definitions}. |
Reference: @ref{Colon Definitions}. |
| |
|
| @cindex stack-effect comments, tutorial |
@cindex stack-effect comments, tutorial |
| @cindex --, tutorial |
@cindex --, tutorial |
| By convention the comment after the name of a definition describes the |
By convention the comment after the name of a definition describes the |
| stack effect: The part in from of the @samp{--} describes the state of |
stack effect: The part in front of the @samp{--} describes the state of |
| the stack before the execution of the definition, i.e., the parameters |
the stack before the execution of the definition, i.e., the parameters |
| that are passed into the colon definition; the part behind the @samp{--} |
that are passed into the colon definition; the part behind the @samp{--} |
| is the state of the stack after the execution of the definition, i.e., |
is the state of the stack after the execution of the definition, i.e., |
| just @code{( -- )}. You should also add some descriptive comment to |
just @code{( -- )}. You should also add some descriptive comment to |
| more complicated words (I usually do this in the lines following |
more complicated words (I usually do this in the lines following |
| @code{:}). If you don't do this, your code becomes unreadable (because |
@code{:}). If you don't do this, your code becomes unreadable (because |
| you have to work through every definition before you can undertsand |
you have to work through every definition before you can understand |
| any). |
any). |
| |
|
| @assignment |
@quotation Assignment |
| The stack effect of @code{swap} can be written like this: @code{x1 x2 -- |
The stack effect of @code{swap} can be written like this: @code{x1 x2 -- |
| x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup}, |
x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup}, |
| @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you |
@code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you |
| are done, you can compare your stack effects to those in this manual |
are done, you can compare your stack effects to those in this manual |
| (@pxref{Word Index}). |
(@pxref{Word Index}). |
| @endassignment |
@end quotation |
| |
|
| Sometimes programmers put comments at various places in colon |
Sometimes programmers put comments at various places in colon |
| definitions that describe the contents of the stack at that place (stack |
definitions that describe the contents of the stack at that place (stack |
| |
|
| You can find a more complete list in @ref{Notation}. |
You can find a more complete list in @ref{Notation}. |
| |
|
| @assignment |
@quotation Assignment |
| Write stack-effect comments for all definitions you have written up to |
Write stack-effect comments for all definitions you have written up to |
| now. |
now. |
| @endassignment |
@end quotation |
| |
|
| |
|
| @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial |
@node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial |
| function; and since there is only one result, you don't have to deal with |
function; and since there is only one result, you don't have to deal with |
| the order of results, either. |
the order of results, either. |
| |
|
| In Forth (and other stack-based languages, e.g., Postscript) the |
In Forth (and other stack-based languages, e.g., PostScript) the |
| parameter and result order of a definition is important and should be |
parameter and result order of a definition is important and should be |
| designed well. The general guideline is to design the stack effect such |
designed well. The general guideline is to design the stack effect such |
| that the word is simple to use in most cases, even if that complicates |
that the word is simple to use in most cases, even if that complicates |
| a constant), pass it on the top of the stack. Conversely, parameters |
a constant), pass it on the top of the stack. Conversely, parameters |
| that usually require a long sequence of code to compute should be passed |
that usually require a long sequence of code to compute should be passed |
| as the bottom (i.e., first) parameter. This makes the code easier to |
as the bottom (i.e., first) parameter. This makes the code easier to |
| read, because reader does not need to keep track of the bottom item |
read, because the reader does not need to keep track of the bottom item |
| through a long sequence of code (or, alternatively, through stack |
through a long sequence of code (or, alternatively, through stack |
| manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the |
manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the |
| address on top of the stack because it is usually simpler to compute |
address on top of the stack because it is usually simpler to compute |
| In Gforth you can have several locals definitions, anywhere in a colon |
In Gforth you can have several locals definitions, anywhere in a colon |
| definition; in contrast, in a standard program you can have only one |
definition; in contrast, in a standard program you can have only one |
| locals definition per colon definition, and that locals definition must |
locals definition per colon definition, and that locals definition must |
| be outside any controll structure. |
be outside any control structure. |
| |
|
| With locals you can write slightly longer definitions without running |
With locals you can write slightly longer definitions without running |
| into stack trouble. However, I recommend trying to write colon |
into stack trouble. However, I recommend trying to write colon |
| definitions without locals for exercise purposes to help you gain the |
definitions without locals for exercise purposes to help you gain the |
| essential factoring skills. |
essential factoring skills. |
| |
|
| @assignment |
@quotation Assignment |
| Rewrite your definitions until now with locals |
Rewrite your definitions until now with locals |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Locals}. |
Reference: @ref{Locals}. |
| |
|
| @code{if} takes a flag from the stack. If the flag is non-zero (true), |
@code{if} takes a flag from the stack. If the flag is non-zero (true), |
| the following code is performed, otherwise execution continues after the |
the following code is performed, otherwise execution continues after the |
| @code{endif} (or @code{else}). @code{<} compares the top two stack |
@code{endif} (or @code{else}). @code{<} compares the top two stack |
| elements and prioduces a flag: |
elements and produces a flag: |
| |
|
| @example |
@example |
| 1 2 < . |
1 2 < . |
| 3 2 min . |
3 2 min . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write @code{min} without @code{else}-part (hint: what's the definition |
Write @code{min} without @code{else}-part (hint: what's the definition |
| of @code{nip}?). |
of @code{nip}?). |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Selection}. |
Reference: @ref{Selection}. |
| |
|
| these combinations are standard (for details see the standard, |
these combinations are standard (for details see the standard, |
| @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}). |
@ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}). |
| |
|
| You can use @code{and or xor invert} can be used as operations on |
You can use @code{and or xor invert} as operations on canonical flags. |
| canonical flags. Actually they are bitwise operations: |
Actually they are bitwise operations: |
| |
|
| @example |
@example |
| 1 2 and . |
1 2 and . |
| 1 foo . |
1 foo . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write @code{min} without @code{if}. |
Write @code{min} without @code{if}. |
| @endassignment |
@end quotation |
| |
|
| For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and |
For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and |
| @ref{Bitwise operations}. |
@ref{Bitwise operations}. |
| @code{Until} consumes a flag; if it is non-zero, execution continues at |
@code{Until} consumes a flag; if it is non-zero, execution continues at |
| the @code{begin}, otherwise after the @code{until}. |
the @code{begin}, otherwise after the @code{until}. |
| |
|
| @assignment |
@quotation Assignment |
| Write a definition for computing the greatest common divisor. |
Write a definition for computing the greatest common divisor. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Simple Loops}. |
Reference: @ref{Simple Loops}. |
| |
|
| |
|
| @example |
@example |
| : ^ ( n1 u -- n ) |
: ^ ( n1 u -- n ) |
| \ n = the uth power of u1 |
\ n = the uth power of n1 |
| 1 swap 0 u+do |
1 swap 0 u+do |
| over * |
over * |
| loop |
loop |
| There is also @code{+do}, which expects signed numbers (important for |
There is also @code{+do}, which expects signed numbers (important for |
| deciding whether to enter the loop). |
deciding whether to enter the loop). |
| |
|
| @assignment |
@quotation Assignment |
| Write a definition for computing the nth Fibonacci number. |
Write a definition for computing the nth Fibonacci number. |
| @endassignment |
@end quotation |
| |
|
| You can also use increments other than 1: |
You can also use increments other than 1: |
| |
|
| earlier definitions are usually visible: |
earlier definitions are usually visible: |
| |
|
| @example |
@example |
| 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms |
1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms |
| : / ( n1 n2 -- n ) |
: / ( n1 n2 -- n ) |
| dup 0= if |
dup 0= if |
| -10 throw \ report division by zero |
-10 throw \ report division by zero |
| 8 fac2 . |
8 fac2 . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write a recursive definition for computing the nth Fibonacci number. |
Write a recursive definition for computing the nth Fibonacci number. |
| @endassignment |
@end quotation |
| |
|
| Reference (including indirect recursion): @xref{Calls and returns}. |
Reference (including indirect recursion): @xref{Calls and returns}. |
| |
|
| @code{>r} takes an element from the data stack and pushes it onto the |
@code{>r} takes an element from the data stack and pushes it onto the |
| return stack; conversely, @code{r>} moves an elementm from the return to |
return stack; conversely, @code{r>} moves an elementm from the return to |
| the data stack; @code{r@@} pushes a copy of the top of the return stack |
the data stack; @code{r@@} pushes a copy of the top of the return stack |
| on the return stack. |
on the data stack. |
| |
|
| Forth programmers usually use the return stack for storing data |
Forth programmers usually use the return stack for storing data |
| temporarily, if using the data stack alone would be too complex, and |
temporarily, if using the data stack alone would be too complex, and |
| standard; Gforth has no problem). However, they solve the same |
standard; Gforth has no problem). However, they solve the same |
| problems, so this shouldn't be an issue. |
problems, so this shouldn't be an issue. |
| |
|
| @assignment |
@quotation Assignment |
| Can you rewrite any of the definitions you wrote until now in a better |
Can you rewrite any of the definitions you wrote until now in a better |
| way using the return stack? |
way using the return stack? |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Return stack}. |
Reference: @ref{Return stack}. |
| |
|
| v3 5 cells dump |
v3 5 cells dump |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write a definition @code{vsum ( addr u -- n )} that computes the sum of |
Write a definition @code{vsum ( addr u -- n )} that computes the sum of |
| @code{u} cells, with the first of these cells at @code{addr}, the next |
@code{u} cells, with the first of these cells at @code{addr}, the next |
| one at @code{addr cell+} etc. |
one at @code{addr cell+} etc. |
| @endassignment |
@end quotation |
| |
|
| You can also reserve memory without creating a new word: |
You can also reserve memory without creating a new word: |
| |
|
| type |
type |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| @code{Emit ( c -- )} types @code{c} as character (not a number). |
@code{Emit ( c -- )} types @code{c} as character (not a number). |
| Implement @code{type ( addr u -- )}. |
Implement @code{type ( addr u -- )}. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{Memory Blocks}. |
Reference: @ref{Memory Blocks}. |
| |
|
| @item Closed the files. |
@item Closed the files. |
| @end enumerate |
@end enumerate |
| |
|
| |
Reference: @ref{General files}. |
| |
|
| @subsection Open file for input |
@subsection Open file for input |
| |
|
| @example |
@example |
| : close-output ( -- ) fd-out close-file throw ; |
: close-output ( -- ) fd-out close-file throw ; |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| How could you modify @code{copy-file} so that it copies until a second line is |
How could you modify @code{copy-file} so that it copies until a second line is |
| matched? Can you write a program that extracts a section of a text file, |
matched? Can you write a program that extracts a section of a text file, |
| given the line that starts and the line that terminates that section? |
given the line that starts and the line that terminates that section? |
| @endassignment |
@end quotation |
| |
|
| @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial |
@node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial |
| @section Interpretation and Compilation Semantics and Immediacy |
@section Interpretation and Compilation Semantics and Immediacy |
| 3 2 ' / catch .s |
3 2 ' / catch .s |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Try the same with @code{execute} instead of @code{catch}. |
Try the same with @code{execute} instead of @code{catch}. |
| @endassignment |
@end quotation |
| |
|
| @code{Throw} always jumps to the dynamically next enclosing |
@code{Throw} always jumps to the dynamically next enclosing |
| @code{catch}, even if it has to leave several call levels to achieve |
@code{catch}, even if it has to leave several call levels to achieve |
| ( ... n ) throw ; |
( ... n ) throw ; |
| @end example |
@end example |
| |
|
| Gforth provides an alternative syntax in addition to @code{catch}: |
However, this is still not safe against, e.g., the user pressing |
| @code{try ... recover ... endtry}. If the code between @code{try} and |
@kbd{Ctrl-C} when execution is between the @code{catch} and |
| @code{recover} has an exception, the stack depths are restored, the |
@code{restore-x}. |
| exception number is pushed on the stack, and the code between |
|
| @code{recover} and @code{endtry} is performed. E.g., the definition for |
Gforth provides an alternative exception handling syntax that is safe |
| @code{catch} is |
against such cases: @code{try ... restore ... endtry}. If the code |
| |
between @code{try} and @code{endtry} has an exception, the stack |
| @example |
depths are restored, the exception number is pushed on the stack, and |
| : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception |
the execution continues right after @code{restore}. |
| try |
|
| execute 0 |
|
| recover |
|
| nip |
|
| endtry ; |
|
| @end example |
|
| |
|
| The equivalent to the restoration code above is |
The safer equivalent to the restoration code above is |
| |
|
| @example |
@example |
| : ... |
: ... |
| save-x |
save-x |
| try |
try |
| word-changing-x 0 |
word-changing-x 0 |
| recover endtry |
restore |
| restore-x |
restore-x |
| |
endtry |
| throw ; |
throw ; |
| @end example |
@end example |
| |
|
| This works if @code{word-changing-x} does not change the stack depth, |
|
| otherwise you should add some code between @code{recover} and |
|
| @code{endtry} to balance the stack. |
|
| |
|
| Reference: @ref{Exception Handling}. |
Reference: @ref{Exception Handling}. |
| |
|
| |
|
| foo . |
foo . |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Define @code{defer ( "name" -- )}, which creates a word that stores an |
Define @code{defer ( "name" -- )}, which creates a word that stores an |
| XT (at the start the XT of @code{abort}), and upon execution |
XT (at the start the XT of @code{abort}), and upon execution |
| @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores |
@code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores |
| @code{xt} into @code{name}, a word defined with @code{defer}. Indirect |
@code{xt} into @code{name}, a word defined with @code{defer}. Indirect |
| recursion is one application of @code{defer}. |
recursion is one application of @code{defer}. |
| @endassignment |
@end quotation |
| |
|
| Reference: @ref{User-defined Defining Words}. |
Reference: @ref{User-defined Defining Words}. |
| |
|
| POSTPONE then ; immediate |
POSTPONE then ; immediate |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write @code{MY-2DUP} that has compilation semantics equivalent to |
Write @code{MY-2DUP} that has compilation semantics equivalent to |
| @code{2dup}, but compiles @code{over over}. |
@code{2dup}, but compiles @code{over over}. |
| @endassignment |
@end quotation |
| |
|
| @c !! @xref{Macros} for reference |
@c !! @xref{Macros} for reference |
| |
|
| see bar |
see bar |
| @end example |
@end example |
| |
|
| @assignment |
@quotation Assignment |
| Write @code{]L} which allows writing the example above as @code{: bar ( |
Write @code{]L} which allows writing the example above as @code{: bar ( |
| -- n ) [ 2 2 + ]L ;} |
-- n ) [ 2 2 + ]L ;} |
| @endassignment |
@end quotation |
| |
|
| @c !! @xref{Macros} for reference |
@c !! @xref{Macros} for reference |
| |
|
| Yes, the order of wordlists in the output of @code{order} is reversed |
Yes, the order of wordlists in the output of @code{order} is reversed |
| from stack comments and the output of @code{.s} and thus unintuitive. |
from stack comments and the output of @code{.s} and thus unintuitive. |
| |
|
| @assignment |
@quotation Assignment |
| Define @code{>order ( wid -- )} with adds @code{wid} as first searched |
Define @code{>order ( wid -- )} with adds @code{wid} as first searched |
| wordlist to the search order. Define @code{previous ( -- )}, which |
wordlist to the search order. Define @code{previous ( -- )}, which |
| removes the first searched wordlist from the search order. Experiment |
removes the first searched wordlist from the search order. Experiment |
| with boundary conditions (you will see some crashes or situations that |
with boundary conditions (you will see some crashes or situations that |
| are hard or impossible to leave). |
are hard or impossible to leave). |
| @endassignment |
@end quotation |
| |
|
| The search order is a powerful foundation for providing features similar |
The search order is a powerful foundation for providing features similar |
| to Modula-2 modules and C++ namespaces. However, trying to modularize |
to Modula-2 modules and C++ namespaces. However, trying to modularize |
| |
|
| @example |
@example |
| @kbd{qwer341@key{RET}} |
@kbd{qwer341@key{RET}} |
| :1: Undefined word |
*the terminal*:2: Undefined word |
| qwer341 |
>>>qwer341<<< |
| ^^^^^^^ |
Backtrace: |
| $400D2BA8 Bounce |
$2A95B42A20 throw |
| $400DBDA8 no.extensions |
$2A95B57FB8 no.extensions |
| @end example |
@end example |
| |
|
| The exact text, other than the ``Undefined word'' may differ slightly on |
The exact text, other than the ``Undefined word'' may differ slightly |
| your system, but the effect is the same; when the text interpreter |
on your system, but the effect is the same; when the text interpreter |
| detects an error, it discards any remaining text on a line, resets |
detects an error, it discards any remaining text on a line, resets |
| certain internal state and prints an error message. For a detailed description of error messages see @ref{Error |
certain internal state and prints an error message. For a detailed |
| messages}. |
description of error messages see @ref{Error messages}. |
| |
|
| The text interpreter waits for you to press carriage-return, and then |
The text interpreter waits for you to press carriage-return, and then |
| processes your input line. Starting at the beginning of the line, it |
processes your input line. Starting at the beginning of the line, it |
| |
|
| @example |
@example |
| @kbd{12 dup fred dup@key{RET}} |
@kbd{12 dup fred dup@key{RET}} |
| :1: Undefined word |
*the terminal*:3: Undefined word |
| 12 dup fred dup |
12 dup >>>fred<<< dup |
| ^^^^ |
Backtrace: |
| $400D2BA8 Bounce |
$2A95B42A20 throw |
| $400DBDA8 no.extensions |
$2A95B57FB8 no.extensions |
| @end example |
@end example |
| |
|
| When you press the carriage-return key, the text interpreter starts to |
When you press the carriage-return key, the text interpreter starts to |
| without affecting the stack. Type: |
without affecting the stack. Type: |
| |
|
| @example |
@example |
| @kbd{clearstack 1 2 3@key{RET}} ok |
@kbd{clearstacks 1 2 3@key{RET}} ok |
| @kbd{.s@key{RET}} <3> 1 2 3 ok |
@kbd{.s@key{RET}} <3> 1 2 3 ok |
| @end example |
@end example |
| |
|
| The text interpreter looks up the word @code{clearstack} and executes |
The text interpreter looks up the word @code{clearstacks} and executes |
| it; it tidies up the stack and removes any entries that may have been |
it; it tidies up the stacks and removes any entries that may have been |
| left on it by earlier examples. The text interpreter pushes each of the |
left on it by earlier examples. The text interpreter pushes each of the |
| three numbers in turn onto the stack. Finally, the text interpreter |
three numbers in turn onto the stack. Finally, the text interpreter |
| looks up the word @code{.s} and executes it. The effect of executing |
looks up the word @code{.s} and executes it. The effect of executing |
| |
|
| @example |
@example |
| @kbd{: add-two 2 + . ;@key{RET}} |
@kbd{: add-two 2 + . ;@key{RET}} |
| ^^^^^^^ |
*the terminal*:4: Undefined word |
| Error: Undefined word |
: >>>add-two<<< 2 + . ; |
| @end example |
@end example |
| |
|
| The reason that this didn't happen is bound up in the way that @code{:} |
The reason that this didn't happen is bound up in the way that @code{:} |
| * Files:: |
* Files:: |
| * Blocks:: |
* Blocks:: |
| * Other I/O:: |
* Other I/O:: |
| |
* OS command line arguments:: |
| * Locals:: |
* Locals:: |
| * Structures:: |
* Structures:: |
| * Object-oriented Forth:: |
* Object-oriented Forth:: |
| * Programming Tools:: |
* Programming Tools:: |
| |
* C Interface:: |
| * Assembler and Code Words:: |
* Assembler and Code Words:: |
| * Threading Words:: |
* Threading Words:: |
| * Passing Commands to the OS:: |
* Passing Commands to the OS:: |
| |
|
| doc-+ |
doc-+ |
| doc-1+ |
doc-1+ |
| |
doc-under+ |
| doc-- |
doc-- |
| doc-1- |
doc-1- |
| doc-* |
doc-* |
| doc-sf! |
doc-sf! |
| doc-df@ |
doc-df@ |
| doc-df! |
doc-df! |
| |
doc-sw@ |
| |
doc-uw@ |
| |
doc-w! |
| |
doc-sl@ |
| |
doc-ul@ |
| |
doc-l! |
| |
|
| @node Address arithmetic, Memory Blocks, Memory Access, Memory |
@node Address arithmetic, Memory Blocks, Memory Access, Memory |
| @subsection Address arithmetic |
@subsection Address arithmetic |
| doc-maxaligned |
doc-maxaligned |
| doc-cfaligned |
doc-cfaligned |
| doc-address-unit-bits |
doc-address-unit-bits |
| |
doc-/w |
| |
doc-/l |
| |
|
| @node Memory Blocks, , Address arithmetic, Memory |
@node Memory Blocks, , Address arithmetic, Memory |
| @subsection Memory Blocks |
@subsection Memory Blocks |
| doc--trailing |
doc--trailing |
| doc-/string |
doc-/string |
| doc-bounds |
doc-bounds |
| |
doc-pad |
| |
|
| @comment TODO examples |
@comment TODO examples |
| |
|
| @i{n2} OF @i{code2} ENDOF |
@i{n2} OF @i{code2} ENDOF |
| @dots{} |
@dots{} |
| ( n ) @i{default-code} ( n ) |
( n ) @i{default-code} ( n ) |
| ENDCASE |
ENDCASE ( ) |
| @end example |
@end example |
| |
|
| Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no |
Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If |
| @i{ni} matches, the optional @i{default-code} is executed. The optional |
no @i{ni} matches, the optional @i{default-code} is executed. The |
| default case can be added by simply writing the code after the last |
optional default case can be added by simply writing the code after |
| @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must |
the last @code{ENDOF}. It may use @i{n}, which is on top of the stack, |
| not consume it. |
but must not consume it. The value @i{n} is consumed by this |
| |
construction (either by a OF that matches, or by the ENDCASE, if no OF |
| |
matches). |
| |
|
| @progstyle |
@progstyle |
| To keep the code understandable, you should ensure that on all paths |
To keep the code understandable, you should ensure that you change the |
| through a selection construct the stack is changed in the same way |
stack in the same way (wrt. number and types of stack items consumed |
| (wrt. number and types of stack items consumed and pushed). |
and pushed) on all paths through a selection construct. |
| |
|
| @node Simple Loops, Counted Loops, Selection, Control Structures |
@node Simple Loops, Counted Loops, Selection, Control Structures |
| @subsection Simple Loops |
@subsection Simple Loops |
| IS foo |
IS foo |
| @end example |
@end example |
| |
|
| Deferred words are discussed in more detail in @ref{Deferred words}. |
Deferred words are discussed in more detail in @ref{Deferred Words}. |
| |
|
| The current definition returns control to the calling definition when |
The current definition returns control to the calling definition when |
| the end of the definition is reached or @code{EXIT} is encountered. |
the end of the definition is reached or @code{EXIT} is encountered. |
| The ANS Forth way to catch exceptions is @code{catch}: |
The ANS Forth way to catch exceptions is @code{catch}: |
| |
|
| doc-catch |
doc-catch |
| |
doc-nothrow |
| |
|
| The most common use of exception handlers is to clean up the state when |
The most common use of exception handlers is to clean up the state when |
| an error happens. E.g., |
an error happens. E.g., |
| @example |
@example |
| ['] foo catch |
['] foo catch |
| CASE |
CASE |
| myerror OF ... ( do something about it ) ENDOF |
myerror OF ... ( do something about it ) nothrow ENDOF |
| dup throw \ default: pass other errors on, do nothing on non-errors |
dup throw \ default: pass other errors on, do nothing on non-errors |
| ENDCASE |
ENDCASE |
| @end example |
@end example |
| @example |
@example |
| TRY |
TRY |
| @i{code1} |
@i{code1} |
| RECOVER \ optional |
IFERROR |
| @i{code2} \ optional |
@i{code2} |
| |
THEN |
| |
@i{code3} |
| ENDTRY |
ENDTRY |
| @end example |
@end example |
| |
|
| This performs @i{Code1}. If @i{code1} completes normally, execution |
This performs @i{code1}. If @i{code1} completes normally, execution |
| continues after the @code{endtry}. If @i{Code1} throws, the stacks are |
continues with @i{code3}. If @i{code1} or there is an exception |
| reset to the state during @code{try}, the throw value is pushed on the |
before @code{endtry}, the stacks are reset to the state during |
| data stack, and execution constinues at @i{code2}, and finally falls |
@code{try}, the throw value is pushed on the data stack, and execution |
| through the @code{endtry} into the following code. |
constinues at @i{code2}, and finally falls through the @i{code3}. |
| |
|
| doc-try |
doc-try |
| doc-recover |
|
| doc-endtry |
doc-endtry |
| |
doc-iferror |
| |
|
| |
If you don't need @i{code2}, you can write @code{restore} instead of |
| |
@code{iferror then}: |
| |
|
| |
@example |
| |
TRY |
| |
@i{code1} |
| |
RESTORE |
| |
@i{code3} |
| |
ENDTRY |
| |
@end example |
| |
|
| |
@cindex unwind-protect |
| The cleanup example from above in this syntax: |
The cleanup example from above in this syntax: |
| |
|
| @example |
@example |
| base @ >r TRY |
base @@ @{ oldbase @} |
| |
TRY |
| hex foo \ now the hex is placed correctly |
hex foo \ now the hex is placed correctly |
| 0 \ value for throw |
0 \ value for throw |
| RECOVER ENDTRY |
RESTORE |
| r> base ! throw |
oldbase base ! |
| |
ENDTRY |
| |
throw |
| @end example |
@end example |
| |
|
| And here's the error handling example: |
An additional advantage of this variant is that an exception between |
| |
@code{restore} and @code{endtry} (e.g., from the user pressing |
| |
@kbd{Ctrl-C}) restarts the execution of the code after @code{restore}, |
| |
so the base will be restored under all circumstances. |
| |
|
| |
However, you have to ensure that this code does not cause an exception |
| |
itself, otherwise the @code{iferror}/@code{restore} code will loop. |
| |
Moreover, you should also make sure that the stack contents needed by |
| |
the @code{iferror}/@code{restore} code exist everywhere between |
| |
@code{try} and @code{endtry}; in our example this is achived by |
| |
putting the data in a local before the @code{try} (you cannot use the |
| |
return stack because the exception frame (@i{sys1}) is in the way |
| |
there). |
| |
|
| |
This kind of usage corresponds to Lisp's @code{unwind-protect}. |
| |
|
| |
@cindex @code{recover} (old Gforth versions) |
| |
If you do not want this exception-restarting behaviour, you achieve |
| |
this as follows: |
| |
|
| @example |
@example |
| TRY |
TRY |
| foo |
@i{code1} |
| |
ENDTRY-IFERROR |
| |
@i{code2} |
| |
THEN |
| |
@end example |
| |
|
| |
If there is an exception in @i{code1}, then @i{code2} is executed, |
| |
otherwise execution continues behind the @code{then} (or in a possible |
| |
@code{else} branch). This corresponds to the construct |
| |
|
| |
@example |
| |
TRY |
| |
@i{code1} |
| RECOVER |
RECOVER |
| |
@i{code2} |
| |
ENDTRY |
| |
@end example |
| |
|
| |
in Gforth before version 0.7. So you can directly replace |
| |
@code{recover}-using code; however, we recommend that you check if it |
| |
would not be better to use one of the other @code{try} variants while |
| |
you are at it. |
| |
|
| |
To ease the transition, Gforth provides two compatibility files: |
| |
@file{endtry-iferror.fs} provides the @code{try ... endtry-iferror |
| |
... then} syntax (but not @code{iferror} or @code{restore}) for old |
| |
systems; @file{recover-endtry.fs} provides the @code{try ... recover |
| |
... endtry} syntax on new systems, so you can use that file as a |
| |
stopgap to run old programs. Both files work on any system (they just |
| |
do nothing if the system already has the syntax it implements), so you |
| |
can unconditionally @code{require} one of these files, even if you use |
| |
a mix old and new systems. |
| |
|
| |
doc-restore |
| |
doc-endtry-iferror |
| |
|
| |
Here's the error handling example: |
| |
|
| |
@example |
| |
TRY |
| |
foo |
| |
ENDTRY-IFERROR |
| CASE |
CASE |
| myerror OF ... ( do something about it ) ENDOF |
myerror OF ... ( do something about it ) nothrow ENDOF |
| throw \ pass other errors on |
throw \ pass other errors on |
| ENDCASE |
ENDCASE |
| ENDTRY |
THEN |
| @end example |
@end example |
| |
|
| @progstyle |
@progstyle |
| * Anonymous Definitions:: Definitions without names |
* Anonymous Definitions:: Definitions without names |
| * Supplying names:: Passing definition names as strings |
* Supplying names:: Passing definition names as strings |
| * User-defined Defining Words:: |
* User-defined Defining Words:: |
| * Deferred words:: Allow forward references |
* Deferred Words:: Allow forward references |
| * Aliases:: |
* Aliases:: |
| @end menu |
@end menu |
| |
|
| @example |
@example |
| CREATE text-buf 80 chars allot |
CREATE text-buf 80 chars allot |
| |
|
| text-buf 0 chars c@@ \ the 1st character (offset 0) |
text-buf 0 chars + c@@ \ the 1st character (offset 0) |
| text-buf 3 chars c@@ \ the 4th character (offset 3) |
text-buf 3 chars + c@@ \ the 4th character (offset 3) |
| @end example |
@end example |
| |
|
| You can build arbitrarily complex data structures by allocating |
You can build arbitrarily complex data structures by allocating |
| @code{nextname} works with any defining word. |
@code{nextname} works with any defining word. |
| |
|
| |
|
| @node User-defined Defining Words, Deferred words, Supplying names, Defining Words |
@node User-defined Defining Words, Deferred Words, Supplying names, Defining Words |
| @subsection User-defined Defining Words |
@subsection User-defined Defining Words |
| @cindex user-defined defining words |
@cindex user-defined defining words |
| @cindex defining words, user-defined |
@cindex defining words, user-defined |
| : foo |
: foo |
| 107645672 stats + - ; |
107645672 stats + - ; |
| |
|
| \ use ' stats . to show that 107645672 is the xt for stats |
\ use ' foo . to show that 107645672 is the xt for foo |
| @end example |
@end example |
| |
|
| You can use techniques like this to make new defining words in terms of |
You can use techniques like this to make new defining words in terms of |
| * CREATE..DOES> applications:: |
* CREATE..DOES> applications:: |
| * CREATE..DOES> details:: |
* CREATE..DOES> details:: |
| * Advanced does> usage example:: |
* Advanced does> usage example:: |
| * @code{Const-does>}:: |
* Const-does>:: |
| @end menu |
@end menu |
| |
|
| @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words |
@node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words |
| |
|
| doc->body |
doc->body |
| |
|
| @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words |
@node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words |
| @subsubsection Advanced does> usage example |
@subsubsection Advanced does> usage example |
| |
|
| The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words |
The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words |
| understand this, but it may improve your understanding of Forth. |
understand this, but it may improve your understanding of Forth. |
| |
|
| |
|
| @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words |
@node Const-does>, , Advanced does> usage example, User-defined Defining Words |
| @subsubsection @code{Const-does>} |
@subsubsection @code{Const-does>} |
| |
|
| A frequent use of @code{create}...@code{does>} is for transferring some |
A frequent use of @code{create}...@code{does>} is for transferring some |
| @file{compat/const-does.fs}. |
@file{compat/const-does.fs}. |
| |
|
| |
|
| @node Deferred words, Aliases, User-defined Defining Words, Defining Words |
@node Deferred Words, Aliases, User-defined Defining Words, Defining Words |
| @subsection Deferred words |
@subsection Deferred Words |
| @cindex deferred words |
@cindex deferred words |
| |
|
| The defining word @code{Defer} allows you to define a word by name |
The defining word @code{Defer} allows you to define a word by name |
| : bar ... greet ... ; |
: bar ... greet ... ; |
| : greet1 ( -- ) ." Good morning" ; |
: greet1 ( -- ) ." Good morning" ; |
| : greet2 ( -- ) ." Hello" ; |
: greet2 ( -- ) ." Hello" ; |
| ' greet2 <IS> greet \ make greet behave like greet2 |
' greet2 IS greet \ make greet behave like greet2 |
| @end example |
@end example |
| |
|
| @progstyle |
@progstyle |
| @example |
@example |
| : real: : ; \ retain access to the original |
: real: : ; \ retain access to the original |
| defer : \ redefine as a deferred word |
defer : \ redefine as a deferred word |
| ' my: <IS> : \ use special version of : |
' my: IS : \ use special version of : |
| \ |
\ |
| \ load application here |
\ load application here |
| \ |
\ |
| ' real: <IS> : \ go back to the original |
' real: IS : \ go back to the original |
| @end example |
@end example |
| |
|
| |
|
| One thing to note is that @code{<IS>} consumes its name when it is |
One thing to note is that @code{IS} has special compilation semantics, |
| executed. If you want to specify the name at compile time, use |
such that it parses the name at compile time (like @code{TO}): |
| @code{[IS]}: |
|
| |
|
| @example |
@example |
| : set-greet ( xt -- ) |
: set-greet ( xt -- ) |
| [IS] greet ; |
IS greet ; |
| |
|
| ' greet1 set-greet |
' greet1 set-greet |
| @end example |
@end example |
| |
|
| |
In situations where @code{IS} does not fit, use @code{defer!} instead. |
| |
|
| A deferred word can only inherit execution semantics from the xt |
A deferred word can only inherit execution semantics from the xt |
| (because that is all that an xt can represent -- for more discussion of |
(because that is all that an xt can represent -- for more discussion of |
| this @pxref{Tokens for Words}); by default it will have default |
this @pxref{Tokens for Words}); by default it will have default |
| semantics of the deferred word in the usual ways: |
semantics of the deferred word in the usual ways: |
| |
|
| @example |
@example |
| : bar .... ; compile-only |
: bar .... ; immediate |
| Defer fred immediate |
Defer fred immediate |
| Defer jim |
Defer jim |
| |
|
| ' bar <IS> jim \ jim has default semantics |
' bar IS jim \ jim has default semantics |
| ' bar <IS> fred \ fred is immediate |
' bar IS fred \ fred is immediate |
| @end example |
@end example |
| |
|
| doc-defer |
doc-defer |
| doc-<is> |
doc-defer! |
| doc-[is] |
|
| doc-is |
doc-is |
| |
doc-defer@ |
| |
doc-action-of |
| @comment TODO document these: what's defers [is] |
@comment TODO document these: what's defers [is] |
| doc-what's |
|
| doc-defers |
doc-defers |
| |
|
| @c Use @code{words-deferred} to see a list of deferred words. |
@c Use @code{words-deferred} to see a list of deferred words. |
| |
|
| Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]} |
Definitions of these words (except @code{defers}) in ANS Forth are |
| are provided in @file{compat/defer.fs}. |
provided in @file{compat/defer.fs}. |
| |
|
| |
|
| @node Aliases, , Deferred words, Defining Words |
@node Aliases, , Deferred Words, Defining Words |
| @subsection Aliases |
@subsection Aliases |
| @cindex aliases |
@cindex aliases |
| |
|
| number) +12.E-4 |
number) +12.E-4 |
| @end itemize |
@end itemize |
| |
|
| By default, the number base used for integer number conversion is given |
By default, the number base used for integer number conversion is |
| by the contents of the variable @code{base}. Note that a lot of |
given by the contents of the variable @code{base}. Note that a lot of |
| confusion can result from unexpected values of @code{base}. If you |
confusion can result from unexpected values of @code{base}. If you |
| change @code{base} anywhere, make sure to save the old value and restore |
change @code{base} anywhere, make sure to save the old value and |
| it afterwards. In general I recommend keeping @code{base} decimal, and |
restore it afterwards; better yet, use @code{base-execute}, which does |
| |
this for you. In general I recommend keeping @code{base} decimal, and |
| using the prefixes described below for the popular non-decimal bases. |
using the prefixes described below for the popular non-decimal bases. |
| |
|
| doc-dpl |
doc-dpl |
| |
doc-base-execute |
| doc-base |
doc-base |
| doc-hex |
doc-hex |
| doc-decimal |
doc-decimal |
| |
|
| |
|
| @cindex '-prefix for character strings |
@cindex '-prefix for character strings |
| @cindex &-prefix for decimal numbers |
@cindex &-prefix for decimal numbers |
| |
@cindex #-prefix for decimal numbers |
| @cindex %-prefix for binary numbers |
@cindex %-prefix for binary numbers |
| @cindex $-prefix for hexadecimal numbers |
@cindex $-prefix for hexadecimal numbers |
| |
@cindex 0x-prefix for hexadecimal numbers |
| Gforth allows you to override the value of @code{base} by using a |
Gforth allows you to override the value of @code{base} by using a |
| prefix@footnote{Some Forth implementations provide a similar scheme by |
prefix@footnote{Some Forth implementations provide a similar scheme by |
| implementing @code{$} etc. as parsing words that process the subsequent |
implementing @code{$} etc. as parsing words that process the subsequent |
| @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions |
@cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions |
| 20(3) pages 26--27. In such implementations, unlike in Gforth, a space |
20(3) pages 26--27. In such implementations, unlike in Gforth, a space |
| is required between the prefix and the number.} before the first digit |
is required between the prefix and the number.} before the first digit |
| of an (integer) number. Four prefixes are supported: |
of an (integer) number. The following prefixes are supported: |
| |
|
| @itemize @bullet |
@itemize @bullet |
| @item |
@item |
| @code{&} -- decimal |
@code{&} -- decimal |
| @item |
@item |
| |
@code{#} -- decimal |
| |
@item |
| @code{%} -- binary |
@code{%} -- binary |
| @item |
@item |
| @code{$} -- hexadecimal |
@code{$} -- hexadecimal |
| @item |
@item |
| @code{'} -- base @code{max-char+1} |
@code{0x} -- hexadecimal, if base<33. |
| |
@item |
| |
@code{'} -- numeric value (e.g., ASCII code) of next character; an |
| |
optional @code{'} may be present after the character. |
| @end itemize |
@end itemize |
| |
|
| Here are some examples, with the equivalent decimal number shown after |
Here are some examples, with the equivalent decimal number shown after |
| in braces: |
in braces: |
| |
|
| -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number), |
-$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number), |
| 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66), |
'A (65), |
| 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98), |
-'a' (-97), |
| &905 (905), $abc (2478), $ABC (2478). |
&905 (905), $abc (2478), $ABC (2478). |
| |
|
| @cindex number conversion - traps for the unwary |
@cindex number conversion - traps for the unwary |
| @end itemize |
@end itemize |
| |
|
| You can read numbers into your programs with the words described in |
You can read numbers into your programs with the words described in |
| @ref{Input}. |
@ref{Line input and conversion}. |
| |
|
| @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter |
@node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter |
| @subsection Interpret/Compile states |
@subsection Interpret/Compile states |
| |
|
| @c anton: these belong in the input stream section |
@c anton: these belong in the input stream section |
| doc-parse |
doc-parse |
| |
doc-parse-name |
| doc-parse-word |
doc-parse-word |
| doc-name |
doc-name |
| doc-word |
doc-word |
| |
|
| doc-execute-parsing |
doc-execute-parsing |
| |
|
| |
A definition of this word in ANS Forth is provided in |
| |
@file{compat/execute-parsing.fs}. |
| |
|
| If you want to run a parsing word on a file, the following word should |
If you want to run a parsing word on a file, the following word should |
| help: |
help: |
| |
|
| @menu |
@menu |
| * Forth source files:: |
* Forth source files:: |
| * General files:: |
* General files:: |
| |
* Redirection:: |
| * Search Paths:: |
* Search Paths:: |
| @end menu |
@end menu |
| |
|
| @file{compat/required.fs}. |
@file{compat/required.fs}. |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node General files, Search Paths, Forth source files, Files |
@node General files, Redirection, Forth source files, Files |
| @subsection General files |
@subsection General files |
| @cindex general files |
@cindex general files |
| @cindex file-handling |
@cindex file-handling |
| doc-rename-file |
doc-rename-file |
| doc-read-file |
doc-read-file |
| doc-read-line |
doc-read-line |
| |
doc-key-file |
| |
doc-key?-file |
| doc-write-file |
doc-write-file |
| doc-write-line |
doc-write-line |
| doc-emit-file |
doc-emit-file |
| doc-stderr |
doc-stderr |
| |
|
| @c --------------------------------------------------------- |
@c --------------------------------------------------------- |
| @node Search Paths, , General files, Files |
@node Redirection, Search Paths, General files, Files |
| |
@subsection Redirection |
| |
@cindex Redirection |
| |
@cindex Input Redirection |
| |
@cindex Output Redirection |
| |
|
| |
You can redirect the output of @code{type} and @code{emit} and all the |
| |
words that use them (all output words that don't have an explicit |
| |
target file) to an arbitrary file with the @code{outfile-execute}, |
| |
used like this: |
| |
|
| |
@example |
| |
: some-warning ( n -- ) |
| |
cr ." warning# " . ; |
| |
|
| |
: print-some-warning ( n -- ) |
| |
['] some-warning stderr outfile-execute ; |
| |
@end example |
| |
|
| |
After @code{some-warning} is executed, the original output direction |
| |
is restored; this construct is safe against exceptions. Similarly, |
| |
there is @code{infile-execute} for redirecting the input of @code{key} |
| |
and its users (any input word that does not take a file explicitly). |
| |
|
| |
doc-outfile-execute |
| |
doc-infile-execute |
| |
|
| |
If you do not want to redirect the input or output to a file, you can |
| |
also make use of the fact that @code{key}, @code{emit} and @code{type} |
| |
are deferred words (@pxref{Deferred Words}). However, in that case |
| |
you have to worry about the restoration and the protection against |
| |
exceptions yourself; also, note that for redirecting the output in |
| |
this way, you have to redirect both @code{emit} and @code{type}. |
| |
|
| |
@c --------------------------------------------------------- |
| |
@node Search Paths, , Redirection, Files |
| @subsection Search Paths |
@subsection Search Paths |
| @cindex path for @code{included} |
@cindex path for @code{included} |
| @cindex file search path |
@cindex file search path |
| doc-list |
doc-list |
| doc-scr |
doc-scr |
| |
|
| doc---gforthman-block |
doc-block |
| doc-buffer |
doc-buffer |
| |
|
| doc-empty-buffers |
doc-empty-buffers |
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Other I/O, Locals, Blocks, Words |
@node Other I/O, OS command line arguments, Blocks, Words |
| @section Other I/O |
@section Other I/O |
| @cindex I/O - keyboard and display |
@cindex I/O - keyboard and display |
| |
|
| * Formatted numeric output:: Formatted (pictured) output |
* Formatted numeric output:: Formatted (pictured) output |
| * String Formats:: How Forth stores strings in memory |
* String Formats:: How Forth stores strings in memory |
| * Displaying characters and strings:: Other stuff |
* Displaying characters and strings:: Other stuff |
| * Input:: Input |
* Terminal output:: Cursor positioning etc. |
| |
* Single-key input:: |
| |
* Line input and conversion:: |
| * Pipes:: How to create your own pipes |
* Pipes:: How to create your own pipes |
| |
* Xchars and Unicode:: Non-ASCII characters |
| @end menu |
@end menu |
| |
|
| @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O |
@node Simple numeric output, Formatted numeric output, Other I/O, Other I/O |
| Blocks}. For words that display characters and strings see |
Blocks}. For words that display characters and strings see |
| @ref{Displaying characters and strings}. |
@ref{Displaying characters and strings}. |
| |
|
| @node Displaying characters and strings, Input, String Formats, Other I/O |
@node Displaying characters and strings, Terminal output, String Formats, Other I/O |
| @subsection Displaying characters and strings |
@subsection Displaying characters and strings |
| @cindex characters - compiling and displaying |
@cindex characters - compiling and displaying |
| @cindex character strings - compiling and displaying |
@cindex character strings - compiling and displaying |
| This section starts with a glossary of Forth words and ends with a set |
This section starts with a glossary of Forth words and ends with a set |
| of examples. |
of examples. |
| |
|
| |
|
| doc-bl |
doc-bl |
| doc-space |
doc-space |
| doc-spaces |
doc-spaces |
| doc-typewhite |
doc-typewhite |
| doc-cr |
doc-cr |
| @cindex cursor control |
@cindex cursor control |
| doc-at-xy |
|
| doc-page |
|
| doc-s" |
doc-s" |
| doc-s\" |
doc-s\" |
| doc-c" |
doc-c" |
| @end itemize |
@end itemize |
| |
|
| |
|
| |
@node Terminal output, Single-key input, Displaying characters and strings, Other I/O |
| |
@subsection Terminal output |
| |
@cindex output to terminal |
| |
@cindex terminal output |
| |
|
| |
If you are outputting to a terminal, you may want to control the |
| |
positioning of the cursor: |
| |
@cindex cursor positioning |
| |
|
| @node Input, Pipes, Displaying characters and strings, Other I/O |
doc-at-xy |
| @subsection Input |
|
| @cindex input |
|
| @cindex I/O - see input |
|
| @cindex parsing a string |
|
| |
|
| For ways of storing character strings in memory see @ref{String Formats}. |
In order to know where to position the cursor, it is often helpful to |
| |
know the size of the screen: |
| |
@cindex terminal size |
| |
|
| @comment TODO examples for >number >float accept key key? pad parse word refill |
doc-form |
| @comment then index them |
|
| |
|
| |
And sometimes you want to use: |
| |
@cindex clear screen |
| |
|
| |
doc-page |
| |
|
| |
Note that on non-terminals you should use @code{12 emit}, not |
| |
@code{page}, to get a form feed. |
| |
|
| |
|
| |
@node Single-key input, Line input and conversion, Terminal output, Other I/O |
| |
@subsection Single-key input |
| |
@cindex single-key input |
| |
@cindex input, single-key |
| |
|
| |
If you want to get a single printable character, you can use |
| |
@code{key}; to check whether a character is available for @code{key}, |
| |
you can use @code{key?}. |
| |
|
| doc-key |
doc-key |
| doc-key? |
doc-key? |
| |
|
| |
If you want to process a mix of printable and non-printable |
| |
characters, you can do that with @code{ekey} and friends. @code{Ekey} |
| |
produces a keyboard event that you have to convert into a character |
| |
with @code{ekey>char} or into a key identifier with @code{ekey>fkey}. |
| |
|
| |
Typical code for using EKEY looks like this: |
| |
|
| |
@example |
| |
ekey ekey>char if ( c ) |
| |
... \ do something with the character |
| |
else ekey>fkey if ( key-id ) |
| |
case |
| |
k-up of ... endof |
| |
k-f1 of ... endof |
| |
k-left k-shift-mask or k-ctrl-mask or of ... endof |
| |
... |
| |
endcase |
| |
else ( keyboard-event ) |
| |
drop \ just ignore an unknown keyboard event type |
| |
then then |
| |
@end example |
| |
|
| doc-ekey |
doc-ekey |
| doc-ekey? |
|
| doc-ekey>char |
doc-ekey>char |
| doc->number |
doc-ekey>fkey |
| doc->float |
doc-ekey? |
| |
|
| |
The key identifiers for cursor keys are: |
| |
|
| |
doc-k-left |
| |
doc-k-right |
| |
doc-k-up |
| |
doc-k-down |
| |
doc-k-home |
| |
doc-k-end |
| |
doc-k-prior |
| |
doc-k-next |
| |
doc-k-insert |
| |
doc-k-delete |
| |
|
| |
The key identifiers for function keys (aka keypad keys) are: |
| |
|
| |
doc-k-f1 |
| |
doc-k-f2 |
| |
doc-k-f3 |
| |
doc-k-f4 |
| |
doc-k-f5 |
| |
doc-k-f6 |
| |
doc-k-f7 |
| |
doc-k-f8 |
| |
doc-k-f9 |
| |
doc-k-f10 |
| |
doc-k-f11 |
| |
doc-k-f12 |
| |
|
| |
Note that @code{k-f11} and @code{k-f12} are not as widely available. |
| |
|
| |
You can combine these key identifiers with masks for various shift keys: |
| |
|
| |
doc-k-shift-mask |
| |
doc-k-ctrl-mask |
| |
doc-k-alt-mask |
| |
|
| |
Note that, even if a Forth system has @code{ekey>fkey} and the key |
| |
identifier words, the keys are not necessarily available or it may not |
| |
necessarily be able to report all the keys and all the possible |
| |
combinations with shift masks. Therefore, write your programs in such |
| |
a way that they are still useful even if the keys and key combinations |
| |
cannot be pressed or are not recognized. |
| |
|
| |
Examples: Older keyboards often do not have an F11 and F12 key. If |
| |
you run Gforth in an xterm, the xterm catches a number of combinations |
| |
(e.g., @key{Shift-Up}), and never passes it to Gforth. Finally, |
| |
Gforth currently does not recognize and report combinations with |
| |
multiple shift keys (so the @key{shift-ctrl-left} case in the example |
| |
above would never be entered). |
| |
|
| |
Gforth recognizes various keys available on ANSI terminals (in MS-DOS |
| |
you need the ANSI.SYS driver to get that behaviour); it works by |
| |
recognizing the escape sequences that ANSI terminals send when such a |
| |
key is pressed. If you have a terminal that sends other escape |
| |
sequences, you will not get useful results on Gforth. Other Forth |
| |
systems may work in a different way. |
| |
|
| |
|
| |
@node Line input and conversion, Pipes, Single-key input, Other I/O |
| |
@subsection Line input and conversion |
| |
@cindex line input from terminal |
| |
@cindex input, linewise from terminal |
| |
@cindex convertin strings to numbers |
| |
@cindex I/O - see input |
| |
|
| |
For ways of storing character strings in memory see @ref{String Formats}. |
| |
|
| |
@comment TODO examples for >number >float accept key key? pad parse word refill |
| |
@comment then index them |
| |
|
| |
Words for inputting one line from the keyboard: |
| |
|
| doc-accept |
doc-accept |
| doc-edit-line |
doc-edit-line |
| doc-pad |
|
| |
Conversion words: |
| |
|
| |
doc-s>number? |
| |
doc-s>unumber? |
| |
doc->number |
| |
doc->float |
| |
|
| |
|
| @comment obsolescent words.. |
@comment obsolescent words.. |
| |
Obsolescent input and conversion words: |
| |
|
| doc-convert |
doc-convert |
| doc-expect |
doc-expect |
| doc-span |
doc-span |
| |
|
| |
|
| @node Pipes, , Input, Other I/O |
@node Pipes, Xchars and Unicode, Line input and conversion, Other I/O |
| @subsection Pipes |
@subsection Pipes |
| @cindex pipes, creating your own |
@cindex pipes, creating your own |
| |
|
| |
|
| doc-broken-pipe-error |
doc-broken-pipe-error |
| |
|
| |
@node Xchars and Unicode, , Pipes, Other I/O |
| |
@subsection Xchars and Unicode |
| |
|
| |
This chapter needs completion |
| |
|
| |
@node OS command line arguments, Locals, Other I/O, Words |
| |
@section OS command line arguments |
| |
@cindex OS command line arguments |
| |
@cindex command line arguments, OS |
| |
@cindex arguments, OS command line |
| |
|
| |
The usual way to pass arguments to Gforth programs on the command line |
| |
is via the @option{-e} option, e.g. |
| |
|
| |
@example |
| |
gforth -e "123 456" foo.fs -e bye |
| |
@end example |
| |
|
| |
However, you may want to interpret the command-line arguments directly. |
| |
In that case, you can access the (image-specific) command-line arguments |
| |
through @code{next-arg}: |
| |
|
| |
doc-next-arg |
| |
|
| |
Here's an example program @file{echo.fs} for @code{next-arg}: |
| |
|
| |
@example |
| |
: echo ( -- ) |
| |
begin |
| |
next-arg 2dup 0 0 d<> while |
| |
type space |
| |
repeat |
| |
2drop ; |
| |
|
| |
echo cr bye |
| |
@end example |
| |
|
| |
This can be invoked with |
| |
|
| |
@example |
| |
gforth echo.fs hello world |
| |
@end example |
| |
|
| |
and it will print |
| |
|
| |
@example |
| |
hello world |
| |
@end example |
| |
|
| |
The next lower level of dealing with the OS command line are the |
| |
following words: |
| |
|
| |
doc-arg |
| |
doc-shift-args |
| |
|
| |
Finally, at the lowest level Gforth provides the following words: |
| |
|
| |
doc-argc |
| |
doc-argv |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Locals, Structures, Other I/O, Words |
@node Locals, Structures, OS command line arguments, Words |
| @section Locals |
@section Locals |
| @cindex locals |
@cindex locals |
| |
|
| * Structure Naming Convention:: |
* Structure Naming Convention:: |
| * Structure Implementation:: |
* Structure Implementation:: |
| * Structure Glossary:: |
* Structure Glossary:: |
| |
* Forth200x Structures:: |
| @end menu |
@end menu |
| |
|
| @node Why explicit structure support?, Structure Usage, Structures, Structures |
@node Why explicit structure support?, Structure Usage, Structures, Structures |
| offset. For a zero offset, the field is basically a noop; it is |
offset. For a zero offset, the field is basically a noop; it is |
| immediate, and therefore no code is generated when it is compiled. |
immediate, and therefore no code is generated when it is compiled. |
| |
|
| @node Structure Glossary, , Structure Implementation, Structures |
@node Structure Glossary, Forth200x Structures, Structure Implementation, Structures |
| @subsection Structure Glossary |
@subsection Structure Glossary |
| @cindex structure glossary |
@cindex structure glossary |
| |
|
| doc-struct |
doc-struct |
| |
|
| |
|
| |
@node Forth200x Structures, , Structure Glossary, Structures |
| |
@subsection Forth200x Structures |
| |
@cindex Structures in Forth200x |
| |
|
| |
The Forth 200x standard defines a slightly less convenient form of |
| |
structures. In general (when using @code{field+}, you have to perform |
| |
the alignment yourself, but there are a number of convenience words |
| |
(e.g., @code{field:} that perform the alignment for you. |
| |
|
| |
A typical usage example is: |
| |
|
| |
@example |
| |
0 |
| |
field: s-a |
| |
faligned 2 floats +field s-b |
| |
constant s-struct |
| |
@end example |
| |
|
| |
An alternative way of writing this structure is: |
| |
|
| |
@example |
| |
begin-structure s-struct |
| |
field: s-a |
| |
faligned 2 floats +field s-b |
| |
end-structure |
| |
@end example |
| |
|
| |
doc-begin-structure |
| |
doc-end-structure |
| |
doc-+field |
| |
doc-cfield: |
| |
doc-field: |
| |
doc-2field: |
| |
doc-ffield: |
| |
doc-sffield: |
| |
doc-dffield: |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Object-oriented Forth, Programming Tools, Structures, Words |
@node Object-oriented Forth, Programming Tools, Structures, Words |
| @section Object-oriented Forth |
@section Object-oriented Forth |
| @cindex @code{method} usage |
@cindex @code{method} usage |
| @example |
@example |
| object class graphical \ "object" is the parent class |
object class graphical \ "object" is the parent class |
| method draw ( x y graphical -- ) |
method draw ( x y -- ) |
| class; |
class; |
| @end example |
@end example |
| |
|
| : draw ( x y -- ) |
: draw ( x y -- ) |
| circle-radius @@ draw-circle ; |
circle-radius @@ draw-circle ; |
| |
|
| : init ( n-radius -- ( |
: init ( n-radius -- ) |
| circle-radius ! ; |
circle-radius ! ; |
| class; |
class; |
| @end example |
@end example |
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words |
@node Programming Tools, C Interface, Object-oriented Forth, Words |
| @section Programming Tools |
@section Programming Tools |
| @cindex programming tools |
@cindex programming tools |
| |
|
| @c !! move this and assembler down below OO stuff. |
@c !! move this and assembler down below OO stuff. |
| |
|
| @menu |
@menu |
| * Examining:: |
* Examining:: Data and Code. |
| * Forgetting words:: |
* Forgetting words:: Usually before reloading. |
| * Debugging:: Simple and quick. |
* Debugging:: Simple and quick. |
| * Assertions:: Making your programs self-checking. |
* Assertions:: Making your programs self-checking. |
| * Singlestep Debugger:: Executing your program word by word. |
* Singlestep Debugger:: Executing your program word by word. |
| |
|
| doc-.s |
doc-.s |
| doc-f.s |
doc-f.s |
| |
doc-maxdepth-.s |
| |
|
| There is a word @code{.r} but it does @i{not} display the return stack! |
There is a word @code{.r} but it does @i{not} display the return stack! |
| It is used for formatted numeric output (@pxref{Simple numeric output}). |
It is used for formatted numeric output (@pxref{Simple numeric output}). |
| doc-depth |
doc-depth |
| doc-fdepth |
doc-fdepth |
| doc-clearstack |
doc-clearstack |
| |
doc-clearstacks |
| |
|
| The following words inspect memory. |
The following words inspect memory. |
| |
|
| doc-xt-see |
doc-xt-see |
| doc-simple-see |
doc-simple-see |
| doc-simple-see-range |
doc-simple-see-range |
| |
doc-see-code |
| |
doc-see-code-range |
| |
|
| @node Forgetting words, Debugging, Examining, Programming Tools |
@node Forgetting words, Debugging, Examining, Programming Tools |
| @subsection Forgetting words |
@subsection Forgetting words |
| @cindex singlestep Debugger |
@cindex singlestep Debugger |
| @cindex debugging Singlestep |
@cindex debugging Singlestep |
| |
|
| The singlestep debugger does not work in this release. |
The singlestep debugger works only with the engine @code{gforth-ditc}. |
| |
|
| When you create a new word there's often the need to check whether it |
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 @code{dbg |
behaves correctly or not. You can do this by typing @code{dbg |
| doc-break: |
doc-break: |
| doc-break" |
doc-break" |
| |
|
| |
@c ------------------------------------------------------------ |
| |
@node C Interface, Assembler and Code Words, Programming Tools, Words |
| |
@section C Interface |
| |
@cindex C interface |
| |
@cindex foreign language interface |
| |
@cindex interface to C functions |
| |
|
| |
Note that the C interface is not yet complete; callbacks are missing, |
| |
as well as a way of declaring structs, unions, and their fields. |
| |
|
| |
@menu |
| |
* Calling C Functions:: |
| |
* Declaring C Functions:: |
| |
* Calling C function pointers:: |
| |
* Callbacks:: |
| |
* C interface internals:: |
| |
* Low-Level C Interface Words:: |
| |
@end menu |
| |
|
| |
@node Calling C Functions, Declaring C Functions, C Interface, C Interface |
| |
@subsection Calling C functions |
| |
@cindex C functions, calls to |
| |
@cindex calling C functions |
| |
|
| |
Once a C function is declared (see @pxref{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 @code{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 @code{lseek()}: |
| |
|
| |
@example |
| |
off_t lseek(int fd, off_t offset, int whence); |
| |
@end example |
| |
|
| |
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: |
| |
|
| |
@example |
| |
fd @@ 0 SEEK_SET lseek -1 = if |
| |
... \ error handling |
| |
then |
| |
@end example |
| |
|
| |
You might be worried that an @code{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 (@pxref{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 @code{dlseek}; the |
| |
result could be called like this: |
| |
|
| |
@example |
| |
fd @@ 0. SEEK_SET dlseek -1. d= if |
| |
... \ error handling |
| |
then |
| |
@end example |
| |
|
| |
Passing and returning structs or unions is currently not supported by |
| |
our interface@footnote{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.}. |
| |
|
| |
Calling functions with a variable number of arguments (@emph{variadic} |
| |
functions, e.g., @code{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. |
| |
|
| |
|
| |
|
| |
@node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface |
| |
@subsection Declaring C Functions |
| |
@cindex C functions, declarations |
| |
@cindex declaring C functions |
| |
|
| |
Before you can call @code{lseek} or @code{dlseek}, you have to declare |
| |
it. The declaration consists of two parts: |
| |
|
| |
@table @b |
| |
|
| |
@item The C part |
| |
is the C declaration of the function, or more typically and portably, |
| |
a C-style @code{#include} of a file that contains the declaration of |
| |
the C function. |
| |
|
| |
@item The Forth part |
| |
declares the Forth types of the parameters and the Forth word name |
| |
corresponding to the C function. |
| |
|
| |
@end table |
| |
|
| |
For the words @code{lseek} and @code{dlseek} mentioned earlier, the |
| |
declarations are: |
| |
|
| |
@example |
| |
\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 |
| |
@end example |
| |
|
| |
The C part of the declarations is prefixed by @code{\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 @code{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 @code{--}, and then |
| |
exactly one type for the return value. The possible types are: |
| |
|
| |
@table @code |
| |
|
| |
@item n |
| |
single-cell integer |
| |
|
| |
@item a |
| |
address (single-cell) |
| |
|
| |
@item d |
| |
double-cell integer |
| |
|
| |
@item r |
| |
floating-point value |
| |
|
| |
@item func |
| |
C function pointer |
| |
|
| |
@item void |
| |
no value (used as return type for void functions) |
| |
|
| |
@end table |
| |
|
| |
@cindex variadic C functions |
| |
|
| |
To deal with variadic C functions, you can declare one Forth word for |
| |
every pattern you want to use, e.g.: |
| |
|
| |
@example |
| |
\c #include <stdio.h> |
| |
c-function printf-nr printf a n r -- n |
| |
c-function printf-rn printf a r n -- n |
| |
@end example |
| |
|
| |
Note that with C functions declared as variadic (or if you don't |
| |
provide a prototype), the C interface has no C type to convert to, so |
| |
no automatic conversion happens, which may lead to portability |
| |
problems in some cases. In such cases you can perform the conversion |
| |
explicitly on the C level, e.g., as follows: |
| |
|
| |
@example |
| |
\c #define printfll(s,ll) printf(s,(long long)ll) |
| |
c-function printfll printfll a n -- n |
| |
@end example |
| |
|
| |
Here, instead of calling @code{printf()} directly, we define a macro |
| |
that casts (converts) the Forth single-cell integer into a |
| |
C @code{long long} before calling @code{printf()}. |
| |
|
| |
doc-\c |
| |
doc-c-function |
| |
|
| |
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 @file{lib.fs} |
| |
and @file{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 @file{lib.fs} interface |
| |
in @file{lib.fs}. |
| |
|
| |
|
| |
@node Calling C function pointers, Callbacks, Declaring C Functions, C Interface |
| |
@subsection Calling C function pointers from Forth |
| |
@cindex C function pointers, calling from Forth |
| |
|
| |
If you come across a C function pointer (e.g., in some C-constructed |
| |
structure) and want to call it from your Forth program, you can also |
| |
use the features explained until now to achieve that, as follows: |
| |
|
| |
Let us assume that there is a C function pointer type @code{func1} |
| |
defined in some header file @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 |
| |
|
| |
@example |
| |
\c #include <func1.h> |
| |
\c #define call_func1(par1,fptr) ((func1)fptr)(par1) |
| |
c-function call-func1 call_func1 n func -- n |
| |
@end example |
| |
|
| |
and then you can call a function pointed to by, say @code{func1a} as |
| |
follows: |
| |
|
| |
@example |
| |
-5 func1a call-func1 . |
| |
@end example |
| |
|
| |
In the C part, @code{call_func} is defined as a macro to avoid having |
| |
to declare the exact parameter and return types, so the C compiler |
| |
knows them from the declaration of @code{func1}. |
| |
|
| |
The Forth word @code{call-func1} is similar to @code{execute}, except |
| |
that it takes a C @code{func1} pointer instead of a Forth execution |
| |
token, and it is specific to @code{func1} pointers. For each type of |
| |
function pointer you want to call from Forth, you have to define |
| |
a separate calling word. |
| |
|
| |
|
| |
@node Callbacks, C interface internals, Calling C function pointers, C Interface |
| |
@subsection Callbacks |
| |
@cindex Callback functions written in Forth |
| |
@cindex C function pointers to Forth words |
| |
|
| |
Callbacks are not yet supported by the documented C interface. You |
| |
can use the undocumented @file{lib.fs} interface for callbacks. |
| |
|
| |
In some cases you have to pass a function pointer to a C function, |
| |
i.e., the library wants to call back to your application (and the |
| |
pointed-to function is called a callback function). You can pass the |
| |
address of an existing C function (that you get with @code{lib-sym}, |
| |
@pxref{Low-Level C Interface Words}), but if there is no appropriate C |
| |
function, you probably want to define the function as a Forth word. |
| |
|
| |
@c I don't understand the existing callback interface from the example - anton |
| |
|
| |
|
| |
@c > > Und dann gibt's noch die fptr-Deklaration, die einem |
| |
@c > > C-Funktionspointer entspricht (Deklaration gleich wie bei |
| |
@c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der |
| |
@c > > C-Funktionsadresse auf dem TOS). |
| |
@c > |
| |
@c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht |
| |
@c > gesehen habe, wozu das gut ist. |
| |
@c |
| |
@c Irgendwie muss ich den Callback ja testen. Und es soll ja auch |
| |
@c vorkommen, dass man von irgendwelchen kranken Interfaces einen |
| |
@c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit |
| |
@c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte |
| |
@c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit |
| |
@c demselben Prototyp. |
| |
|
| |
|
| |
@node C interface internals, Low-Level C Interface Words, Callbacks, C Interface |
| |
@subsection 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 @code{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 @code{\c} lines are literally included in the C code (but without |
| |
the @code{\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. |
| |
|
| |
|
| |
@node Low-Level C Interface Words, , C interface internals, C Interface |
| |
@subsection Low-Level C Interface Words |
| |
|
| |
doc-open-lib |
| |
doc-lib-sym |
| |
doc-call-c |
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Assembler and Code Words, Threading Words, Programming Tools, Words |
@node Assembler and Code Words, Threading Words, C Interface, Words |
| @section Assembler and Code Words |
@section Assembler and Code Words |
| @cindex assembler |
@cindex assembler |
| @cindex code words |
@cindex code words |
| * 386 Assembler:: Deviations and special cases |
* 386 Assembler:: Deviations and special cases |
| * Alpha Assembler:: Deviations and special cases |
* Alpha Assembler:: Deviations and special cases |
| * MIPS assembler:: Deviations and special cases |
* MIPS assembler:: Deviations and special cases |
| |
* PowerPC assembler:: Deviations and special cases |
| * Other assemblers:: How to write them |
* Other assemblers:: How to write them |
| @end menu |
@end menu |
| |
|
| |
|
| @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words |
@node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words |
| @subsection Common Disassembler |
@subsection Common Disassembler |
| |
@cindex disassembler, general |
| |
@cindex gdb disassembler |
| |
|
| You can disassemble a @code{code} word with @code{see} |
You can disassemble a @code{code} word with @code{see} |
| (@pxref{Debugging}). You can disassemble a section of memory with |
(@pxref{Debugging}). You can disassemble a section of memory with |
| |
|
| doc-disasm |
doc-discode |
| |
|
| The disassembler generally produces output that can be fed into the |
There are two kinds of disassembler for Gforth: The Forth disassembler |
| |
(available on some CPUs) and the gdb disassembler (available on |
| |
platforms with @command{gdb} and @command{mktemp}). If both are |
| |
available, the Forth disassembler is used by default. If you prefer |
| |
the gdb disassembler, say |
| |
|
| |
@example |
| |
' disasm-gdb is discode |
| |
@end example |
| |
|
| |
If neither is available, @code{discode} performs @code{dump}. |
| |
|
| |
The Forth disassembler generally produces output that can be fed into the |
| assembler (i.e., same syntax, etc.). It also includes additional |
assembler (i.e., same syntax, etc.). It also includes additional |
| information in comments. In particular, the address of the instruction |
information in comments. In particular, the address of the instruction |
| is given in a comment before the instruction. |
is given in a comment before the instruction. |
| |
|
| |
The gdb disassembler produces output in the same format as the gdb |
| |
@code{disassemble} command (@pxref{Machine Code,,Source and machine |
| |
code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for |
| |
the 386 and AMD64 architectures). |
| |
|
| @code{See} may display more or less than the actual code of the word, |
@code{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 |
because the recognition of the end of the code is unreliable. You can |
| use @code{disasm} if it did not display enough. It may display more, if |
use @code{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 |
the code word is not immediately followed by a named word. If you have |
| something else there, you can follow the word with @code{align latest ,} |
something else there, you can follow the word with @code{align latest ,} |
| to ensure that the end is recognized. |
to ensure that the end is recognized. |
| @example |
@example |
| ax bx mov \ move ebx,eax |
ax bx mov \ move ebx,eax |
| 3 # ax mov \ mov eax,3 |
3 # ax mov \ mov eax,3 |
| 100 di ) ax mov \ mov eax,100[edi] |
100 di d) ax mov \ mov eax,100[edi] |
| 4 bx cx di) ax mov \ mov eax,4[ebx][ecx] |
4 bx cx di) ax mov \ mov eax,4[ebx][ecx] |
| .w ax bx mov \ mov bx,ax |
.w ax bx mov \ mov bx,ax |
| @end example |
@end example |
| <n> # <reg> <inst> |
<n> # <reg> <inst> |
| <mem> <reg> <inst> |
<mem> <reg> <inst> |
| <reg> <mem> <inst> |
<reg> <mem> <inst> |
| |
<n> # <mem> <inst> |
| @end example |
@end example |
| |
|
| Immediate to memory is not supported. The shift/rotate syntax is: |
The shift/rotate syntax is: |
| |
|
| @example |
@example |
| <reg/mem> 1 # shl \ shortens to shift without immediate |
<reg/mem> 1 # shl \ shortens to shift without immediate |
| end-code |
end-code |
| @end example |
@end example |
| |
|
| |
|
| @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words |
@node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words |
| @subsection Alpha Assembler |
@subsection Alpha Assembler |
| |
|
| |
|
| @code{fbgt,} gives @code{fgt}. |
@code{fbgt,} gives @code{fgt}. |
| |
|
| @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words |
@node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words |
| @subsection MIPS assembler |
@subsection MIPS assembler |
| |
|
| The MIPS assembler was originally written by Christian Pirker. |
The MIPS assembler was originally written by Christian Pirker. |
| then, |
then, |
| @end example |
@end example |
| |
|
| @node Other assemblers, , MIPS assembler, Assembler and Code Words |
|
| |
@node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words |
| |
@subsection 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: @code{and or xor fabs}); so if you want to use the Forth |
| |
words, you have to make them visible first, e.g., with @code{also |
| |
forth}. |
| |
|
| |
Registers are referred to by their number, e.g., @code{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., |
| |
@code{addi,}, not just @code{add,}. |
| |
|
| |
The assembler and disassembler usually support the most general form |
| |
of an instruction, but usually not the shorter forms (especially for |
| |
branches). |
| |
|
| |
|
| |
|
| |
@node Other assemblers, , PowerPC assembler, Assembler and Code Words |
| @subsection Other assemblers |
@subsection Other assemblers |
| |
|
| If you want to contribute another assembler/disassembler, please contact |
If you want to contribute another assembler/disassembler, please contact |
| For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows |
For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows |
| how simple it can be. |
how simple it can be. |
| |
|
| |
|
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words |
@node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words |
| @section Threading Words |
@section Threading Words |
| Gforth allows you to pass an arbitrary string to the host operating |
Gforth allows you to pass an arbitrary string to the host operating |
| system shell (if such a thing exists) for execution. |
system shell (if such a thing exists) for execution. |
| |
|
| |
|
| doc-sh |
doc-sh |
| doc-system |
doc-system |
| doc-$? |
doc-$? |
| doc-getenv |
doc-getenv |
| |
|
| |
|
| @c ------------------------------------------------------------- |
@c ------------------------------------------------------------- |
| @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words |
@node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words |
| @section Keeping track of Time |
@section Keeping track of Time |
| in file included from \evaluated string/:-1 |
in file included from \evaluated string/:-1 |
| in file included from ./yyy.fs:1 |
in file included from ./yyy.fs:1 |
| ./xxx.fs:4: Invalid memory address |
./xxx.fs:4: Invalid memory address |
| bar |
>>>bar<<< |
| ^^^ |
|
| Backtrace: |
Backtrace: |
| $400E664C @@ |
$400E664C @@ |
| $400E6664 foo |
$400E6664 foo |
| error happened when text-interpreting line 4 of the file |
error happened when text-interpreting line 4 of the file |
| @file{./xxx.fs}. This line is given (it contains @code{bar}), and the |
@file{./xxx.fs}. This line is given (it contains @code{bar}), and the |
| word on the line where the error happened, is pointed out (with |
word on the line where the error happened, is pointed out (with |
| @code{^^^}). |
@code{>>>} and @code{<<<}). |
| |
|
| The file containing the error was included in line 1 of @file{./yyy.fs}, |
The file containing the error was included in line 1 of @file{./yyy.fs}, |
| and @file{yyy.fs} was included from a non-file (in this case, by giving |
and @file{yyy.fs} was included from a non-file (in this case, by giving |
| @code{catch}, it is not necessarily clear which @code{throw} should be |
@code{catch}, it is not necessarily clear which @code{throw} should be |
| used for the return stack dump (e.g., consider one @code{throw} that |
used for the return stack dump (e.g., consider one @code{throw} that |
| indicates an error, which is caught, and during recovery another error |
indicates an error, which is caught, and during recovery another error |
| happens; which @code{throw} should be used for the stack dump?). Gforth |
happens; which @code{throw} should be used for the stack dump?). |
| presents the return stack dump for the first @code{throw} after the last |
Gforth presents the return stack dump for the first @code{throw} after |
| executed (not returned-to) @code{catch}; this works well in the usual |
the last executed (not returned-to) @code{catch} or @code{nothrow}; |
| case. |
this works well in the usual case. To get the right backtrace, you |
| |
usually want to insert @code{nothrow} or @code{['] false catch drop} |
| |
after a @code{catch} if the error is not rethrown. |
| |
|
| @cindex @code{gforth-fast} and backtraces |
@cindex @code{gforth-fast} and backtraces |
| @cindex @code{gforth-fast}, difference from @code{gforth} |
@cindex @code{gforth-fast}, difference from @code{gforth} |
| |
|
| @menu |
@menu |
| * ANS Report:: Report the words used, sorted by wordset. |
* ANS Report:: Report the words used, sorted by wordset. |
| |
* Stack depth changes:: Where does this stack item come from? |
| @end menu |
@end menu |
| |
|
| See also @ref{Emacs and Gforth}. |
See also @ref{Emacs and Gforth}. |
| |
|
| @node ANS Report, , Tools, Tools |
@node ANS Report, Stack depth changes, Tools, Tools |
| @section @file{ans-report.fs}: Report the words used, sorted by wordset |
@section @file{ans-report.fs}: Report the words used, sorted by wordset |
| @cindex @file{ans-report.fs} |
@cindex @file{ans-report.fs} |
| @cindex report the words used in your program |
@cindex report the words used in your program |
| compilation semantics of @code{S"}, it is a Core word; if you also use |
compilation semantics of @code{S"}, it is a Core word; if you also use |
| its interpretation semantics, it is a File word. |
its interpretation semantics, it is a File word. |
| |
|
| |
|
| |
@node Stack depth changes, , ANS Report, Tools |
| |
@section Stack depth changes during interpretation |
| |
@cindex @file{depth-changes.fs} |
| |
@cindex depth changes during interpretation |
| |
@cindex stack depth changes during interpretation |
| |
@cindex items on the stack after interpretation |
| |
|
| |
Sometimes you notice that, after loading a file, there are items left |
| |
on the stack. The tool @file{depth-changes.fs} helps you find out |
| |
quickly where in the file these stack items are coming from. |
| |
|
| |
The simplest way of using @file{depth-changes.fs} is to include it |
| |
before the file(s) you want to check, e.g.: |
| |
|
| |
@example |
| |
gforth depth-changes.fs my-file.fs |
| |
@end example |
| |
|
| |
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 |
| |
@code{~~} (@pxref{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 |
| |
|
| |
@example |
| |
gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs |
| |
@end example |
| |
|
| |
This checks the stack depth at every end-of-line. So the depth change |
| |
occured in the line reported by the @code{~~} (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 |
| |
|
| |
@example |
| |
gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs |
| |
@end example |
| |
|
| @c ****************************************************************** |
@c ****************************************************************** |
| @node ANS conformance, Standard vs Extensions, Tools, Top |
@node ANS conformance, Standard vs Extensions, Tools, Top |
| @chapter ANS conformance |
@chapter ANS conformance |
| @item providing the String Extensions word set (another easy one) |
@item providing the String Extensions word set (another easy one) |
| @end itemize |
@end itemize |
| |
|
| |
Gforth has the following environmental restrictions: |
| |
|
| |
@cindex environmental restrictions |
| |
@itemize @bullet |
| |
@item |
| |
While processing the OS command line, if an exception is not caught, |
| |
Gforth exits with a non-zero exit code instyead of performing QUIT. |
| |
|
| |
@item |
| |
When an @code{throw} is performed after a @code{query}, Gforth does not |
| |
allways restore the input source specification in effect at the |
| |
corresponding catch. |
| |
|
| |
@end itemize |
| |
|
| |
|
| @cindex system documentation |
@cindex system documentation |
| In addition, ANS Forth systems are required to document certain |
In addition, ANS Forth systems are required to document certain |
| implementation choices. This chapter tries to meet these |
implementation choices. This chapter tries to meet these |
| @item conditions under which control characters match a space delimiter: |
@item conditions under which control characters match a space delimiter: |
| @cindex space delimiters |
@cindex space delimiters |
| @cindex control characters as delimiters |
@cindex control characters as delimiters |
| If @code{WORD} is called with the space character as a delimiter, all |
If @code{word} is called with the space character as a delimiter, all |
| white-space characters (as identified by the C macro @code{isspace()}) |
white-space characters (as identified by the C macro @code{isspace()}) |
| are delimiters. @code{PARSE}, on the other hand, treats space like other |
are delimiters. @code{Parse}, on the other hand, treats space like other |
| delimiters. @code{SWORD} treats space like @code{WORD}, but behaves |
delimiters. @code{Parse-name}, which is used by the outer |
| like @code{PARSE} otherwise. @code{Name}, which is used by the outer |
|
| interpreter (aka text interpreter) by default, treats all white-space |
interpreter (aka text interpreter) by default, treats all white-space |
| characters as delimiters. |
characters as delimiters. |
| |
|
| |
|
| @item division rounding: |
@item division rounding: |
| @cindex division rounding |
@cindex division rounding |
| installation dependent. @code{s" floored" environment? drop .}. We leave |
The ordinary division words @code{/ mod /mod */ */mod} perform floored |
| the choice to @code{gcc} (what to use for @code{/}) and to you (whether |
division (with the default installation of Gforth). You can check |
| to use @code{fm/mod}, @code{sm/rem} or simply @code{/}). |
this with @code{s" floored" environment? drop .}. If you write |
| |
programs that need a specific division rounding, best use |
| |
@code{fm/mod} or @code{sm/rem} for portability. |
| |
|
| @item values of @code{STATE} when true: |
@item values of @code{STATE} when true: |
| @cindex @code{STATE} values |
@cindex @code{STATE} values |
| @item values returned after arithmetic overflow: |
@item values returned after arithmetic overflow: |
| On two's complement machines, arithmetic is performed modulo |
On two's complement machines, arithmetic is performed modulo |
| 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double |
2**bits-per-cell for single arithmetic and 4**bits-per-cell for double |
| arithmetic (with appropriate mapping for signed types). Division by zero |
arithmetic (with appropriate mapping for signed types). Division by |
| typically results in a @code{-55 throw} (Floating-point unidentified |
zero typically results in a @code{-55 throw} (Floating-point |
| fault) or @code{-10 throw} (divide by zero). |
unidentified fault) or @code{-10 throw} (divide by zero). Integer |
| |
division overflow can result in these throws, or in @code{-11 throw}; |
| |
in @code{gforth-fast} division overflow and divide by zero may also |
| |
result in returning bogus results without producing an exception. |
| |
|
| @item whether the current definition can be found after @t{DOES>}: |
@item whether the current definition can be found after @t{DOES>}: |
| @cindex @t{DOES>}, visibility of current definition |
@cindex @t{DOES>}, visibility of current definition |
| @cindex result out of range |
@cindex result out of range |
| On two's complement machines, arithmetic is performed modulo |
On two's complement machines, arithmetic is performed modulo |
| 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double |
2**bits-per-cell for single arithmetic and 4**bits-per-cell for double |
| arithmetic (with appropriate mapping for signed types). Division by zero |
arithmetic (with appropriate mapping for signed types). Division by |
| typically results in a @code{-10 throw} (divide by zero) or @code{-55 |
zero typically results in a @code{-10 throw} (divide by zero) or |
| throw} (floating point unidentified fault). @code{convert} and |
@code{-55 throw} (floating point unidentified fault). Overflow on |
| |
division may result in these errors or in @code{-11 throw} (result out |
| |
of range). @code{Gforth-fast} may silently produce bogus results on |
| |
division overflow or division by zero. @code{Convert} and |
| @code{>number} currently overflow silently. |
@code{>number} currently overflow silently. |
| |
|
| @item reading from an empty data or return stack: |
@item reading from an empty data or return stack: |
| @cindex image file initialization sequence |
@cindex image file initialization sequence |
| @cindex initialization sequence of image file |
@cindex initialization sequence of image file |
| |
|
| You can add your own initialization to the startup sequence through the |
You can add your own initialization to the startup sequence of an image |
| deferred word @code{'cold}. @code{'cold} is invoked just before the |
through the deferred word @code{'cold}. @code{'cold} is invoked just |
| image-specific command line processing (i.e., loading files and |
before the image-specific command line processing (i.e., loading files |
| evaluating (@code{-e}) strings) starts. |
and evaluating (@code{-e}) strings) starts. |
| |
|
| A sequence for adding your initialization usually looks like this: |
A sequence for adding your initialization usually looks like this: |
| |
|
| ; IS 'cold |
; IS 'cold |
| @end example |
@end example |
| |
|
| |
After @code{'cold}, Gforth processes the image options |
| |
(@pxref{Invoking Gforth}), and then it performs @code{bootmessage}, |
| |
another deferred word. This normally prints Gforth's startup message |
| |
and does nothing else. |
| |
|
| @cindex turnkey image files |
@cindex turnkey image files |
| @cindex image file, turnkey applications |
@cindex image file, turnkey applications |
| You can make a turnkey image by letting @code{'cold} execute a word |
So, if you want to make a turnkey image (i.e., an image for an |
| (your turnkey application) that never returns; instead, it exits Gforth |
application instead of an extended Forth system), you can do this in |
| via @code{bye} or @code{throw}. |
two ways: |
| |
|
| @cindex command-line arguments, access |
|
| @cindex arguments on the command line, access |
|
| You can access the (image-specific) command-line arguments through the |
|
| variables @code{argc} and @code{argv}. @code{arg} provides convenient |
|
| access to @code{argv}. |
|
| |
|
| If @code{'cold} exits normally, Gforth processes the command-line |
|
| arguments as files to be loaded and strings to be evaluated. Therefore, |
|
| @code{'cold} should remove the arguments it has used in this case. |
|
| |
|
| |
@itemize @bullet |
| |
|
| |
@item |
| |
If you want to do your interpretation of the OS command-line |
| |
arguments, hook into @code{'cold}. In that case you probably also |
| |
want to build the image with @code{gforthmi --application} |
| |
(@pxref{gforthmi}) to keep the engine from processing OS command line |
| |
options. You can then do your own command-line processing with |
| |
@code{next-arg} |
| |
|
| doc-'cold |
@item |
| doc-argc |
If you want to have the normal Gforth processing of OS command-line |
| doc-argv |
arguments, hook into @code{bootmessage}. |
| doc-arg |
|
| |
@end itemize |
| |
|
| |
In either case, you probably do not want the word that you execute in |
| |
these hooks to exit normally, but use @code{bye} or @code{throw}. |
| |
Otherwise the Gforth startup process would continue and eventually |
| |
present the Forth command line to the user. |
| |
|
| |
doc-'cold |
| |
doc-bootmessage |
| |
|
| @c ****************************************************************** |
@c ****************************************************************** |
| @node Engine, Cross Compiler, Image Files, Top |
@node Engine, Cross Compiler, Image Files, Top |
| The Gforth project was started in mid-1992 by Bernd Paysan and Anton |
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 |
Ertl. The third major author was Jens Wilke. Neal Crook contributed a |
| lot to the manual. Assemblers and disassemblers were contributed by |
lot to the manual. Assemblers and disassemblers were contributed by |
| Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop |
Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky. |
| (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden |
Lennart Benschop (who was one of Gforth's first users, in mid-1993) |
| inspired us with their continuous feedback. Lennart Benshop contributed |
and Stuart Ramsden inspired us with their continuous feedback. Lennart |
| @file{glosgen.fs}, while Stuart Ramsden has been working on automatic |
Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been |
| support for calling C libraries. Helpful comments also came from Paul |
working on automatic support for calling C libraries. Helpful comments |
| Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John |
also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller, |
| Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert |
Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge |
| Epprecht, Dennis Ruffer and David N. Williams. Since the release of |
Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David |
| Gforth-0.2.1 there were also helpful comments from many others; thank |
N. Williams. Since the release of Gforth-0.2.1 there were also helpful |
| you all, sorry for not listing you here (but digging through my mailbox |
comments from many others; thank you all, sorry for not listing you |
| to extract your names is on my to-do list). |
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, |
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 |
and autoconf, among others), and to the creators of the Internet: Gforth |
| |
|
| VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg |
VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg |
| Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in |
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 F83. |
the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth. |
| |
|
| Henry Laxen and Mike Perry wrote F83 as a model implementation of the |
@c Henry Laxen and Mike Perry wrote F83 as a model implementation of the |
| Forth-83 standard. !! Pedigree? When? |
@c Forth-83 standard. !! Pedigree? When? |
| |
|
| A team led by Bill Ragsdale implemented fig-Forth on many processors in |
A team led by Bill Ragsdale implemented fig-Forth on many processors in |
| 1979. Robert Selzer and Bill Ragsdale developed the original |
1979. Robert Selzer and Bill Ragsdale developed the original |
| A part of the information in this section comes from |
A part of the information in this section comes from |
| @cite{@uref{http://www.forth.com/Content/History/History1.htm,The |
@cite{@uref{http://www.forth.com/Content/History/History1.htm,The |
| Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and |
Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and |
| Charles H. Moore, presented at the HOPL-II conference and preprinted in |
Charles H. Moore, presented at the HOPL-II conference and preprinted |
| SIGPLAN Notices 28(3), 1993. You can find more historical and |
in SIGPLAN Notices 28(3), 1993. You can find more historical and |
| genealogical information about Forth there. |
genealogical information about Forth there. For a more general (and |
| |
graphical) Forth family tree look see |
| |
@cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/}, |
| |
Forth Family Tree and Timeline}. |
| |
|
| @c ------------------------------------------------------------------ |
@c ------------------------------------------------------------------ |
| @node Forth-related information, Licenses, Origin, Top |
@node Forth-related information, Licenses, Origin, Top |