% -*- Mode:Text -*-

\chapter{A Forth tutorial}\sectlabel{tuto}

The main purpose of this tutorial is to give you an overall \emph{reading}
familiarity with Forth---enough to follow the \cam\ programming examples
given in this book and in the accompanying software.\index{Forth!tutorial}

\medskip

Relatively little knowledge of Forth is needed to compose full-fledged \cam\
experiments: the same few constructs appear over and over with minor
variations, while many features of the Forth environment that are prominent
in other programming contexts are not required at all.

However, these few constructs must be understood well. In many cases an
intuitive presentation will be sufficient, but we shall not hesitate to give
the appropriate amount of technical detail in those few cases where this is
necessary to insure exact comprehension.

\medskip

To practice this tutorial, you have two choices. You can work with the bare
Forth system (\ttt{/usr/bin/forth}), or you can run \tdf{\SF}
(\ttt{/usr/bin/step})---the \step\ machine \emph{monitor}---which is an
extension of Forth and provides a complete programming environment for the
\step\ machine.

\medskip

By `Forth' in this chapter we mean the particular Forth dialect on which
\SF\ is built. We'll explicitly say `\SF' when we want to
make clear that a certain feature belongs to the \step\ extension of Forth
rather that to the underlying language.

\medskip

Historically, Forth started out with 16-bit data \tdf{cells}, corresponding
to a 16-bit memory word. The present Forth uses 32-bit cells; all our
examples will be based on cells of this size. (There is no connection between
Forth cells and \step\ cells; a Forth cell is a unit of storage of the size
of a ``machine word'' of the Forth processor (which resides in the
host), while a \step\ cell is an assembly of data bits that are logically
associated with a given spatial site of the \step\ machine.)


\section{The command interpreter}

You may visualize the Forth \emph{command
interpreter}\index{Forth!interpreter} as a competent but not-too-literate
technician who sits in the machine room of your computer and has access to
all the levers and dials.  From the deck, you speak to him through an
``intercom''---i.e., your terminal---issuing orders and receiving reports and
acknowledgements (see \sect{access-forth} and \sect{access-dos} for
how to summon the command interpreter).  For instance, if you say
 \begin{verbatim}
    beep\end{verbatim}
    (type it at the terminal, followed by a carriage return) the terminal
will respond with a ``beep''; if you say
 \begin{verbatim}
    0 100 dump\end{verbatim}
    the contents of the first 100 memory locations (starting from location 0)
will be dumped on the screen.  After that, the interpreter will say
  \begin{verbatim}
    ok\end{verbatim}
    to tell you it's done and ready for a new command.  (From now on, we'll
take this carriage-return and \id|ok| business for granted.)

Saying \id|bye| dismisses the interpreter; you are then automatically
returned to the process from which you had gained access to the interpreter
itself.

\medskip

The interpreter's ``ears'' are conditioned to break up the input character
stream into \emph{tokens},\index{Forth!token} using ``blank space'' (one or
more consecutive spaces) and \emph{only} blank space as the token
separator.\footnote
        {\label{foot.blank}At the interactive terminal, carriage return acts,
of course, as a token terminator.  For ``canned'' text submitted to the
interpreter from a disk file, cf.\ footnote \ref{foot.return}.}
        Even though some Forth tokens consist of a single character
(including comma, period, semicolon, etc., which in other computer languages
are often used as ``punctuation marks'') one should be careful not to omit
the blank space between them and adjacent tokens.
        The tokens are passed on one-by-one to the interpreter's ``brain''
and the spaces are discarded.  Thus, the interpreter hears the above command
as a sequence of three tokens---\id|0|, \id|100|, and \id|dump|---and would
hear the same thing if you typed, say,
 \begin{verbatim}
    0 100 dump\end{verbatim}

\medskip

In order to be understood by the interpreter, the two of you must share a
dictionary of terms and a set of grammatical conventions, which together make
up the Forth language. The Forth grammar is simple and fixed; on the other
hand, the \tdf{Forth dictionary}, which reflects the range of things that the
interpreter currently knows about, typically grows with time. As you take
command, you'll find that the Forth interpreter has already gone through
``standard training''---and possibly some additional, more specialized
training (for example, how to exchange data with a \cam\ machine).  This
standard training, which is documented in any good Forth manual, is more
extensive than that of many common computer languages; in this sense, one
speaks of Forth as a programming \emph{environment} rather than just a
programming \emph{language}.

\section{The compiler}\sectlabel{compiler}

The entries that make up the Forth dictionary are called, as you might
expect, \tdf{words}.\index{Forth!word} To \emph{program} in Forth, you
successively add new words to the dictionary---defining each new word in
terms of existing ones. In this way you extend the interpreter's
knowledge---and at the same time your expressive range---with regard to the
set of activities you are interested in.  At any stage of this construction
you may say something that uses the new words, and check that its actual
meaning (i.e., what the interpreter does in response to your words) is
what \emph{you} had in mind.

