\chapter{A Forth tutorial}\label{tuto}  % -*- Mode:TeX -*-

The main purpose of this tutorial is to give you an overall {\sl
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, by running the program \id|F83.EXE| from the DOS level;
or you can run \id|CAM.EXE| as you have been doing so far, and access
the Forth interpreter from the \cp\ by issuing the command \keyF\ (or \keyf).

\section{The command interpreter}

You may visualize the Forth {\sl 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 Sections
\ref{access-forth} and \ref{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 \iprog{BYE} dismisses the interpreter; you are then
automatically returned to the context (namely, the \cam\ control panel
or the operating system) 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 {\sl tokens},\index{Forth/token} using ``blank space'' (one or more
consecutive spaces) and {\sl 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 {\sl dictionary} of terms and some miscellaneous conventions,
which together make up the Forth language. The dictionary's contents
reflect the range of things that the interpreter currently knows
about. 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 run 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 {\sl
environment} rather than just a programming {\sl language}.

\section{The compiler}\label{compiler}

The entries that make up the Forth dictionary are called, as you might
expect, {\sl words}.\index{Forth/word}  To {\sl 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 {\sl interpreter} does in
response to your words) is what {\sl 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 (`{\tt :}'), the interpreter summons
the aid of another technician, called the {\sc colon \sl
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 (`{\tt ;}')---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 {\sc 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}\label{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  +  '  CONSTANT  C@  ;  :  C!  0=\end{verbatim}
 taken at random from the dictionary give you an idea of what typical
Forth words look like.  {\sl 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 `{\tt :}', can appear
as part of a Forth word, or even make up a word all by themselves; the
word `{\tt C,}' is very different than the two-word sequence `{\tt 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|Believe it or not, this is a beep!|'.  This
is done by redefining \id|BEEP| as follows
 \begin{verbatim}
    : BEEP    CR ." Believe it or not, 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 {\tt." }$\langle{\rm
text}\rangle${\tt "} will print $\langle{\rm text}\rangle$ on the screen (this
construct can only be used within a {\sc colon} definition).  If you now define
 \begin{verbatim}
    : 4BEEP   BEEP BEEP BEEP BEEP ;\end{verbatim}
 this word will be compiled using the {\sl new} version of \id|BEEP|,
and when executed will print
 \begin{verbatim}
    Believe it or not, this is a beep!
    Believe it or not, this is a beep!
    Believe it or not, this is a beep!
    Believe it or not, 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| {\sl will retain its
original meaning}---which is tied to the {\sl 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 ``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 {\tt EDITOR} vocabulary
containing editor-specific terms, etc.\index{Forth/vocabularies}  As explained in Section
\ref{search-order}, there are commands available for specifying which
vocabularies should be searched at any particular moment, and in what
order.


\section{Numbers}\label{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|100| while operating in \id|DECIMAL|
mode, this token will be recognized as a number and will be internally
converted to 0000000001100100 (Forth stores integers in 16-bit
cells); however, if you have told the interpreter to operate in
\id|HEX| mode,\footnote
    {I.e., base sixteen rather than base ten. In Forth,
numbers can be read and printed in any base you choose.}
    the same token will be given the meaning 0000000100000000.

\medskip

Some numbers that for historical or practical reasons deserve explicit
mention, such as `three', {\sl 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 {\sl words} in the Forth dictionary.\footnote
    {Words of type {\sc constant}; cf.\ Section \ref{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 16-bit range (only
$2^{16}$=65,536 different values are available) so that the ordinary counting sequence
-2,-1,0,1,2,3,\ldots at a certain point ``wraps around'': \ldots
32765,32766,32767,-32768,-32767,-32765,\ldots,-2,-1,0 (cf.\ Section \ref{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.\ Section \ref{precision}).

\section{The stack}\label{stack}

\index{Forth/stack}Forth manages to achieve remarkable expressive
power and efficiency; yet a Forth {\sl 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 {\sl cell}, having a capacity of 16 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 {\sl
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 Section \ref{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 {\sl 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
{\sl 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 `{\tt .}' (``dot'') picks up the top cell of the stack and prints
its contents {\sl 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 `{\tt
356 .}' would be something like `{\tt print(356)}'.) Note that the
stack went up one level with \id|356|, down one level with `{\tt .}',
and is now the same height as before.

The word `\verb|+|' (``plus'') gobbles up the top {\sl two} cells of the
stack, adds them together, and places the result---consisting of {\sl
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 `{\tt .}').  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{\tt #2}}
$$
  \begin{array}{lcc}
    \hbox{\sc stack} & \hbox{\sc input} & \hbox{\sc
output} \\
    \st{\ldots\ }{1} \\
    \st{\ldots\ 1}{2} \\
    \st{\ldots\ 1 2}{+} \\
    \st{\ldots\ 3}{4} \\
    \st{\ldots\ 3 4}{+} \\
    \st{\ldots\ 7}{.} & \hbox{\tt 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 {\sl
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{\tt 1 1 + 1 + 1 +}\quad{\rm and}\quad\hbox{\tt 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{\sc stack} & \hbox{\sc 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{\sc stack} & \hbox{\sc 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}\label{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 Section \ref{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
{\sl 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 the Forth {\sl
screen editor}.\index{Forth/editor} Then you can ask the interpreter to use this file (or
a portion of it) as the input stream, instead of what comes from the
keyboard; this process is called {\sl loading}.\index{Forth/loader} When you load a file,
everything (well, {\em 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.\footnote
    {\label{foot.return}A typical Forth source file is organized as a collection
of text ``screens;'' the lines that make up a screen
are stored one after the other in the file without any intervening separation marks. Thus,
within a text screen, end-of-line does {\em not} act as a carriage return or as a token
separator (cf.\ footnote \ref{foot.blank} in this chapter); on the other hand,
the physical end of the screen does.}

\medskip The commands for accessing the editor and the loader directly from the \cp\
without explicitly going through the Forth interpreter are discussed in Sections
\ref{enter-editor} and \ref{enter-loader}; from within the Forth interpreter, use
\iprog{EDIT} and \iprog{LOAD} (Sections \ref{util-edit} and \ref{util-load}).

\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 formatting scheme used in this book is the following
 \begin{verbatim}
                               : 3BEEP
                BEEP BEEP BEEP ;
                               : BEEP
                          BEEP 
                      10 TICKS ;
                               : 4BEEP
           BEEP BEEP BEEP BEEP ;\end{verbatim}
 where dictionary entries are lined up on the right half of the page
and the ``bodies'' of the definitions are segregated on the left half.

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 ( two more )\end{verbatim}
and the interpreter will never hear what is ``in parentheses.''\footnote
    {Observe that the following spacing is correct too

{\tt BEEP BEEP ( two beeps)BEEP BEEP ( two more)}

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

{\tt BEEP BEEP (two beeps) BEEP BEEP (two more)}

 \noindent won't do, since it will make the interpreter think that
`\verb|(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''}\label{constants}

In Section \ref{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
{\sc colon} compiler, the competent technician is the {\sc colon} {\sl
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 {\sc code} ``compiler;''\index{Forth/code{\sc 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 {\sc constant} compiler,\index{Forth/constant{\sc constant}}
(cf.\ Section \ref{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 ({\sl code field\/})\index{Forth/code field} contains a notice saying ``I
am to be executed by the {\sc constant} interpreter;'' the second
({\sl data cell\/})\index{Forth/data cell} is reserved for the value of the constant. At
this point the {\sc 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 {\sc 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 `{\sc 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 {\sc constant} is that
it returns the {\sl value} of its data cell, rather than a {\sl
pointer} to it (cf.\ \id|VARIABLE|) below).  

\medskip

In \cam, ``neighbor words'' such as \id|NORTH|, \id|SOUTH|, etc.\ act like Forth
{\sc constant}s insofar as they return a value; however, this value will change
very many times during the construction of a rule table.

\bigskip

Forth provides another mechanism for accessing a piece of data, namely
by its {\sl 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 {\sl value}.
The {\sc variable} compiler,\index{Forth/variable{\sc variable}}
used in a construct such as
 \begin{verbatim}
                        VARIABLE TIME\end{verbatim}
 is analogous to the {\sc 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 {\sc variable} interpreter
puts on the stack the {\sl 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 {\sl value} of \id|TIME| you use the word `\verb|@|'
(pronounced ``fetch''), as in
 \begin{verbatim}
    TIME @  ( data )\end{verbatim}
 (i.e., `{\tt @}' 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., `{\tt !}' expects a piece of data {\sl 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{{\tt TIME}'s contents} & \hbox{\sc stack} & \hbox{\sc 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.\ Section \ref{logic}.)

From the viewpoint of \cam's user, Forth {\sc 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}\label{defining-words}

The words \id|:| (`colon'), \id|CONSTANT|, and \id|VARIABLE| belong to the class of
{\em 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
{\em control constructs}, discussed in the following sections.

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

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

\section{Iteration}\label{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. Short
of turning off the power, there is no way you can get out of this
loop.\footnote
    {Unless your computer has a working {\sc break} key---the
equivalent of a ``panic button.''}

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 the two elements of the
pair, flush on the {\sl 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 {\tt 999BEEPS} 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 {\sc limit}) and 0 (the loop {\sc
index}), and saves them for later use.  The execution proceeds until
\id|LOOP| is encountered. At this point, {\sc index} is incremented by
one and compared with {\sc limit}: if {\sc index}={\sc limit} the loop
is terminated; otherwise, execution jumps back to \id|DO|.\footnote
    {The loop index is a modulo-$2^{16}$ counter.
The minimum number of iterations, namely 1, is achieved when
the loop is entered with {\sc index} just one less than {\sl limit};
the maximum, when the loop is entered with {\sc
index} {\sl equal} to {\sc limit}: \id|0 0 LOOP| will cycle $2^{16}$
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
{\sc 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 flow-control constructs can only appear inside a
{\sc colon} definition: you cannot say
 \begin{verbatim}
    100 0 DO BEEP LOOP\end{verbatim}
at the command-interpreter level.

\section{Stack comments}\label{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 {\sl 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
``dash'' (customarily a double-dash) to indicate the word in question.
Before the dash we write a list of what the word {\sl expects} on the
stack; after the dash we write a list of what the word {\sl leaves} on it. If nothing
appears {\sl after} the dash, the dash itself is usually omitted.

What really counts is the {\sl 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 {\sl 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}
 and then 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.

Note that if we define words giving a little thought to the ``stack
interface'' ({\sl who} should supply or consume {\sl what} and {\sl
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{{\tt DUP}, {\tt DROP}, and all that}\label{dup-drop}

The Forth word `{\tt *}' (``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 {\sl 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 {\sl duplicate} copy of it on
top of it; e.g.,
 $$
  \begin{array}{ll}
   \hbox{\sc stack} & \hbox{\sc 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 `{\tt *}' 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 {\sl pronouns} in English (`this', `that', `one another',
etc.), in that they allow one to refer by {\sl position} rather than by
{\sl 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 tell you what's on the stack before and after).

\section{Case selection}\label{case}

A flow-control construct that is extensively used in programming \cam\
is the {\sc case} statement,\index{Forth/case construct{{\sc case} construct}}
which allows one to
select for execution one of several alternative actions. 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 Section \ref{numbers}) numbers are {\sl not} in the dictionary.
There is an easy fix to this problem: {\sl before} defining \id|DAYS|,
enter the desired numbers in the dictionary as {\sl 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 {\sl
number} \id|28| used to do before. The case statement will now accept
it as a list item.

\section{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 {\em 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 exists also two {\sl 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 {\sl 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{Logic expressions}\label{logic}

In defining a \cam\ rule, sometimes it is convenient to treat the
contents of a \cam\ cell as a logic quantity (`on' or `off', `true'
or `false') and sometimes as a number (0 or 1---or even 0, 1, 2, or 3
when one is dealing with two bit-planes at once).  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 \cam\ Forth 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 16-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 65,535 (``unsigned number''), an integer from
-32,768 to +32767 (``signed number''), two ASCII characters
(8 bits each) or, quite commonly, a single ASCII character
(using only the lower 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 1000000000101010; the three words `{\tt .}', \id|U.|, and \id|EMIT|
will all print on the terminal the contents of this cell. However,
`{\tt .}' will treat it as a signed number, and print `{\tt -32726}';
\id|U.| will treat it as un unsigned number, and print `{\tt 32810}';
and \id|EMIT| will treat it as a character, and print `{\tt *}' (since
the lower eight bits of the pattern, namely 00101010, make up the
ASCII code for `{\tt *}').

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 eight bits of a pattern by {\sc and}ing it with an appropriate
{\sl mask} pattern, namely 0000000011111111, in
which the upper eight bits are ``off'' and the lower eight are ``on.''

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

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

\medskip

\index{Forth/logic value}To drive a conditional statement along one or the other of two
possible paths (see previous section) 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.\ Section \ref{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 16 bits, and
one must have an agreement on which 16-bit pattern(s) should mean
`true' and which `false'.

The Forth-83 standard stipulates that words that {\sl return} a logic flag
(such as \id|=| and similar ``compare'' words) should never put on the
stack anything but the patterns 1111111111111111 for `true' or
0000000000000000 for `false'; for convenience, these patterns have been
entered in the dictionary, as {\sc 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|65535| (\id|FFFF| in hexadecimal).} 
    On the other hand, words that {\sl expect} a logic flag (such as
\id|IF| and similar ``conditional'' words) will treat as `false' the
pattern 0000000000000000 and as `true' {\sl 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.\ previous section), which beeps only when $m$ and $n$ are
{\sl not} equal. This word would work the same
if one replaced `{\tt = NOT}' by just `{\tt -}';
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 `{\tt -}' works ``the same'' as `{\tt = NOT}', won't `{\tt -
NOT}' work the same as `{\tt =}' 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 {\sl will} contain some
1's but {\sl 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

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 16 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 words such as \id|>PLN0| and
\id|>AUX0|, which take a stack item and write it as an entry of a \cam\
look-up table (Section \ref{table-generation}), only use the least
significant bit of the item: any garbage that may have accumulated in
the remaining bits as a result of arithmetic/logic manipulation tricks
will be ignored.  (``Joint'' versions of these words, such as \id|>PLNA|
and \id|>AUXA|, use the lowest {\sl two} bits.)


\section{Extended precision}\label{precision}

It is occasionally necessary to handle numerical quantities having a
greater range or resolution than that provided by 16-bit integers.
Forth's traditional approach has been to provide minimal support for {\sl
double numbers} (i.e., double-precision integers) and let the user
define whatever data structures and operations are needed beyond this.

On the stack, double numbers occupy two consecutive Forth cells,\index{Forth/double number}
with the most significant cell on top. The words \id|2DUP|, \id|2DROP|,
\id|2@|, \id|2!|, etc., which are useful also in other contexts, can be used
for manipulating double-numbers. The words \id|D+|, \id|D-|, \id|D=|, etc.
are specifically intended for double-number arithmetic.

\medskip

No floating-point package is provided with the current version of \cam\ Forth.\footnote
    {A floating-point interface that takes advantage of the 8087 or
80287 coprocessor may be included in a later release.}
        For the moment, it is recommended that other programs be used
for numerical tasks, using data files for exchanging experiment data
between \cam\ Forth and these programs.  (Data file formats are
discussed in Section \ref{data}.)

Occasionaly, quadruple precision integers\index{Forth/quadruple
number} (``quad'' numbers) may come in handy for some data-analysis
tasks; the file \iprog{QUAD.4TH} provides optional quad-number
utilities.


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

We have seen that, in addition to the main section, called \iprog{FORTH}, the Forth dictionary
may contain a number of more specialized sections (\iprog{ASSEMBLER},
\iprog{EDITOR}, etc.).\index{Forth/vocabularies} {\sl Search order} commands allow one to do the necessary
vocabulary switching.\index{Forth/search order} At any moment, the {\sc 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
\iprog{CURRENT} and \iprog{CONTEXT} pointers point to the \id|FORTH| vocabulary.)
Just mentioning a vocabulary, such as \id|EDITOR|, makes it the {\sc context}
vocabulary, superseding the former {\sc context}; the word \iprog{DEFINITIONS} 
makes {\sc current} be whatever the {\sc context} is at that moment.
Thus, after saying
        \begin{verbatim}
    EDITOR DEFINITIONS FORTH\end{verbatim}
        \id|FORTH| is {\sc context} but \id|EDITOR| is {\sc 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, certain ``neighbor
words'' (such as \id|S.EAST|, \id|&CENTER|, etc.) are segregated in
special vocabularies in order to make them available only when the
corresponding ``neighbor wires'' are actually connected to the lookup
table.

\medskip

F83 enriches the concept of ``context vocabulary'' by providing a number
of optional ``second (third, fourth, etc.)  choices'' when a given token
is not found in the primary context vocabulary.  
Although \cam\ experiments will not need to use this mechanism,
it is an integral part of the way that neighborhood 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 \iprog{ROOT} vocabulary which
normally is always available as a last-resort choice, and which
contains the search-order words described below.  The command
\iprog{ONLY} empties the search stack and makes \id|ROOT| the {\sc
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 {\sc 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
\iprog{ALSO} pushes a copy of the {\sc 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 {\sl that} fails,
then give up!'' 

If you further say \id|META ALSO ASSEMBLER|, the search order (which is displayed
if you type \iprog{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 \iprog{PREVIOUS} pops the top of the search stack
into {\sc context}, dropping the previous {\sc 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 {\sl all} of the
vocabularies to be searched in a certain situation, without worrying
much about their order and without relying on {\sc 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 {\sc 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 {\sl
first}.

\medskip

The {\sc 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 {\sl current} vocabulary---and there is only one {\sc current} vocabulary
at any moment. The word \id|DEFINITIONS| makes the {\sc current} vocabulary
be whatever {\sc context} is. Thus, if you say 
 \begin{verbatim}
    EDITOR DEFINITIONS FORTH
 \end{verbatim}
the {\sc 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.

\section{The Forth glossary}\label{forth-glossary}

Probably the most useful piece of documentation to accompany a Forth
system is a {\sl glossary}, i.e., a plain English description,
arranged in dictionary form, of the words that make-up the system
itself.\index{Forth/glossary}

The glossary provided at the end of this manual (Appendix \ref{gloss})
consists of two sections.  The first documents those \cam-specific words
that are meant to be employed by the \cam\ users; the second
section describes a number of general-purpose Forth words that are
specific to the present implementation, as well as a few F83 words
that deserve clarification. 

Common-usage Forth words are documented in any of a number of Forth
manuals (cf.\ next section).  Excerpts from the {\sl Forth-83
Standard}---which specifies standards for a number of fundamental words
and constructs---are reproduced in Appendix \ref{forth83}.\index{Forth-83 standard}  This
standard is closely obeyed by the F83 implementation.

\section{Further readings}

{\sl Starting FORTH} by Leo Brodie (Prentice-Hall, 1981) is an excellent
practical introduction to Forth, while {\sl Thinking FORTH}, by the same
author (Prentice-Hall, 1984), discusses the methodology that inspires
this programming language.\index{Forth/references} {\sl 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 {\sl 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 {\sl Forth-83 Standard} (cf.\
Appendix \ref{forth83}) are available from the Forth Interest Group
(P.O.  Box 8231, San Jose, CA 95155).\index{Forth-83 standard}

The periodical {\sl 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 {\sl Journal of Forth
Application and Research}, published by the Institute for Applied
Forth Research, Inc., is a more academically oriented publication.