For example, to make up a new word for ``beep three times'' you type
 \begin{verbatim}
    : 3beep beep beep beep ;\end{verbatim}
 As soon as it sees the colon token (`\ttt{:}'), the interpreter summons the
aid of another technician, called the \tsc{colon \em compiler}.\index{Forth!compiler} This technician takes the token that
immediately follows, in this case \id|3beep|, and starts a new dictionary
entry under that name.  After that, it expects a phrase (a sequence of
tokens) describing the action of the new word; this phrase, namely \id|beep
beep beep|, is not executed at this time, but is compiled in the dictionary
as the meaning of \id|3beep|.  The end of the phrase is marked by a semicolon
token (`\ttt{;}')---don't drop the space before it---which tells the {\sc
colon} compiler to return control to the command interpreter.

The language understood by the \tsc{colon} compiler is slightly different
(and somewhat richer) than that understood by the command interpreter; some
things only work with either the compiler or the interpreter, but not with
both. Except when noted below, everything we will discuss works well either
way.

\medskip

If you now type
 \begin{verbatim}
    3beep\end{verbatim}
 the interpreter will look up this word in the dictionary, execute it, and
respond with the usual \id|ok|. If you type, say,
 \begin{verbatim}
    4beep\end{verbatim}
 the interpreter will look it up but won't find it in the dictionary; it will
then ask an assistant whether it might possibly be a number (see next
section); and finally will print
 \begin{verbatim}
    4beep ?\end{verbatim}
 to tell you it can't make sense of the token \id|4beep|.

\section{The dictionary}\sectlabel{dictionary}

If you type \id|forth words|, you'll get a listing of all the words currently
contained in the main section of Forth's
dictionary,\index{Forth!dictionary}\footnote
    {In addition to this main section, called \id|forth|, the dictionary may
contain some additional specialized sections, as will be explained in a
moment.}
    starting with the ones Forth has learned most recently. Thus, if you had
just had the above conversation with the interpreter, the word \id|3beep|
would be on top of the list.  The older word \id|beep| would appear somewhere
down the list.

The following entries
 \begin{verbatim}
    beep here + ' c@ ; : c! 0=\end{verbatim}
 taken at random from the dictionary give you an idea of what typical Forth
words look like.  \emph{Any} token can be entered in the dictionary as a word.
In particular, characters that in other languages are used as punctuation
marks, such as `\ttt{:}', can appear as part of a Forth word, or even make up
a word all by themselves; the word `\ttt{c,}' is very different than the
two-word sequence `\ttt{c~,}'.

\medskip

A word already present in the dictionary may be redefined by you.  For
instance, if the speaker in your terminal is dead, as a temporary fix you may
use a version of \id|beep| that prints on the screen, on a new line, the
message `\verb|This IS a beep!|'.  This is done by
redefining \id|beep| as follows
 \begin{verbatim}
    : beep    cr ." This IS a beep!" ;\end{verbatim}
        Type the above line exactly as it appears (there must be at least one
space after \id|beep|, after \id|cr|, after \id|."|, and before the \id|;|).
the word \id|cr| will execute a ``carriage return'' (moving the terminal's
``printing head'' to the beginning of a fresh line); the construct \ttt{."
}$\langle{\rm text}\rangle$\ttt{"} will print $\langle{\rm text}\rangle$ on
the screen (this construct can only be used within a \tsc{colon} definition).
If you now define
 \begin{verbatim}
    : 4beep beep beep beep beep ;\end{verbatim}
 this word will be compiled using the \emph{new} version of \id|beep|, and
when executed will print
 \begin{verbatim}
    This IS a beep!
    This IS a beep!
    This IS a beep!
    This IS a beep!\end{verbatim}
  The old version of \id|beep| is not deleted from the dictionary, and the
previously defined word \id|3beep| \emph{will retain its original
meaning}---which is tied to the \emph{old} version of \id|beep|). If you say
\id|3beep| now, the three beeps will still be routed to the (dead) speaker.

It's all right, and often useful, to redefine a word in terms of its previous
namesake. For instance, if you discover that beeps in your terminal have such
a long decay time that three consecutive beeps sound more like a long one,
you may redefine \id|beep| as
 \begin{verbatim}
    : beep beep 10 ticks ;\end{verbatim} (where \id|10 ticks| means ``Wait
for ten ticks of an internal computer clock''), and a sequence of beeps will
now sound ``staccato'' rather than ``legato''.

\medskip

In some English dictionaries, words belonging to certain specialized areas of
discourse are listed in separate sections (e.g., geographical names,
measurement units, abbreviations).  In Forth, these sections are called
\tdf{vocabularies}; in addition to the main \id|forth| vocabulary there may be
an \id|assembler| vocabulary containing machine-language op-codes and other
assembler-specific terms, an \ttt{editor} vocabulary containing
editor-specific terms, etc.\index{Forth!vocabularies} As explained in
\sect{search-order}, there are commands available for specifying which
vocabularies should be searched at any particular moment, and in what order.


\section{Numbers}\sectlabel{numbers}

\index{Forth!number}If in an ordinary piece of English text you find a phrase
such as ``the motion was passed with 371 votes in favor'', you won't look up
`371' in the dictionary---and for that matter you wouldn't find it there if
you did.  The meaning of a number derives from its make-up; this makes it
possible for any fool to produce more numbers than any one would want to
list, but at the same time makes it unnecessary to list the meaning of
individual numbers in a dictionary.

The situation is analogous in Forth: numbers are parsed as they are
encountered and their meaning is reconstructed from their make-up by another
technician, called \id|number|, summoned by the interpreter as the occasion
arises. This ``meaning'' is nothing but an internal representation in binary
form.  For instance, if the interpreter sees the token \id|103|, by default
this token will be recognized as a numeral and will be converted to and
internally stored as a 32-bit pattern---namely 00\ldots01100100 (this is the
binary expression for the number 103).  However, if you had told the
interpreter to use base sixteen rather than base ten when reading input,\footnote
    {In Forth, numbers can be read and printed in any base you choose.}
    the same token \id|103| will be interpreted as a hexadecimal numeral and
stored as the pattern 00\ldots0100000011 (meaning $2^8+2^1+2^0$, or 259 in
decimal).

\medskip

Some numbers that for historical or practical reasons deserve explicit
mention, such as `three', \emph{are} listed (in a spelled-out form) in the
English dictionary. In an analogous way, some common numbers such as 0 and 1
have been entered (in this form, i.e., \id|0|---not \id|zero|) as \emph{words}
in the Forth dictionary.\footnote
    {Words of type \tsc{constant}; \cf{constants}.}
 This leads to more efficient execution (their meaning has been established
in advance, once and for all, and there is no need to ask for the help of the
\id|number| technician) and more compact code.

\medskip

By default, Forth handles numbers as signed integers with a 32-bit range
(only $2^{32}$=4,294,967,295 different values are available) so that the
ordinary counting sequence $-$2, $-$1, 0, 1, 2, 3, \ldots\ at a certain point
``wraps around'': \ldots, 2147483646, 2147483647, $-$2147483648,
$-$2147483647, \ldots, $-$2, $-$1, 0 (\cf{logic}).  We'll not try to convince
you that what is most natural for a computer (or for a person that lives with
computers) should be the most natural thing for you; indeed, while these
features of Forth's ``numbers'' are actually an asset in low-level
programming tasks, serious numerical applications require much more powerful
number-handling facilities.  The Forth philosophy is that specialized
applications should be served by specialized extensions to the language
(\cf{precision}).

\section{The stack}\sectlabel{stack}

\index{Forth!stack}Forth manages to achieve remarkable expressive power and
efficiency; yet a Forth \emph{system} (i.e., the language as implemented on a
computer) can be amazingly simple and compact.  These advantages are bought
at the cost of ruthless standardization, in particular in the way nearby
words in a phrase communicate to one another the information that binds them
together as a semantic whole.

For the purpose of this communication, all data (characters, Boolean
variables, numbers, addresses, etc.) are packaged in a standard-size
``carton'', called a \tdf{cell}, having a capacity of 32 bits, and all data
exchanges take place---in a preordained choreography, as we shall see in a
moment---through a single clearing-house called the \tdf{stack}. This is just
a pile of cells that grows or shrinks according to the traffic.

Imagine a stage with this stack in the middle. The Forth interpreter is the
ballet conductor; as he reads off the words that make up your phrase, the
corresponding actors show up in sequence, do their thing, and disappear. If
an actor's part tells him to leave behind certain data for later actors,
he'll walk to the stack and pile these data, cell by cell, on top of it; if
his part expects data from previous actors, he will walk to the stack and
pick them up.

Some data that an actor needs may end up, say, buried two cells deep into the
stack. The actor won't go fumbling through the stack looking for them (the
cartons don't carry a label!); rather, his score will explicitly tell him to
lift just the top two cells, grab the cell that is now on top, and put the
first two back down (incidentally, the score notation specifying this
sequence of actions is \id|rot|, discussed in \sect{dup-drop}).

With this scheme, there is no need for each piece of data to have an {\sl
absolute} address---a permanent mailbox with a distinguished name.  Instead,
all addressing is by position \emph{relative} to the top of the stack. If a
new, self-contained piece of choreography is inserted in the old score, at
the moment of executing it one will find the stack already built up to a
certain height; during execution of this piece one will see the stack grow
more, shrink a bit, etc., and by the end of the inserted piece of
choreography return to its original height. The rest of the score will then
resume, finding its own data where they had been left.

\section{Expressions}

The stack discipline is well suited to the communication needs of a
hierarchically built program.  It allows one to use a particularly simple
scoring notation---called \tdf{reverse Polish notation}\index{Forth!reverse
Polish notation}---by which arithmetical and logic expressions of arbitrary
depth can be written without making recourse to parentheses or other place
markers.\index{Forth!arithmetical expressions}

\medskip

When you type a number to the command interpreter, this number is packaged in
one cell and put on top of the stack. The one-character word `\ttt{.}'
(``dot'') picks up the top cell of the stack and prints its contents \emph{as
a number} on the screen.  Thus, if you type
 \begin{verbatim}
    356 .\end{verbatim} (where the dot `.' is part of what you type) the
screen will respond with
    \begin{verbatim}
    356\end{verbatim}
 (In a more conventional programming language, the equivalent of `\ttt{356
.}' would be something like `\ttt{print(356)}'.) Note that the stack went up
one level with \id|356|, down one level with `\ttt{.}', and is now the same
height as before.

The word `\verb|+|' (``plus'') gobbles up the top \emph{two} cells of the
stack, adds them together, and places the result---consisting of \emph{one}
cell---on top of the stack; thus, it leaves the stack one level lower than it
found it.  For example, the expression
 \begin{verbatim}
    2 3 +\end{verbatim}
 will leave the result 5 on the stack (from where you can move it to the
screen with `\ttt{.}').  If you want to see how much $1+2+4$ is, you type
 \begin{verbatim}
    1 2 + 4 + .\end{verbatim}
 We can picture the evolution of the stack as follows
 
 \newcommand{\st}[2]{\hbox{#1} & \hbox{\ttt{#2}}}
 $$
  \begin{array}{lcc}
    \hbox{\tsc{stack}} & \hbox{\tsc{input}} & \hbox{\tsc{output}} \\
    \st{\ldots\ }{1} \\
    \st{\ldots\ 1}{2} \\
    \st{\ldots\ 1 2}{+} \\
    \st{\ldots\ 3}{4} \\
    \st{\ldots\ 3 4}{+} \\
    \st{\ldots\ 7}{.} & \hbox{\ttt{7}}\\
    \st{\ldots\ }{}
 \end{array}
 $$
 \noindent
 where each row displays (a) the current state of the stack (with the top
element on the right), (b) the text to be interpreted, and (c) what is
printed on the screen.  The dots on the left indicate the part of the stack
that we haven't touched; this indication will be dropped in the following
stack examples.

Note that once 3 has been placed on the stack, it does not matter \emph{how}
it got there; from a functional viewpoint, the expression \id|1 2 +| is
interchangeable with, say, \id|3|, or \id|1 1 + 1 +|, or anything that
eventually bows out having left just a 3 on top of whatever else the stack
contained before. Note also that the two different expressions
 $$
    \hbox{\ttt{1 1 + 1 + 1 +}}\quad\mathrm{and}\quad\hbox{\ttt{1 1 1 1 + + +}}
 $$
 \noindent produce the same end result even though the second one temporarily
builds up the stack to a higher level: $$
  \begin{array}{lc}
    \hbox{\tsc{stack}} & \hbox{\tsc{input}} \\
    \st{}{1} \\
    \st{1}{1} \\
    \st{1 1}{+} \\
    \st{2}{1} \\
    \st{2 1}{+} \\
    \st{3}{1}\\
    \st{3 1}{+}\\
    \st{4}{}
  \end{array}
  \quad
  \begin{array}{lc}
    \hbox{\tsc{stack}} & \hbox{\tsc{input}} \\
    \st{}{1} \\
    \st{1}{1} \\
    \st{1 1}{1} \\
    \st{1 1 1 }{1} \\
    \st{1 1 1 1}{+} \\
    \st{1 1 2}{+}\\
    \st{1 3}{+}\\
    \st{4}{}
 \end{array}
 $$
 
\section{Editing and loading}\sectlabel{editing-loading}

Once you have said something to the Forth interpreter, you cannot take it
back; if something goes wrong, you may not even remember exactly what you
said.\footnote
        {But see \id|see| in \sect{view}.}
        While immediate interaction with the interpreter is very useful,
there are times where you would like to carefully think out in advance a
whole sequence of commands and definitions, review and edit it, and perhaps
discuss it with somebody else before you give it to the interpreter. You want
to be in a position to give \emph{written} orders, and you might have a
collection of different ``orders of the day'' to be handed to the interpreter
according to the circumstances.

You can do all of this by first writing your text on a disk file, where it
can be inspected and modified by means of an ordinary
text editor such as \tsc{emacs}. Then you can ask the interpreter to use this
file as the input stream, instead of what comes from the
keyboard; this process is called \tdf{loading}.\index{Forth!loader} When you
load a file, everything (well, \emph{almost} everything) works as if you were
typing the file's contents from the keyboard---except that the interpreter
now processes your tokens as they come, without waiting for a carriage
return.

\medskip

When you compose your text with the editor for subsequent loading, you may
choose to format it in a way that facilitates comprehension, and here and
there add a comment to yourself.

The Forth word \id|(| removes from the input stream everything that follows,
up to and including the matching character `\verb|)|'; thus, you may write a
line as follows
  \begin{verbatim}
    beep beep ( two beeps ) beep beep\end{verbatim}
	and the
interpreter will never hear what is ``in parentheses''.\footnote
    {Observe that the following spacing is correct too

\ttt{beep beep ( two beeps)beep beep}

 \noindent even though there is no intervening space between `\ttt{)}' and
\id|beep|, since the effect of the word \id|(| is precisely to
throw away the string `\ttt{two beeps)}'. On the other hand, the
following spacing

\ttt{beep beep (two beeps) beep beep}

 \noindent won't do, since it will make the interpreter think that

`\ttt{(two}' is a token to be processed.}

The word `\verb|\|' (``backslash'') treats as a comment the remainder of the
line on which it appears
 \begin{verbatim}
    : beep             \ new version!
            beep       \ plain beep
            10 ticks ; \ insert delay\end{verbatim}

\section{``Constants'' and ``variables''}\sectlabel{constants}

In \sect{compiler} we said that the interpreter ``executes'' the words
you type.  Actually, each word in the Forth dictionary carries a notice
saying ``I am to be executed by technician so-and-so, who knows how to handle
me'', and the interpreter will just pass the buck to this technician.  For
words that have been entered in the dictionary by the \tsc{colon} compiler,
the competent technician is the \tsc{colon} interpreter.  In general,
each type of word has its own compiler and a corresponding interpreter.  The
buck stops with words that have been compiled by the \tsc{code}
``compiler'';\index{Forth!code@\tsc{code}} this technician actually produces
code written directly in machine language (i.e., your microprocessor's native
language), and is more properly termed an {\sl
assembler}.\index{Forth!assembler} At this point the hardware takes over.

\medskip

All of this works much more simply than it sounds.  Suppose you are writing a
telescope-driving program that needs to know your town's latitude, say,
$43^{\circ}$. It is good programming practice to give this number a {\sl
name}---say, \id|latitude|---so that whenever this name appears in your
program it will have the same effect as if you had typed `43'. To do this, in
Forth you say
 \begin{verbatim}
    43 constant latitude\end{verbatim}
  the word \id|latitude| will be entered in the dictionary as a constant, and
when executed it will place the number 43 on the stack.

What happens is that as soon as it sees the word \id|constant| the command
interpreter summons the aid of the \tsc{constant}
compiler,\index{Forth!constant@\tsc{constant}} (\cf{defining-words}) who
gobbles up the next token---namely \id|latitude|---and starts a new
dictionary entry under that name. The entry will consist of two parts: the
first (\tdf{code field\/})\index{Forth!code field} contains a notice saying
``I am to be executed by the \tsc{constant} interpreter''; the second
(\tdf{data cell\/})\index{Forth!data cell} is reserved for the value of the
constant. At this point the \tsc{constant} compiler takes the top cell of the
stack---with the 43 you had just put there---and moves it to the data cell in
the dictionary.  At execution time, the \tsc{constant} interpreter will look
at the data cell and place a copy of it on the stack.

With the above definition of \id|latitude|, the command
 \begin{verbatim}
    latitude 7 + .\end{verbatim}
 will print \id|50| on the screen.

\medskip

The term `\tsc{constant}' is somewhat of a misnomer (though it is retained
for historical reasons), since the contents of the data cell may be altered
at will; in the present implementation of Forth, to change the value of
\id|latitude| to $45^{\circ}$ you say
 \begin{verbatim}
    45 is latitude\end{verbatim}
 The most relevant aspect of a Forth \tsc{constant} is that it returns the
\emph{value} of its data cell, rather than a \emph{pointer} to it (cf.\
\id|variable|) below).

\medskip

In \cam, \tsc{field} words, defined by the defining word \id|==| or
derivatives therof (\cf{}), act like Forth \tsc{constant}s insofar as they
return a value; however, this value will change very many times during the
construction of a rule table (\sect{}).

\bigskip

Forth provides another mechanism for accessing a piece of data, namely by its
\emph{address}\footnote
    {In an ordinary computer, memory locations are sequentially numbered; the
address of a piece of data is the number of its location.} rather than by its
\emph{value}.  The \tsc{variable} compiler,\index{Forth!variable@{\sc
variable}} used in a construct such as
 \begin{verbatim}
    variable time\end{verbatim}
 is analogous to the \tsc{constant} compiler insofar as it constructs a
dictionary entry, namely \id|time|, with a data cell in it.  However,
 \begin{itemize}
  \item This data cell is not initialized to a particular value (and
therefore the defining word \id|variable|, unlike \id|constant|, does {\sl
not} expect a value on the stack).
  \item When \id|time| is executed, the \tsc{variable} interpreter puts on
the stack the \emph{address} of the data cell, rather than its contents.
 \end{itemize}
 Thus, if we type
 \begin{verbatim}
    time\end{verbatim} what will be placed on the stack is not the current
value of \id|time| (which may change several times during execution of the
program), but its address (which is always the same).

To get the \emph{value} of \id|time| you use the word `\verb|@|' (pronounced
``fetch''), as in
 \begin{verbatim}
    time @ ( data )\end{verbatim}
 (i.e., `\ttt{@}' expects an address on the stack, and replaces it with the
data at that address), and to set it you use the word `\verb|!|' (``store''),
as in
 \begin{verbatim}
    ( data ) time !\end{verbatim}
 (i.e., `\ttt{!}' expects a piece of data \emph{and} an address, and ships the
data to that address). For example, to increment time by one unit you write
 \begin{verbatim}
    time @ 1 + time !\end{verbatim} Supposing that the \id|time| data cell is
at location 1000 and its initial contents is 5, the evolution of the relevant
data is the following
 $$
  \begin{array}{cll}
    \hbox{\ttt{time}'s contents} & \hbox{\tsc{stack}} & \hbox{\tsc{input}} \\
    5 & \st{}{time} \\
    5 & \st{1000}{@} \\
    5 & \st{5}{1} \\
    5 & \st{5 1}{+} \\
    5 & \st{6}{time} \\
    5 & \st{6 1000}{!} \\
    6 & \st{}{}
 \end{array}
 $$
        \noindent (The word \id|+!| allows you to use the more efficient
construct \id|1 time +!|, where the cell's value never appears on the stack.
Similarly, \id|time off| will store all \id|0|s in the cell at the address
supplied by \id|time|, and \id|time on| will store all \id|1|s, corresponding
to the logic values \id|false| and \id|true|---\cf{logic}.)

From the viewpoint of \cam's user, Forth \tsc{variable}s need seldom be used.
In this book, the term `variable' always has the usual meaning of ``a generic
quantity to which we may assign an arbitrary value'' rather the the more
technical Forth meaning, for which we reserve the small-caps term {\sc
variable}.

\section{Defining words}\sectlabel{defining-words}

The words \id|:| (`colon'), \id|constant|, and \id|variable| belong to the
class of \tdf{defining words}, whose action is to create new dictionary
entries.

In Forth, a number of defining words of common utility are built-in; each one
activates a miniature compiler (and, at execution time, a miniature
interpreter) for a specific data structure. If an application is going to
make regular use of other data structures, it is possible (and quite easy) to
introduce new, appropriate defining words. Similar considerations apply to
\emph{control constructs}, discussed in the following sections.

In other words, while, for the casual user, programming will consist merely
of extending the \emph{lexicon} of the received Forth system, the more
sophisticated user will find it both expedient and easy to extend Forth's
very \emph{syntax}.  Practically every major programming effort can benefit
from a moderate investment in ``language development'' of this kind.

The developers of \SF\ have made extensive use of the above features of
Forth.

\section{Iteration}\sectlabel{iteration}

Once you've stored a program in the computer's memory, portions of it can be
executed over and over, perhaps with some variations.\index{Forth!iteration}

\medskip

For instance, you can define
 \begin{verbatim}
    : beep-stuck   begin beep again ;\end{verbatim}
 When this word is called, once the execution reaches \id|again| it jumps
back to \id|begin|, producing an endless series of beeps.
The only way to break the loop is through a keyboard interrupt
(typically \id|^C| to abort the loop, or \id|^Z| to suspend the Forth process).

The above \id|begin|/\id|again| pair delimits a phrase somewhat like a pair
of parentheses: the phrase in between gets iterated forever. Note that for
readability we vertically aligned\memo{revise} the two elements of the
pair, flush on the \emph{right} (this is recommended in
reverse-Polish-notation style), and indented the phrase inside.

 A more flexible pair is \id|do|/\id|loop|; the word
 \begin{verbatim}
    : 100beeps   100 0 do beep loop ;\end{verbatim}
 will beep 100 times.\footnote
    {Of course, if you had typed \ttt{999beeps} rather than \ttt{100beeps}
you still would have gotten a word that beeps 100 times. A name is a name is
a name\ldots}
  What happens in detail is that \id|do| gobbles up the top two numbers on
the stack, 100 (the loop \tsc{limit}) and 0 (the loop \tsc{index}), and saves
them for later use.  The execution proceeds until \id|loop| is encountered.
At this point, \tsc{index} is incremented by one and compared with {\sc
limit}; if \tsc{index}=\tsc{limit} the loop is terminated; otherwise,
execution jumps back to \id|do|.\footnote
    {The loop index is a modulo-$2^{32}$ counter.  The minimum number of
iterations, namely 1, is achieved when the loop is entered with \tsc{index}
just one less than \tsc{limit}; the maximum, when the loop is entered with
\tsc{index} \emph{equal} to \tsc{limit}: \id|0 0 loop| will cycle $2^{32}$
times!}

Inside a \id|do| loop, the word \id|i| returns on the stack the current value
of the index. Thus, the word
        \begin{verbatim}
    : print-ascii   127 32 do i emit loop ;\end{verbatim}
        will produce all printable \ascii\ characters.  (Character 0--31 are
control characters; all others are printable except for the last character of
the \ascii\ set, namely character 127, which on old-fashioned paper tape
``prints'' 7 holes on the last punched character, effectively \tsc{delete}ing
it.) \medskip

Pairs of ``parentheses'' such as \id|begin|/\id|again| and \id|do|/\id|loop|
can be nested as ordinary parentheses, and a lot more bells and whistles are
available.  You can look up the details of these and other flow-control
constructs in a Forth manual. Here we shall only mention that, in traditional
Forth, flow-control constructs can only appear inside a \tsc{colon}
definition; that is, you cannot say
 \begin{verbatim}
    100 0 do beep loop\end{verbatim}
 at the command-interpreter level. In \SF, flow-control constructs
encountered outside a colon definition are colon-compiled ``on-the-fly'' and
then executed as if they were part of a \tsc{colon} word. However, the
material thus compiled is not enclosed in the dictionary and is immediately
discarded. 

\section{Stack comments}\sectlabel{stack-comments}

By now, we have encountered many words that expect arguments on the stack or
leave results on the stack.  Since breaches of stack discipline may send a
computation berserk (if you leave an extra item on the stack everyone after
you will get his data wrong), it will be convenient to have a notation to
remind us of just how many items a word takes from the stack or leaves on
it.\index{Forth!stack comment}

The following are examples of \emph{stack comments}:
 \begin{verbatim}
    do ( n1 n2 -- )
    do ( limit index --)
    beep ( -- )
    latitude ( -- n)
    time ( -- addr)
    + ( n1 n2 -- n3)
    + ( m n -- m+n)
    2 ( -- n)
    2 ( -- 2)\end{verbatim}
 The general convention is as follows. We put in parentheses a' double-dash
to indicate the word in question.  Before the dash we write a list of what
the word \emph{expects} on the stack; after the dash we write a list of what
the word \emph{leaves} on it. If nothing appears \emph{after} the dash, the
dash itself is usually omitted.

What really counts is the \emph{number} of items in each list---which
corresponds to the number of cells taken from or given to the stack; but the
items themselves may be elaborated upon a little, for extra clarity.

For example, \id|do| takes two items and leaves none. A minimal notation is
 \begin{verbatim}
    DO ( n1 n2 -- )\end{verbatim} which just tells us that \id|do| expects
two items. A better mnemonic is provided by
 \begin{verbatim}
    DO ( limit index --)\end{verbatim} which reminds us that the first item
is used as the \emph{limit} and the second as (the initial value of) the {\sl
index} of the loop.

\medskip

As a final grand example, let us load the following three definitions from a
disk file
 \begin{verbatim}
      100 constant hundred  ( -- n)
    10000 constant a-lot-of ( -- n)
                 : beeps    ( n --)
            0 do
       beep loop ;\end{verbatim}
 The words \id|hundred| and \id|a-lot-of| are introduced by the defining word
\id|constant|; the word \id|beeps|, by the defining word \id|:| (`colon').  The
vertical alignment of the three defined words---\id|hundred|, \id|a-lot-of|,
and \id|beeps|---is for clarity; so is the right-justified alignment of
\id|do| and \id|loop| (\cf{visual structuring}).

Now type the following three commands
 \begin{verbatim}
    3 beeps
    hundred beeps
    a-lot-of beeps\end{verbatim}
 We have seen above that \id|do| wants two arguments.  When we type \id|3
beeps|, the first argument is left on the stack by the \id|3| we typed, while
the second is placed on the stack by the \id|0| appearing within the
definition of \id|beeps|: \id|do|'s hunger is satisfied.

Thus, if we define words giving a little thought to the \tdf{stack interface}
(i.e., the conventions about \emph{who} should supply or consume \emph{what}
and \emph{when}) and to choosing appropriate names, the flow of a Forth phrase
can be given a natural-language flavor that is hard to achieve in other
programming languages.  Properly trained Forth words can talk to one another
under the surface of the phrase, without bothering us with their chatter.

A generally obeyed convention in Forth is to make words ``use up'' their
arguments rather than leave them on the stack.  If an object on the stack is
needed as an argument by a given word and also by another word that closely
follows, a second copy of this object is made---using the word \id|dup|
introduced below---before the first copy is used up.

\section{\ttt{dup}, \ttt{drop}, and all that}\sectlabel{dup-drop}

The Forth word `\ttt{*}' (``times'') takes two numbers and returns their
product; to compute the square of 3 you have to type 3 twice: \id|3 3 *|.
How about a word \id|sqr| that will take a \emph{single} argument and multiply
it by itself?

Forth provides a number of general-purpose words for manipulating the stack;
one of these is \id|dup| (pronounced ``dupe''), which looks at the cell on
top of the stack and puts a \emph{duplicate} copy of it on top of it; e.g.,
 $$
  \begin{array}{ll}
   \hbox{\tsc{stack}} & \hbox{\tsc{input}} \\
    \st{5}{dup} \\
    \st{5 5}{}
 \end{array}
 $$
 \noindent Thus, \id|sqr| can be simply
 \begin{verbatim}
    : sqr ( n -- n*n)   dup * ;\end{verbatim}
 since here `\ttt{*}' will see two copies of the argument.

\index{Forth!stack operators}Related to \id|dup| are \id|drop| (which drops
the top item from the stack), \id|swap| (which swaps the top two items),
\id|over| (which makes a copy of the next-to-the-top stack item), \id|rot|
(which pulls the third item from underneath and puts in on top of the first
two), and a few more.  Words of this kind act somewhat like \emph{pronouns} in
English (`this', `that', `one another', etc.), in that they allow one to
refer by \emph{position} rather than by \emph{name} to objects introduced in a
different part of the sentence.  As an exercise, verify that the function
$y(m,n)=(m+n)(m-n)$ is computed by the following Forth expression
 \begin{verbatim}
    ( m n ) over over + rot rot - * ( y )\end{verbatim}
 (where the comments in parentheses tell you what's on the stack before and
after).

\section{Case selection}\sectlabel{case}

A flow-control construct that is supported and encouraged by \SF\ is the
\tsc{flash case} construct,\index{Forth!flash case construct@\tsc{flash case}
construct} which allows one to select for execution one of several
alternative actions.\footnote
	{Another type of case construct, called simply
\ttt{case}\index{Forth!case construct@\ttt{case} construct}, is available; it
is more flexible but less compact and efficient than the \tsc{flash case},
and is not discussed here.}
	Suppose we have three words called \id|beep|, \id|honk|, and
\id|whistle|; we can then make up a new word, called \id|sound|, which will
take an integer argument from the stack, with value 0, 1, or 2, and
respectively beep, honk, or whistle:
 \begin{verbatim}
    : sound ( n --)   { beep honk whistle } ;\end{verbatim}
 That is, \id|0 sound| will execute \id|beep|, \id|1 sound| will execute
\id|honk|, and so on.  The selection list may consist of any number $n$ of
entries, which are to be thought of as consecutively numbered from 0 upwards,
and is delimited by the two ``brace'' words, namely `\verb|{|' and
`\verb|}|'. If you attempt to execute the case statement with an argument
that is less than 0 or greater than $n-1$ you get an error message.

\medskip

Suppose you want to make up a word that returns the number of days in a
month. You'd probably try the following
 \begin{verbatim}
    : days ( month -- days)
              1 -  { 31 28 31 30 31 30
                     31 31 30 31 30 31 } ;\end{verbatim}
 Assuming that months are numbered 1, 2, \ldots, 11, 12, you subtract 1 in
order to have the numbering 0, 1, \ldots, 10, 11---better suited to the case
statement---and then you look up the number of days.  The reasoning is
correct, but there is one minor catch: in \cam\ Forth the case statement only
accepts individual dictionary words as items in the selection list; with a
few exceptions (mentioned in \sect{numbers}) numbers are \emph{not} in
the dictionary.  There is an easy fix to this problem: \emph{before} defining
\id|days|, enter the desired numbers in the dictionary as \tsc{constants}
 \begin{verbatim}
    28 constant 28 ( -- 28)
    30 constant 30 ( -- 30)
    31 constant 31 ( -- 31)\end{verbatim}
 From this moment the token \id|28| (for one) will be recognized as a {\sl
word}---one that leaves a 28 on the stack just as the \emph{number} \id|28|
used to do before. The case statement will now accept it as a list item.

\section{Conditional statements}\sectlabel{conditional statements}

The phrase between a \id|begin| and \id|again| pair is iterated forever, that
between \id|do| and \id|loop| is iterated a number of times as specified by
the two arguments that \id|do| finds on the stack.\index{Forth!conditional
statement} A phrase between the words \id|if| and \id|then| is executed only
if the argument found on the stack by \id|if| has the logic value
`true'.\footnote
    {How logic values are encoded in a Forth cell doesn't matter at this
point, and is discussed in the next section.}

The word
 \begin{verbatim}
    = ( m n -- flag)\end{verbatim}
 compares the two arguments $m$ and $n$ and returns a \emph{logic flag} having
the value `true' if they are equal and `false' if different.  Thus, the
following word will beep only when the top two stack items are equal
 \begin{verbatim}
    : beep-if-equal ( m n --)   = if beep then ;\end{verbatim}
 A richer construct is the \id|if|/\id|else|/\id|then|, used as follows
 \begin{verbatim}
    : beep-or-whistle ( m n --)
        = if beep else whistle then
        honk honk honk ;\end{verbatim}
 This word will beep if $m$ and $n$ are equal, and whistle if they are
different; after that, it will honk three times.

\medskip

There also exist two \emph{conditional iteration} statements.  The first has
the form `\id|begin| $\langle\rm body\rangle$ \id|until|'; the $\langle\rm
body\rangle$ (which returns a logic flag) is iterated \emph{until} the value
of this flag becomes `true'.  The other has the form `\id|begin| $\langle\rm
setup\rangle$ \id|while| $\langle\rm body\rangle$ \id|repeat|'; in which,
after the first $\langle\rm setup\rangle$ (which is always executed), the
sequence $\langle\rm body\rangle$ $\langle\rm setup\rangle$ is iterated {\sl
as long as} the value of the logic flag returned by $\langle\rm setup\rangle$
remains `true'.


\section{Visual structuring}\sectlabel{visual structuring}

Visual structuring of Forth code confronts us with an unusual problem.
In the following code fragment, for each \ascii\ character code (from
0 through 127) we print the character itself if the code corresponds
to a printable character, and an appropriate comment otherwise.

Since Forth uses reverse Polish notation (each operator \emph{follows} its
arguments), the most natural way to indent nested flow-control constructs
would be ``from the right'' rather than ``from the left'', as shown below.
 \begin{verbatim}
               128 0 do \ for all 128 codes
             cr i .     \   newline, print code
i 32 126 between if     \   if printable
        i emit else     \   then print it
     i 127 = if         \   else if 127
   ." DEL" else         \        then is DEL
  ." CTRL" then         \        else is CTRL
                        \        endif
               then     \   endif
                   loop \ endfor\end{verbatim}
 Here \id|do| matches \id|loop|; this is shown by placing the \emph{right}
edges of these two words on the same indentation level.  One level lower (and
thus to the \emph{left}) we find an \id|if|/\id|else|/\id|then| group, with
these three keywords on the same level. The phrase associated with the
\id|if| operator is the arithmetic condition \ttt{i 32 126 between}; that
associated with the \id|else| is what is executed if the condition is true,
namely \ttt{i emit}; that associated with the \id|then|---executed if the
condition is false---is another \id|if|/\id|else|/\id|then| group on an inner
level. The comments on the right show conventional (left-to-right)
indentation.

It will up to the user to decide to what extent visual layout and structure
should be correlated.

\section{Logic expressions}\sectlabel{logic}

In defining a \cam\ rule, sometimes it is convenient to treat the value of a
\step\ field as a logic quantity (`on' or `off', `true' or `false') and
sometimes as a number (0 or 1, for a two-state field; 0, 1, 2, or 3, for a
four-state field; etc.).  To understand precisely what is passed on the stack
by one word to another in these cases, it is important to be aware of the
coding conventions employed in \SF\ concerning arithmetic and logic
expressions.\index{Forth!logic expression}

This lengthy section is meant as a reference for cases where doubts might
arise; you may quickly go over it (or skip it altogether) on first reading.

\medskip

We have seen that the contents of a Forth cell consists of a 32-bit pattern.
The same pattern can have different meanings, depending on agreed-upon
conventions. For instance, it can be used to encode an integer from 0 to
4,294,967,295 (``unsigned number''), an integer from $-$2,147,483,648 to
2,147,483,647 (``signed
number''), four \ascii\ characters (8 bits each) or, quite commonly, a single
\ascii\ character (using only the lowest 8 bits), etc. The cell does not carry a
label telling what kind of encoding was used: it is up to the programmer to
arrange things so that any ``user'' of the pattern will know what conventions
to use in interpreting it.

For example, suppose that the top cell of the stack contains the pattern
100\ldots00101010; the three words `\ttt{.}', \id|u.|, and \id|emit| will all
print on the terminal the contents of this cell. However, `\ttt{.}' will
treat it as a signed number, and print `\ttt{-2147483606}'; \id|u.| will treat it
as un unsigned number, and print `\ttt{2147483690}'; and \id|emit| will treat it
as a character, and print `\ttt{*}' (since the lower eight bits of the
pattern, namely 00101010, make up the \ascii\ code for `\ttt{*}').

In many cases it is convenient to treat the cell pattern just as a collection
of separate bits---each one representing an individual binary choice. The
words
 \begin{verbatim}
    not ( p -- r)
    and ( p q -- r)
    or ( p q -- r)
    xor ( p q -- r)\end{verbatim}
 are useful in this context, since they allow one to individually or jointly
manipulate these bits. For instance, one can ``turn off'' the upper
twenty-four bits of a pattern by \tsc{and}ing it with an appropriate {\sl
mask} pattern, namely 00\ldots0011111111, in which the upper twenty-four bits
are ``off'' and the lower eight are ``on''.

As a reminder, the logic operations \tsc{not}, \tsc{and}, \tsc{or}, and {\sc
xor} are defined as follows:
 $$
 \begin{array}{c}
  \hbox{\tsc{not}} \\[0.5ex]
  0\mapsto1 \\
  1\mapsto0 \\
  \phantom{0} \\
  \phantom{0}
 \end{array},
 \qquad
 \begin{array}{c}
  \hbox{\tsc{and}} \\[0.5ex]
  00\mapsto0 \\
  01\mapsto0 \\
  10\mapsto0 \\
  11\mapsto1
 \end{array},
 \qquad
 \begin{array}{c}
  \hbox{\tsc{or}} \\[0.5ex]
  00\mapsto0 \\
  01\mapsto1 \\
  10\mapsto1 \\
  11\mapsto1
 \end{array},
 \qquad
 \begin{array}{c}
  \hbox{\tsc{xor}} \\[0.5ex]
  00\mapsto0 \\
  01\mapsto1 \\
  10\mapsto1 \\
  11\mapsto0
 \end{array}.
 $$

\noindent In particular, the logic operation \tsc{not} complements its
one-bit argument, and thus the Forth word \id|not| complements \emph{each} of
the 32 bits of a cell.  The other three logic operators act on corresponding
bits of two input cells to produce a 32-bit result.

\medskip

\index{Forth!logic value}To drive a conditional statement along one or the
other of two possible paths (\sect{conditional statements}) all one needs is
a binary ``flag''---with values `true' and `false'.\footnote
    {When more than two choices present themselves, it is usually more
natural to use a case statement (\cf{case}) rather than many
nested \id|if| statements.} For this purpose, a one-bit cell would be
sufficient; but Forth cells come in a standard size of 32 bits, and one must
have an agreement on which 32-bit pattern(s) should mean `true' and which
`false'.

The Forth-83 standard stipulates that words that \emph{return} a logic flag
(such as \id|=| and similar ``compare'' words) should never put on the stack
anything but the patterns 11\ldots11 for `true' or 00\ldots00 for
`false'; for convenience, these patterns have been entered in the dictionary,
as \tsc{constant} words, under the names \id|true| and \id|false|.\footnote
    {Note that, when printed as signed numbers, \id|true| will yield \id|-1|
and \id|false| will yield \id|0|; as an unsigned number, \id|true| will yield
\id|4294967295| (\id|ffff| in hexadecimal).}
    On the other hand, words that \emph{expect} a logic flag (such as \id|if|
and similar ``conditional'' words) will treat as `false' the pattern
0000000000000000 and as `true' \emph{any other pattern}.

\medskip

As long as one uses only the \id|true| and \id|false| patterns for `true' and
`false', the bitwise logic operations \id|not|, \id|and|, etc.\ can also be
used to manipulate such logic flags. However, if one tries to take advantage
in an indiscriminate fashion of the wider ``catching range'' of
\id|if|\footnote
    {As when using arithmetic as a shortcut to logic.}
 some subtle problems may arise. We shall give just one example, as a warning
to the reckless programmer.\index{Forth!arithmetic to logic conversion}

Consider the word
 \begin{verbatim}
    : beep-if-not-equal ( m n --)
                      = not if
                     beep then ;\end{verbatim}
 (\cf{conditional statements}), which beeps only when $m$ and $n$ are {\em
not} equal. This word would work the same if one replaced `\ttt{= not}' by
just `\ttt{-}'; In fact, if $m$ and $n$ are equal their difference $m-n$ will
be 0, and will be seen as `false' by \id|if|; on the other hand, if they are
different $m-n$ will be a pattern containing at least one non-zero bit, and
will be seen as `true' by \id|if|.

Well, if `\ttt{-}' works ``the same'' as `\ttt{= not}', won't `\ttt{- not}'
work the same as `\ttt{=}' in \id|beep-if-equal| of the previous section? If
$m=n$, their difference $m-n$ is 0 and its complement as given by \id|not| is
the pattern of all \id|1|s (the \id|true| pattern)---which of course is
recognized as `true' by \id|if|, as we intended.  If $m\ne n$, the difference
pattern \emph{will} contain some 1's but \emph{may} also contain some 0's; thus
the complementary pattern returned by \id|not| may contain some \id|1|s---in
which case it will again be recognized by \id|if| as `true', which is {\sl
not} what we intended.

\medskip

\memo{adapt to field words}
Since neighbor words such as \id|center|, \id|north|, etc.\ return \id|1| or
\id|0| as a value, we shall use these values as respectively `true' and
`false' whenever expedient.  Logic operations involving such 1-bit flags work
well, except for \id|not| (since it complements all 32 bits).  The two word
sequence `\id|1 xor|' can be used to get the 1-bit complement. Alternatively,
comparisons such as `\id|=|' `\id|>|' `\id|<|' and `\id|<>|' (not equal) can
be used to convert 1-bit flags into standard logic flags.\footnote{
 The words `\id|0=|' `\id|0>|' etc. also exist as abbreviations for `\id|0
=|' etc.}

\medskip

Finally, it will be useful to remember that word a defined by \id|==|, and
thus associated with a certain subset of $n$ \cam\ layers, will care only
about the $n$ least significant bits of a Forth cell (\cf{}).  Any garbage
that may have accumulated in the remaining bits of the cell as a result of
arithmetic/logic manipulation tricks will be ignored.

\section{Numerical tasks}

No floating-point package is provided with the current version of \cam\
Forth. It is recommended that other programs be used for intensive numerical
tasks.  Data files can be used for exchanging data between \cam\ Forth and
these programs. Moreover, separately compiled C procedures can be directly
linked to the Forth code.

\section{Search order}\sectlabel{search-order}

We have seen that, in addition to the main section, called \id|forth|, the
Forth dictionary may contain a number of more specialized sections
(\id|assembler|, \id|editor|, etc.).\index{Forth!vocabularies} \emph{Search
order} commands allow one to do the necessary vocabulary
switching.\index{Forth!search order} At any moment, the \tsc{current}
vocabulary is the one in which new definitions are inserted, while the {\sc
context} vocabulary is the one where old definitions are looked up. (Of
course, most of the time both \id|current| and \id|context| pointers point to
the \id|forth| vocabulary.)  Just mentioning a vocabulary, such as
\id|editor|, makes it the \tsc{context} vocabulary, superseding the former
\tsc{context}; the word \id|definitions| makes \tsc{current} be whatever the
\tsc{context} is at that moment.  Thus, after saying
        \begin{verbatim}
    editor definitions forth\end{verbatim}
        \id|forth| is \tsc{context} but \id|editor| is \tsc{current}: the
interpreter will keep looking words up in the \id|forth| vocabulary, but any
new definitions will be added to the \id|editor| vocabulary.

The vocabulary organization provides a way to use the same name with
different meanings in different contexts, or to make a word unavailable in a
certain context. In \cam\ Forth, for instance, words that are meaningful only
for manipulating certain registes are segregated in special vocabularies
and made visible only in the appropriate context.

\medskip

The concept of ``context vocabulary'' is extended by providing a number of
optional ``second (third, fourth, etc.)  choices'' when a given token is not
found in the primary context vocabulary.  Although most \cam\ users will not
need to explicitly use this mechanism, it is an integral part of the way that
register setup options and menus are defined in the \cam\ software, and so we
briefly discuss it here.

The additional vocabulary choices are arranged stack fashion---the {\sl
search-order} stack.  In addition, there is a minimal \id|root| vocabulary
which normally is always available as a last-resort choice, and which
contains the search-order words described below.  The command \id|only|
empties the search stack and makes \id|root| the \tsc{context} vocabulary.
After saying \id|only|, the search order will be
        $$\tt
        \begin{tabular}{r|l|}
        \multicolumn{1}{r}{\sc context:} &
\multicolumn{1}{l}{root}\\\cline{2-2}
        \multicolumn{1}{r}{} & \multicolumn{1}{l}{root}
        \end{tabular}
        $$
 \noindent (where the black line represents the search-order stack, now
empty).  Naming a vocabulary makes that vocabulary the \tsc{context}; if you
say \id|forth| now, the search order becomes
        $$\tt
        \begin{tabular}{r|l|}
        \multicolumn{1}{r}{\sc context:} &
\multicolumn{1}{l}{forth}\\\cline{2-2}
        \multicolumn{1}{r}{} & \multicolumn{1}{l}{root}
        \end{tabular}
        $$
 \noindent \id|also| pushes a copy of the \tsc{context} vocabulary onto the
stack; if you said \id|also| now the search order would become
        $$\tt
        \begin{tabular}{r|l|}
        \multicolumn{1}{r}{\sc context:} &
\multicolumn{1}{l}{forth}\\\cline{2-2}
           & forth \\\cline{2-2}
        \multicolumn{1}{r}{} & \multicolumn{1}{l}{root}
        \end{tabular}
        $$
 \noindent meaning, ``Look it up in \id|forth|; if that fails, try \id|forth|
again; if that fails, you've got a last chance with \id|root|; if \emph{that}
fails, then give up!''

If you further say \id|meta also assembler|, the search order (which is
displayed if you type \id|order|) will become
        $$\tt
        \begin{tabular}{r|l|}
        \multicolumn{1}{r}{\sc context:} &
\multicolumn{1}{l}{assembler}\\\cline{2-2}
           & meta \\
           & forth \\\cline{2-2}
        \multicolumn{1}{r}{} & \multicolumn{1}{l}{root}
        \end{tabular}
        $$
 \noindent Finally, the command \id|previous| pops the top of the search
stack into \tsc{context}, dropping the previous \tsc{context}.

This may sound confusing, but is in practice quite straightforward if you
don't try to take advantage of all the tricks that are in principle possible.
Usually you put in the search stack \emph{all} of the vocabularies to be
searched in a certain situation, without worrying much about their order and
without relying on \tsc{context} (so that the latter can be switched rather
freely, without going every time through the \id|also|--\id|previous|
business).  You explicitly make a vocabulary the \tsc{context}---by just
naming it---only (a) when it's a rather secret one that you want to
occasionally pull out of your hat to give a special meaning to the word that
follows, or (b) though it's already in the back-up stack, you want to make
sure that it will be searched \emph{first}.

\medskip

The \tsc{context} vocabulary and the rest of the search-order machinery only
have to do with where a word will be looked up. As mentioned above, newly
defined word are added to the \emph{current} vocabulary---and there is only
one \tsc{current} vocabulary at any moment. The word \id|definitions| makes
the \tsc{current} vocabulary be whatever \tsc{context} is. Thus, if you say
 \begin{verbatim}
    editor definitions forth
 \end{verbatim} the \tsc{context} switches to \id|editor|, then \id|editor|
is made the current vocabulary (by \id|definitions|), and finally the {\sc
context} reverts to \id|forth|.  Though the search order still starts with
Forth, the next definitions will be added to the \id|editor| vocabulary.

\subsection{The Forth thesaurus}

Traditionally, a Forth system is accompanied by a \tdf{glossary}, i.e., a
plain English description, arranged in dictionary form, of the words that
make-up the system itself. We have found the \tdf{thesaurus} format much more
compact, informative, and pedagogical. In the thesaurus, all the \SF\ words
are arranged and discussed \emph{by subject}; an alphabetical index allows one
to locate the thesaurus section where the desired word and related words are
located.


\section{Further reading}

[revise]

\emph{Starting FORTH} by Leo Brodie (Prentice-Hall, 1981) is an excellent
practical introduction to Forth, while \emph{Thinking FORTH}, by the same
author (Prentice-Hall, 1984), discusses the methodology that inspires this
programming language.\index{Forth!references} \emph{Inside F83}, by C.  H.
Ting (Offete Enterprises, 1306 South B.  St., San Mateo, CA 94402; 1985) is a
thorough description of F83's internal structure.  The book \emph{Mastering
Forth}, by A.  Anderson and M.  Tracy (Brady Communications Co., 1984),
describes Micromotion Forth---a commercial package based on the F83 model
(and thus having a close family relationship with the present
implementation).

The complete specifications for the \emph{Forth-83 Standard} (cf.\
\appnd{forth83}) are available from the Forth Interest Group (P.O.  Box 8231,
San Jose, CA 95155).\index{Forth-83 standard}

The periodical \emph{FORTH Dimensions}, published by the Forth Interest Group,
P.O. Box 8231, San Jose, CA, is a good source for news, applications,
programming techniques, literature listings, and software and hardware
developments; most of the above books can be purchased from the F.I.G\null.
The \emph{Journal of Forth Application and Research}, published by the
Institute for Applied Forth Research, Inc., is a more academically oriented
publication.


