\documentclass[a4paper]{memoir}
\usepackage{manual}
\setlength{\parindent}{0.0cm}
\setlength{\parskip}{1.4ex}
\headstyles{default}
%%% ToC down to susubsections
\settocdepth{subsubsection}
%%% Numbering down to sections
\setsecnumdepth{subsection}
%%% index
\makeindex[lines]
%%%% end preamble -----------------------------------------------------

\begin{document}
\tightlists
\midsloppy
\chapterstyle{ell}
% ----- Title Page
\frontmatter
\pagestyle{empty}
%%
\title{\cafeobj~User's Manual \\ --- ver.1.4.12 ---}
\author{Ataru T. Nakagawa \and Toshimi Sawada \and Kokichi Futatsugi}
%\date{\today}
\date{2013/3/1}
\bibliographystyle{plain}

\maketitle
\vfill
\begin{center}
\includegraphics[scale=0.2]{cafe-logo.pdf}
\end{center}
\vfill
%% \Hline
%% \begin{center}
%% \footnotesize{Revised on 2012/3 by Kosakusha}
%% \end{center}
\thispagestyle{empty}
%% \Hline
%% %%%%
%% \subsubsection*{NOTE}
%% This manual is out of date and is subject to change.

%% \subsubsection*{Changes from Version 1.3}

%% The main changes from version 1.3 are as follows.
%% \begin{itemize}
%% \item In addition to Gnu Common Lisp, CMU Common Lisp and Allegro Common Lisp
%%   can be used as a platform.
%% \item Faster rewrite engines are now available, and can be invoked from
%%   \cafeobj.
%% \item The predicate \verb|==>| (for transition relations) gets a more
%%   powerful support. A couple of new switches are added for this reason.
%% \item Behavioural axioms can be used in equational reduction, and
%%   an operator attribute \kbd{coherent} is added for this purpose.
%% \item A behavioural reduction command is introduced.
%% \item Sort predicates are introduced.
%% \end{itemize}
%% \Hline
\clearpage
\newpage
\pagestyle{headings}
\tableofcontents
%\listoffigures
\clearpage

%%%%%%%%%%%%%%%%%%%%%%
\pagestyle{ruled}
\chapter{Introduction}

\cafeobj~is a specification language based on three-way extensions to
many-sorted equational logic: the underlying logic is
order-sorted, not just many-sorted; it admits unidiretional transitions,
as well as equations; it also accommodates hidden sorts, on top of
ordinary, visible sorts. A subset of \cafeobj~is executable, where the
operational semantics is given by a conditional order-sorted term rewriting
system. These theoretical bases are indispensable to employ \cafeobj~properly.
Fortunately, there is an ample literature on these subjects, and we are able
to refer the reader to, e.g., \cite{e-m85}, \cite{m-g82} (for basics of
algebraic specifications), \cite{osa}, \cite{osa-survey} (for order-sorted
logic), \cite{hsa} (for hidden sorts), \cite{eatcs-coalg} (for coinduction),
\cite{rew-logic} (for rewriting
logic), \cite{institution} (for institutions), and \cite{trs-eatcs},
\cite{trs-handbook} (for term rewriting systems), as primers.
The logical aspects of \cafeobj~are explained in detail in \cite{razvan96-1}
and \cite{cafeobj-rep}. This manual is for the initiated, and we sometimes
abandon the theoretical rigour for the sake of intuitiveness.

For a very brief introduction, we just highlight a couple of features
of \cafeobj. \cafeobj~is an offspring of the family of algebraic
specification techniques. A specification is a text, usually of
formal syntax. It denotes an algebraic system constructed out of
sorts (or data types) and sorted (or typed) operators. The system
is characterised by the axioms in the specification. An axiom was
traditionally a plain equation (``essentially algebraic''), but is now
construed much more broadly. For example, \cafeobj~accommodates
conditional equations, directed transitions, and (limited) use of
disequality.

The underlying logic of \cafeobj~is as follows\footnote{
 Some of the authors feel that some of these technical terms are
 queer. But to avoid confusion, we basically keep to the
 established terminology.
}.
\begin{itemize}
\item[]\textbf{ Order-sorted logic}\cite{osa}. A sort may be a subset of
  another sort. For example, natural numbers may be embedded into rationals.
  This embedding makes valid the assertion that 3 equals 6/2. It also
  realises ``operator inheritance'', in the sense that an operator
  declared on rationals are automatically declared on natural numbers.
  Moreover, the subsort relation offers you a simple way to define
  partial operations and exception handling.
\item[] \textbf{ Rewriting logic}\cite{rew-logic}. In addition to equality,
  which is subject to the law of symmetry, you may use transition relations,
  which are directed in one way only. State transitions are
  naturally formalised by those relations. In particular, transition
  relations are useful to represent concurrency and/or indeterminacy.
\item[]\textbf{ Hidden sorts}\cite{hsa}. You have two kinds of equivalence. One
  is a minimal equivalence, that identifies terms (elements) iff
  they are the same under the given equational theory. Another
  equivalence, employed for so-called hidden sorts, is behavioural:
  two terms are equivalent iff they behave identically under the
  given set of observations.
\end{itemize}
We would also like to emphasise a very useful feature of \cafeobj.
\begin{itemize}
\item[]\textbf{ Parameters}. There are many sorts that are inherently
  generic. Stacks, lists, sets and so on have operations that
  act independently of the properties of base (``data'') elements.
  A more tricky case is priority queues, which require base elements to
  have an order relation. You may define these sorts by
  parameterised modules, where base elements are parameterised out.
  A parameter may be subject to constraints. For example, the parameter
  of a priority queue module may be declared an ordered set, not
  an arbitrary set.
\end{itemize}

\section{Legends}

Restrictions, particulars, and prejudices of the current implementation
shall be highlighted by preceding \emph{!!}, as

\begin{warning}
Woe betide those who do not heed this warning!
\end{warning}

while syntactical definitions are shown as

\begin{bsyntax} title
\mbox{\texttt{I am a language construct.}}
\end{bsyntax}
\setcounter{bsyntax}{0}

The definitions inside the box are by way of notations as follows.
\begin{itemize}
\item[(1)] $\{$, $\}$ are meta-syntactical brackets.
\item[(2)] $|$ separates alternatives.
\item[(3)] $*$ means zero or more repetitions of the preceding construct.
\item[(4)] $+$ means one or more repetitions.
\item[(5)] $*_{,}$ means zero or more repetitions separated by commas.
\item[(6)] $+_{,}$ means one or more repetitions separated by commas.
\item[(7)] $[$, $]$ enclose optional constructs.
\item[(8)] The above symbols, to appear as they are, are enclosed by quotes,
  as ``\verb|{|''.
\item[(9)] Symbols in the typewriter font appear as they are: \kbd{x} is
  literally \kbd{x}. In case this convention is ambiguous, e.g. when a
  parenthesis appears in isolation, symbols are quoted as in (8).
\end{itemize}
For example,

\begin{tabular}{l}
  \kbd{A} $+_,$
\end{tabular}

represents sequences of one or more \verb|A|'s, separated by commas.

%%%%%%%
\mainmatter
\pagestyle{ruled}
\chapter{Dialogue with the System}

\section*{Availability}

You may obtain a complete distribution package from the
following site. 
\begin{vvtm}
\begin{ccode}
  http://www.ldl.jaist.ac.jp/cafeobj/system.html
\end{ccode}
\end{vvtm}
% where \verb|???| is a version numbering. Or you can get a system linked
% from the site
% \begin{vvtm}
% \begin{verbatim}
%   http://www.ldl.jaist.ac.jp/cafeobj/
% \end{verbatim}
% \end{vvtm}
% Mirror sites in Europe and USA are under consideration.

% The current version works under Unix operating systems (usual
% vernaculars, including various versions of Sun OS, FreeBSD, and Linux, are
% all okay) or Mac (MacOSX 10.5 or later), and is implemented on
% various Common Lisp processors (including
% Gnu, CMU, Allegro, and MacLisp). But you cannot run, for example, MacLisp
% on Solaris, for an obvious reason. On the question of which Lisp systems
% to use on which operating systems, and which Lisp systems to be obtained
% from where, consult the installation guide (README) in the distribution
% package.
The current version works under i386 Linux, i386 MacOSX (version 10.5
or later), and win32. Binary package of these platforms can be
obtained from the above site. You can also download source code of the
system from the same place. 

% In principle the system should also work on Windows with Allegro, but there
% is no guarantee of its behaviours. The implementors have no intention
% of testing the system under Windows environments.

\section{Hello, Goodbye}\label{sec:p2-startup}

\subsection{Starting Up}

After installation, type ``\verb|cafeobj|'' to your shell to
invoke the system. Then the \cafeobj~interpreter starts up, producing
a welcoming message.
% \begin{vvtm}
% \begin{verbatim}
%   % cafeobj
%   -- loading standard prelude 
%   ; Loading /mnt1/lang/cafeobj-1.4/prelude/std.bin.
%
%                      -- cafeobj system Version 1.4.100203p116 --
%                      built: 1984 Dec 24 Mon 3:44:17 GMT
%                            prelude file: std.bin
%                                     ***
%                         1999 Dec 31 Fri 23:59:45 GMT
%                               Type ? for help
%
%
%   CafeOBJ> 
% \end{verbatim}
% \end{vvtm}
\begin{vvtm}
\begin{ccode}
% cafeobj
-- loading standard prelude
; Loading /usr/local/cafeobj-1.4/prelude/std.bin

          -- CafeOBJ system Version 1.4.8(PigNose0.99,p18) --
                   built: 2010 Jul 5 Mon 0:50:01 GMT
                         prelude file: std.bin
                                  ***
                      2010 Jul 5 Mon 6:59:56 GMT
                            Type ? for help
                                  ***
                  -- Containing PigNose Extensions --
                                  ---
         built on International Allegro CL Enterprise Edition
               8.2 [Mac OS X (Intel)] (Jul 5, 2010 9:49)
CafeOBJ>
\end{ccode}
\end{vvtm}
For a moment, ignore the message.
``\verb|cafeobj>|'' is a prompt for your requests. You may type
modules, views, parsing instructions, reduction commands, and so on,
each of which shall be gradually introduced in the rest of the manual.

As a first experiment, try feeding a trivial module definition
(you need not worry about the meaning for now).
\begin{vvtm}
\begin{ccode}
module TEST { [ Elt ] }

-- defining module TEST
processing input : /usr/local/cafeobj-1.4/lib/bool.mod
processing input : /usr/local/cafeobj-1.4/lib/truth.mod
-- defining module! TRUTH
-- reading in file  : truth
-- done reading in file: truth
............_......* done.
-- defining module! BOOL............._......................* done.._* done.
CafeOBJ> 
\end{ccode}
\end{vvtm}
Your input is up to the first newline character. The rest is from the
system. It shows that the system has accepted the definition, put
this module somewhere in its memory, to be available hereafter.
%%% t.swd 2010/June
\footnote{As you see in the example above, system may load some other
modules required for defining your module. 
In this case, \kbd{TRUTH} and \kbd{BOOL} are loaded in automatic.
These are modules which provides built-in Boolean types and
operations.
More on this at page~\pageref{sec:p2-import-decl}.}
%%%
You may continue to feed other modules, or check if indeed the module
is correctly stored. As a further trial, type
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select TEST
  TEST>
\end{ccode}
\end{vvtm}
The command \texttt{select}\index{\texttt{select}} takes as argument a module name.
``\verb|TEST>|'' is a new prompt. As you see, \verb|TEST| is the name
of the module just \texttt{select}ed. The system maintains
a module, called the \emph{current module}\index{current module},
that is the focus of manipulation at the time. The initial prompt
``\verb|CafeOBJ>|'' indicates the current module is not yet supplied.
Or a module \verb|cafeobj| is now current (it is possible, if confusing,
to define such a module).
Various commands, such as parsing and reduction, are executed under
the current module. For more details on current modules, see Section
\ref{sec:p2-current-module}.

%\begin{warning}
%  \cafeobj~has a command structure quite similar to that of
%  OBJ3\cite{OBJ}. In fact, former versions of \cafeobj~accepted
%  a subset of OBJ3's commands. This version, however, contains
%  some major extensions, and adopts different conventions. In OBJ3,
%  the current module changes whenever you have defined a new module,
%  fed a reduction command, etc. In contrast, in this version of \cafeobj~,
%  the current module does not change (by default). To get a convention
%  similar to OBJ3, you may toggle a switch (cf. Section
%  \ref{sec:p2-current-module}).
%\end{warning}

%\begin{warning}
%  This version has discarded another convention of OBJ3. In OBJ3, many
%  commands and language constructs require ``blank-period'' stoppers.
%  Former versions of \cafeobj~clinged to the convention, partly
%  for compatibility, partly for easier lexical analyses.
%  This version does not require them, most of the time.
%\end{warning}

\subsection{Quitting the System}

To quit \cafeobj, type \verb|quit| (or \verb|q| for short) or the end of
input character (usually control-D) at a prompt.
Then the interpreter terminates and the control is given back to
the original shell.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> quit
  [Leaving CafeOBJ]
  %
\end{ccode}
\end{vvtm}
%\begin{warning}
%Former versions of \cafeobj~allowed you to quit to the underlying lisp
%environment. Upon \verb|quit|, this version goes straight back to the
%shell.
%\end{warning}

\subsection{Emergency --- Resumption and Bug Reports}

In detecting errors, \cafeobj~growls.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> module ERROR }
  [Error]: was expecting the symbol `{' not `}' .

  CafeOBJ> 
\end{ccode}
\end{vvtm}
The above message starting with ``\verb|[Error]|'' indicates that
the system detected a syntax error in processing your input.

Due to irrecoverable input errors, or just to mulfunctions, \cafeobj
~may stop abnormally, and throw the control away to an error environment.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> ^C
  Correctable error: Console interrupt.
  Signalled by CAFEOBJ-TOP-LEVEL.
  If continued: Type :r to resume execution, or :q to quit to top level.
  Broken at SYSTEM:TERMINAL-INTERRUPT.  Type :H for Help.
  CHAOS>>
\end{ccode}
\end{vvtm}
The above session was obtained by typing the interrupt code (usually
Control-C) at the initial prompt, forcing \cafeobj~to stop willy-nilly.
The prompt ``\verb|CHAOS>>|'' indicates you plunged into an error
environment. The above message may look familiar to you, if you are
a user of GCL. The message was from GCL, and the error
environment is a GCL error loop\footnote{
Error loops of CMU, Allegro, and MacLisp work more or less similarly,
and the same recover command \kbd{:q} works.
}.

Following the instructions from GCL, you may resume the \cafeobj~session
with \verb|:q|, as
\begin{vvtm}
\begin{ccode}
  CHAOS>>:q

  CafeOBJ>
\end{ccode}
\end{vvtm}
The message 

There may be irrecoverable cases, when \verb|:q| (or similar commands of
other Common Lisp systems) fails to work.
Then try ``\verb|(cafeobj t)|''. This is a more
robust means to return to \cafeobj. If, for goodness, you are unable
to return to \cafeobj~even then, exit GCL (control-D normally works)
and start from scratch.

If the system still works fine, but if you happen to have destroyed
some vital module definitions, try
\begin{vvtm}
\begin{ccode}
  CafeOBJ> reset
\end{ccode}
\end{vvtm}
which restores the definitions of built-in modules (Chapter
\ref{sec:p2-builtin-module}) and preludes (Section \ref{sec:p2-init-opt}).
This command does not affect other modules. For complete cleanup, use
\begin{vvtm}
\begin{ccode}
  CafeOBJ> full-reset
\end{ccode}
\end{vvtm}
which reinitialises the internal state of the system. But before calling
this command, remember that
you will lose all the module definitions you have supplied so far.
You are warned.

\paragraph{Bug Reports}

The system is under continual improvement. If you detect any bugs,
malfunctions, or just inconveniences, do let us know. The support team is
reachable via
\begin{vvtm}
\begin{ccode}
  cafe-bugs@ldl.jaist.ac.jp
\end{ccode}
\end{vvtm}

%%%%%%%%
\section{Files and Libraries}

\subsection{Reading Files}\label{sec:p2-reading-files}

Not every module is as trivial as \verb|TEST|, and you will % sooooon
soon need library systems for store/recovering module definitions,
test cases, and so on. \cafeobj~requires every imported module
(cf. Section 
\ref{sec:p2-import-decl}) to be
defined beforehand, so you need a recursive file reference
mechanism. As a minimum, you need the following command.

\begin{bsyntax} \texttt{input} command\index{\texttt{input}}\index{\texttt{in}}\Hline
\texttt{input}~\textit{pathname}
\end{bsyntax}

\verb|input| (or \verb|in| for short)
requests the system to read the file specified by the
pathname. The file itself may contain \verb|input| command, and so on,
ad nauseum. \cafeobj~reads the file up to eof, or until it encounters
a line that only contains (the literal) \verb|eof|.

\begin{bsyntax} \texttt{eof}~command \index{\texttt{eof}}\Hline
\texttt{eof}
\end{bsyntax}

This little command is especially useful when the % program 
codes are under development. You can supply the system with only those
definitions that are up to scratch.

Pathnames follow the conventions of the Unix file system. Both
relative and absolute paths are possible, and
``\verb|~|''\index{\texttt{\~} (home directory)} 
denotes your home directory.
If there is no file with the pathname, the system expands the name
with suffixes ``kbd{.cafe}''\footnote{The older systems prior
  to version 1.4.8 used a diffrenct suffix ``\kbd{.mod}''. 
  This is also supported for compatibility.}
\index{\texttt{.cafe} (suffix)} \index{\texttt{.mod} (suffix)}
or ``\kbd{.bin}''
\index{\texttt{.bin} (suffix)} and re-search the
directory. By convention, a file suffixed with ``\kbd{.cafe}'' is assumed
to contain definitions and commands written in \cafeobj, 
while ``\kbd{.bin}''
indicates a file containing internal codes. Normally, you should prepare
``\kbd{.cafe}'' files yourself, and leave the system to create
``\kbd{.bin}'' files (see Section \ref{sec:p2-save-restore}).

Some directory traversal commands of Unix are also available.

\begin{bsyntax} \texttt{cd}~ command \index{\texttt{cd}}\Hline
\texttt{cd}~\textit{pathname}
\end{bsyntax}

\begin{bsyntax} \texttt{pwd}~\textit{command}\index{\texttt{pwd}}\Hline
\texttt{pwd}
\end{bsyntax}

\begin{bsyntax} \texttt{ls} command \index{\texttt{ls}}\Hline
\texttt{ls} \textit{pathname}
\end{bsyntax}

where pathnames must be those of directories.

\begin{warning}
  The above commands act like their namesakes in Unix shells,
  but are not exactly the same.
  The arguments to \verb|cd|, \verb|ls| are not optional, but necessary.
  Also, the system does not recognise \verb|~bimbo| as the home directory of
  \verb|bimbo|.
\end{warning}

\subsection{Saving and Restoring}\label{sec:p2-save-restore}

Module definitions may be saved in an internal format, for efficient
later retrieval. The commands

\begin{bsyntax} \texttt{save} command \index{\texttt{save}}\Hline
\texttt{save} \textit{pathname}
\end{bsyntax}

\begin{bsyntax} \texttt{restore} command \index{\texttt{restore}}\Hline
\texttt{restore} \textit{pathname}
\end{bsyntax}

save/restore module definitions into/from the designated file.
Pathnames must be those of files. To adhere to the system's convention,
file names should be suffixed with ``\verb|.bin|''.  In place of
\verb|restore| command, you may also use \verb|input| command
(Section \ref{sec:p2-reading-files}).

\begin{warning}
  \kbd{save} saves the contents of prelude files (see Section
 \ref{sec:p2-init-opt})
  as well as module definitions given during the session.
  \kbd{restore} reestablishes those definitions as they are saved, and
  the effects may be different from reading the file with \kbd{input} command.
  It is safer to use \kbd{restore} command to read \kbd{save}d files.
\end{warning}

You can also save the entire image of the system, including
the state of module definitions, into a dump file, by the following
command.

\begin{bsyntax} \texttt{save-system} command \index{\texttt{save-system}}\Hline
\texttt{save-system} \textit{pathname}
\end{bsyntax}

\begin{warning}
  \kbd{save-system} dumps the image of Common Lisp, so do not abuse
  this command.
  And due to the restictions of Common Lisp systems, this command may
  not work.
\end{warning}

\subsection{Initialisations and Options}\label{sec:p2-init-opt}

Recall (Section \ref{sec:p2-startup}) that the initial system message
contained
\begin{vvtm}
\begin{ccode}
  -- loading standard prelude 
  ; Loading /mnt1/lang/cafeobj-1.4/prelude/std.bin.
\end{ccode}
\end{vvtm}
In starting up, \cafeobj~autoloads\index{autoloading} a set of modules,
called standard preludes.\index{prelude}\index{standard preludes} They
define frequently used data types
and house-keeping data (cf. Chapter \ref{sec:p2-builtin-module}).

You may initialise the system to your taste, with options and
initialisation files.\index{initialisation file}\index{\texttt{.cafeobj}}
If a file named ``\kbd{.cafeobj}'' is under your
home directory, the system reads the file as if you type
\begin{vvtm}
\begin{ccode}
  CafeOBJ> in ~/.cafeobj
\end{ccode}
\end{vvtm}
after the startup. This initialisation is useful to change default
values of modes and switches (cf. \verb|set| command, Section
\ref{sec:p2-set-command}).

Various options\index{option (for startup)} control the initial state of
the system.
\begin{itemize}
\item[\kbd{-q}] This option prohibits reading \verb|.cafeobj|.
\item[\kbd{-p}] \emph{pathname}.~~ Instead of the standard prelude
  file, which is set up during installation,
  \index{standard prelude file}
  the system reads the given pathname (which must be a file).
  The suffix convention is applicable here.
\item[\kbd{+p}] {\em pathname}. ~~The sytstem reads the given pathname
  {\em in addition to} the standard prelude file.
\item[\kbd{-l}] {\em pathname-list}. ~~In processing \kbd{input} command,
  the system searches the pathname list to locate the specified file.
  (For default search paths, see Section \ref{sec:p2-lib-system}.)
  All the pathnames must be directories, and the list must be separated
  by ``\kbd{:}''.
\item[\kbd{+l}] {\em pathname-list}. ~~Pathnames are {\em added} to
  the search directory list.
\end{itemize}
For example,
\begin{vvtm}
\begin{ccode}
  % cafeobj +p /usr/cern/particle/muon.bin
            -l /usr/cern/lib/std:/usr/cern/lib/muon:/usr/home/eva/cafe
\end{ccode}
\end{vvtm}
makes the system (1) read the standard prelude file, (2) read
\kbd{muon.bin} in addition, (3) set the search directories as given,
and (4) read the initialisation file \kbd{.cafeobj}, if it exists.

%\begin{warning}
%  Pathnames in \verb|-l|, \verb|+l| options must be absolute.
%\end{warning}

You may also make the system read files by giving them as arguments.
For example,
\begin{vvtm}
\begin{ccode}
  % cafeobj lemma1 lemma2
\end{ccode}
\end{vvtm}
has the same effects as typing
\begin{vvtm}
\begin{ccode}
  CafeOBJ> input lemma1
  ... messages from the system ...
  CafeOBJ> input lemma2
  ... messages from the system ...
\end{ccode}
\end{vvtm}
at the beginning of the session.

Note that, even though ``\kbd{-p}'' options, file name arguments and
``\kbd{.cafeobj}'' all cause the system to process definitions and
commands, their effects are slightly different. Modules defined in
prelude files, whether standard or user-supplied, are treated as
preludes. This difference reveals itself when, e.g., \kbd{reset}
command (Section \ref{sec:p2-startup}) is invoked.

Finally, if you are disinclined to remember all of the above,
just memorise the help option.
\begin{vvtm}
\begin{ccode}
  % cafeobj -help
\end{ccode}
\end{vvtm}
lists the available options.

\subsection{Batch \cafeobj} \label{sec:p2-batch}

If you do not want to pay much attention to the system,
you may run the system non-interactively.
An option \kbd{-batch} causes the system to run on the batch mode,
and the system terminates immediately. This is useful in processing
a large file. For example,
\begin{vvtm}
\begin{ccode}
  % cafeobj -batch goliath > cafe.out
\end{ccode}
\end{vvtm}
forces the system to read and process \kbd{goliath} (or \kbd{goliath.bin}
or \kbd{goliath.cafe} or \kbd{goliath.mod}) while you have an afternoon tea.

\subsection{Module Libraries} \label{sec:p2-lib-system}

As suggested in the previous section, \cafeobj~maintains a list of
search directories. Some of them are {\em standard}.
You may change the list by ``\kbd{-l}'' or ``\kbd{+l}'' options,
as explained in Section \ref{sec:p2-init-opt}. You may also change it
during the session with \verb|set| command (Section \ref{sec:p2-set-command}).
For example,
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set libpath + /usr/home/maria/cafe:/usr/home/tania/cafe
\end{ccode}
\end{vvtm}
adds the two directories to the search list, while
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set libpath /usr/home/maria/cafe:/usr/home/tania/cafe
\end{ccode}
\end{vvtm}
replaces the search list by the twosome.
Each pathname should be separated by ``\kbd{:}'', like in
``\kbd{-l}'' and ``\kbd{+l}'' options.

By default, if an apparent single file name is given as argument to
\kbd{input} command, the system searches the current directory,
then standard library directories. The standard library directories
\index{standard library}
are fixed at the time of installation. By default of defaults,
they are
\begin{vvtm}
\begin{ccode}
  /usr/local/cafeobj-1.4/lib
  /usr/local/cafeobj-1.4/exs
\end{ccode}
\end{vvtm}
which are searched {\em in this order}. If the search paths are
modified, the sytem searches (a) the current directory,
(b) the paths given by the user (from left to right), and (c) the
above default paths (in case of \kbd{+} or \kbd{+l} options).

\begin{warning}
  The current directory has a privileged status. It is always searched
  first, and cannot be suppressed by ``\kbd{-l}'' options or \kbd{set}
  command.
\end{warning}

To inspect the current search paths, type
\begin{vvtm}
\begin{ccode}
  CafeOBJ> show switch libpath
\end{ccode}
\end{vvtm}
(see Section \ref{sec:p2-show-command} for \kbd{show} command in general).

\subsection{Requiring and Providing}

If you are familiar with emacs\index{emacs}, you may fancy the
following pair of commands for configuration management.

\begin{bsyntax} \texttt{require} command \index{\texttt{require}}\Hline
\texttt{require} \textit{feature} $[$\textit{pathname}$]$
\end{bsyntax}

\begin{bsyntax} \texttt{provide} command \index{\texttt{provide}}\Hline
\texttt{provide} \textit{feature}
\end{bsyntax}

\kbd{require} requires a feature, which usually
denotes a set of module definitions. Given this command, the
system searches for a file named the feature, and read the file
if found. If a pathname is given, the system searches for a file
named the pathname instead.

\kbd{provide} discharges a feature
requirement: once \kbd{provide}d, all the subsequent
\kbd{require}ments of a feature are assumed to have been fulfilled
already.
For example, you may be
at the point of reading a file that refers to a module of
lists. Suppose your convention is to store a set of container modules
--- lists, bags, sets, and so on --- in a single file. Suppose further
that, for various
reasons, you have a couple of alternative definitions of those modules,
stored in files \kbd{container-1.cafe}, \kbd{container-2.cafe}, etc.
Then it is convenient to insert the command
\begin{vvtm}
\begin{ccode}
  provide container
\end{ccode}
\end{vvtm}
in each file, so that, once one of them read in, the system knows
that a module of lists is already supplied.

To see which features have been provided, type
\begin{vvtm}
\begin{ccode}
  CafeOBJ> show features
\end{ccode}
\end{vvtm}
(see Section \ref{sec:p2-show-command} for \kbd{show} command).
\index{\texttt{show}}

To continue the above example, provided there is a file
\kbd{container-1.mod} that
defines lists, bags, et al. and contains the \kbd{provide} command line
as above, you may get the following session.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> provide numbers

  CafeOBJ> require container container-1
  
  processing input : ./container-1.cafe
  -- defining module LIST_* done.
  -- defining module BAG_* done.
  -- defining module SET_* done.
  CafeOBJ> require container container-1

  CafeOBJ> show features
  container numbers
\end{ccode}
\end{vvtm}
The first invocation of \kbd{require} made the system read the file,
while the second invocation caused nothing.
Also, since \kbd{numbers} was
explicitly \kbd{provide}d, the system presumes the feature as given.

\section{Some Helpful Commands}\label{sec:p2-other-toplevels}

\subsection{Help Command and Top-level Commands}\label{sec:p2-help-command}

Help commands of \cafeobj~in general employ ``?'', instead of
``help'', ``aide-moi'', ``socorro'', and so on. You may remember that
the welcoming message contained the line
\begin{vvtm}
\begin{ccode}
                              Type ? for help
\end{ccode}
\end{vvtm}
saying that the topmost help command is

\begin{bsyntax} command listing command \texttt{?}(help command)\index{\texttt{?} (help command)}\Hline
\texttt{?}
\end{bsyntax}

which lists the top-level commands. They may be classified as follows.
\begin{itemize}
\item[-] Starting module declarations. \kbd{module}
 (Section \ref{sec:p2-module-decl-syntax}), \kbd{view}
 (Section \ref{sec:p2-view}), and some others introduce building
 blocks of \cafeobj~codes. They are to be explained in detail, in the rest of
 the manual.
\item[-] Checking properties of modules. \kbd{check}
 (Section \ref{sec:p2-check-command}).
\item[-] Managing systems. \verb|quit| (Section \ref{sec:p2-startup}),
 \verb|select| (Section \ref{sec:p2-current-module}),
 \verb|set| (Section \ref{sec:p2-set-command}),
 \verb|protect| (Section \ref{sec:p2-module-decl-syntax}), and others.
\item[-] Managing files. \verb|input| (Section \ref{sec:p2-reading-files}),
 \verb|save| (Section \ref{sec:p2-save-restore}), and others. They
  should be already familiar to you.
\item[-] Peeping systems. \verb|show| and \verb|describe|
 (Section \ref{sec:p2-show-command}) are at your command.
\item[-] Evaluating terms. \verb|reduce|,
 \verb|execute|, and some others. Part of
 \verb|set| command also concerns evaluation. They are all explained in
  Chapter \ref{sec:p2-term-evaluation}.
\item[-] Helping theorem proving. \verb|apply|, \verb|open|, et al. They
 shall be explained in Chapter \ref{sec:p2-theorem-proving}.
\end{itemize}

Many commands have abbreviations. We list them below (For a complete 
list of abbreviations, see Appendix \ref{sec:syntax-abbrev}).
\begin{center}
\begin{tabular}{ll||ll}
\verb|module| & \verb|mod| & \verb|module!| & \verb|mod!| \\
\verb|module*| & \verb|mod*| & \verb|quit| & \verb|q| \\
\verb|show| & \verb|sh| & \verb|describe| & \verb|desc| \\
\verb|input| & \verb|in| & \verb|reduce| & \verb|red| \\
\verb|execute| & \verb|exec| & \verb|b-reduce| & \verb\bred| \\
\end{tabular}
\end{center}

\begin{warning}
  Other abbreviations may be accepted by the system. But unless
  explicitly stated in the manual, correct behaviours are not
  guaranteed.
\end{warning}

Some of the commands takes many different kinds of arguments. It is
unlikely for you to remember all. In such cases, the system
interprets the argument ``\verb|?|'' as your desperate call. For
example,
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set ?
\end{ccode}
\end{vvtm}
prints a list of arguments acceptable to \verb|set| command, to be introduced
immediately.

\subsection{Switch-Toggling Command}\label{sec:p2-set-command}

The system maintains various kind of switches. By definition a
{\em switch}\index{switch} is two-valued (\verb|on|\index{\texttt{on}}
and \verb|off|\index{\texttt{off}}). The following command changes
the value of a switch.

\begin{bsyntax} \texttt{set} command for switches \index{\texttt{set}}\Hline
\texttt{set} \textit{switch\_name} $\{$ \texttt{on} $|$ \texttt{off} $\}$
\end{bsyntax}

As explained in Section \ref{sec:p2-help-command},
you get a list of available switches by just typing
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set ?
\end{ccode}
\end{vvtm}
and the current value of switches are listed by
\begin{vvtm}
\begin{ccode}
  CafeOBJ> show switches
\end{ccode}
\end{vvtm}
(for \verb|show|\index{\texttt{show}} command,
see Section \ref{sec:p2-show-command}).

A switch that affects the general behaviour of the system is
\verb|verbose|. After this switch is turned \verb|on|, the system suddenly
becomes talkative in responding to many commands, such as \verb|show| and
\verb|describe|.
Another such switch is \verb|quiet|. If this switch is \verb|on|,
the system does not bother you with messages other than blatant error messages.
Other switches are relevant to the specific commands of the system,
and will be explained as the need arises.

\begin{warning}
  Available switches are subject to frequent changes.
\end{warning}

Some arguments to \verb|set| command are not switches, and may range
over many values. An example is \verb|libpath|, which was appeared
in Section \ref{sec:p2-lib-system}. The general syntax might be

\begin{bsyntax} \texttt{set} command for others \index{\texttt{set}} \Hline
\texttt{set} \textit{a\_name} $[$\textit{option}$]$ \textit{value}
\end{bsyntax}

but options and values are dependent on the name, and names have no
common characteristic other than that they refer to something.
We shall explain them individually, as the occasions arise.

\subsection{Inspection Commands}\label{sec:p2-show-command}

\verb|show| command prints information on modules, system status, et al.
The acceptable arguments are many, so you are wise to remember that
\begin{vvtm}
\begin{ccode}
  CafeOBJ> show ?
\end{ccode}
\end{vvtm}
lists them all (cf. Section \ref{sec:p2-help-command}).

The general syntax is complicated. It is better understood
when divided into two. For the first half, you have

\begin{bsyntax} \texttt{show} command for module inspection\Hline
\index{\texttt{show}}
\texttt{show} $[$\textit{module\_expression}$]$
\texttt{show} $[$\texttt{all}$]$ $\{$ \texttt{sorts} $|$ \texttt{ops} $|$ \texttt{sign} $|$ \texttt{axioms} $\}$ $[$\textit{module\_expression}$]$
\texttt{show} $\{$ \texttt{vars} $|$ \texttt{params} $|$ \texttt{subs} $\}$ $[$\textit{module\_expression}$]$
\texttt{show} $\{$ \texttt{sort} \textit{sort\_name} $\}$ $|$ $\{$ \texttt{op} \textit{operator\_name} $\}$ $[$ \textit{module\_expression}$]$
\texttt{show} $\{$ \texttt{sub} \textit{number} $\}$ $|$ $\{$ \texttt{param} \textit{parameter\_name} $\}$ $|$ $\{$ $[$ \texttt{all}$]$ \texttt{rules} $\}$ 
~~~~~~~~$[$\textit{module\_expression}$]$
\texttt{show view} \textit{view\_name}
\end{bsyntax}

Do not bother to memorise all of these for now --- or ever.
We illustrate them after module building constructs are
explained (cf. Chapter \ref{sec:p2-inspect-module}). For the second half,
you have

\begin{bsyntax} \texttt{show} command for other inspection \Hline
\texttt{show tree} $|$ $\{$ \texttt{term} $[$\textit{let\_variable}$]$ $[$\texttt{tree}$]$ $\}$ $|$ $\{$ \texttt{subterm} $[$\texttt{tree}$]$ $\}$
\texttt{show $[$ let $|$ selection $|$ pending $|$ context $|$ modules $|$ views $|$}
~~~~~~~~\texttt{time $|$ limit $|$ stop $|$ features $|$ memo}
\texttt{show $[$all$]$ $\{$ rule \textit{rule\_specification} $\}$ $|$ $\{$ switches $[$\textit{switch\_name}$]$ $\}$}
\end{bsyntax}

Again, do not bother now. Most of these arguments are unrelated, and
we explain the system's response separately for each of them,
in relevant chapters.

There is a command that enables
you to look deeper into module definitions.

\begin{bsyntax} \texttt{describe} command \index{\texttt{describe}} \Hline
\texttt{describe $[$\textit{module\_expression}$]$}
\texttt{describe $[$all$]$ $\{$ sorts $|$ ops $|$ sign $|$ axioms $\}$ $[$\textit{module\_expression}$]$}
\texttt{describe $\{$ vars $|$ params $|$ subs $\}$ $[$\textit{} module\_expression $]$}
\texttt{describe $\{$ sort \textit{sort\_name} $\}$ $|$ $\{$ op \textit{operator\_name} $\}$ $[$\textit{module\_expression}$]$}
\end{bsyntax}

\begin{warning}
  In using the system, you may notice that it treats
  \verb|show| and \verb|describe| in combination. In fact
\begin{vvtm}
\begin{ccode}
  CafeOBJ> show ?
\end{ccode}
\end{vvtm}
  lets you know the syntax of \verb|describe| as well as \verb|show|.
  Try also
\begin{vvtm}
\begin{ccode}
  CafeOBJ> describe ?
\end{ccode}
\end{vvtm}
\end{warning}

\chapter{Module Declaration}\label{sec:p2-module-declaration}

The basic building blocks of \cafeobj~are modules. This chapter explains
the outermost structure of a module.

\section{Overall Structure}\label{sec:p2-module-decl-syntax}

A module without parameters\index{module} has the following syntax.
\index{\texttt{module}}

\begin{bsyntax} module without parameters \Hline
\texttt{module} \textit{module\_name} ``\texttt{\{}''
~~\textit{module\_element} $*$
``\texttt{\}}''
\end{bsyntax}

A module name\index{module name} is an arbitrary character string.
A module element\index{module element} is either
%% (1) import declaration, (2) sort declaration (with ordering),
%% (3) operator declaration, (4) record declaration,
%% (5) variable declaration, (6) equation declaration, or
%% (7) transition declaration.
(1) import declaration, (2) sort declaration (with ordering),
(3) operator declaration, (4) variable declaration, 
(5) equation declaration, or (6) transition declaration.
In the subsequent chapters, we shall introduce each of them in turn.

A general rule about module elements is that a referent must precede
in the textual order. For example, you cannot refer to a variable unless
you declared it somewhere above. Another general rule is that
a module element belongs to the module where it appears, and,
unless imported (Section \ref{sec:p2-import-decl}), it cannot be
referred to in other modules.

Different modules with the same name may be declared, but only the latest
declaration is maintained. You cannot recover previous declarations.
The system gives a warning when a previous declaration is discarded.

Some modules are vital for the system to behave correctly. Those modules
cannot be overwritten. There are other special modules, not so vital but
worth a diligent protection.
An example is a module that defines natural number
arithmetic, called \verb|NAT| (cf. Chapter \ref{sec:p2-builtin-module}).
You may remove the guard from those modules, by the command

\begin{bsyntax} \texttt{unprotect} command \index{\texttt{unprotect}} \Hline
\texttt{unprotect} \textit{module\_name}
\end{bsyntax}

For the reverse effect, you may use

\begin{bsyntax} \texttt{protect} command \index{\texttt{protect}} \Hline
\texttt{protect} \textit{module\_name}
\end{bsyntax}

which make it impossible to overwrite the given module. You may use
this command to protect your own cherished modules.
The following session illustrates the behaviour of the system.
In this session, we only use the syntax introduced so far.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> module TEST { }

  -- defining module TEST_* done.
  CafeOBJ> module TEST { }

  -- defining module TEST
  [Warning]: redefining module TEST _* done.
  CafeOBJ> protect TEST

  CafeOBJ> module TEST { }

  -- defining module TEST
  [Error]: module TEST is protected!
  CafeOBJ> unprotect TEST

  CafeOBJ> module TEST { }

  -- defining module TEST
  [Warning]: redefining module TEST _* done.
  CafeOBJ> 
\end{ccode}
\end{vvtm}
According to the syntax of module declarations, empty modules
are allowed, as was the \verb|TEST| here.
You are warned even if the unprotected \verb|TEST| is overwritten.
Once under protection, \verb|TEST| cannot be redefined. Stripped
of protection, it is subject to redefinition again.

\section{Blocks in a Module}\label{sec:p2-blocks-in-mod}

Module elements can be classified in three categories: (1) references
to other modules, (2) signature definitions\index{signature},
and (3) axioms.
It is possible to gather elements in each category into blocks.
\index{block (of declarations)}
References to other modules may be clustered by the following syntax.

\begin{bsyntax} \texttt{imports} block \index{\texttt{imports}} \Hline
\texttt{imports} ``\texttt{\{} \textit{module\_element} $*$ ``\texttt{\}}''
\end{bsyntax}

where module elements are restricted to import declarations
(Section \ref{sec:p2-import-decl}). Similarly, signature definitions
and axioms may be clustered by

\begin{bsyntax} \texttt{signature} block \index{\texttt{signature}} \Hline
\texttt{signature} ``\texttt{\{} \textit{module\_element} $*$ ``\texttt{\}}''
\end{bsyntax}

\begin{bsyntax} \texttt{axioms} block \index{\texttt{axioms}} \Hline
\texttt{axioms} ``\texttt{\{} \textit{module\_element} $*$ ``\texttt{\}}''
\end{bsyntax}

%% where module elements in a \verb|signature| block
%% are restricted to declarations of sorts,
%% operators, and records (Chapter \ref{sec:p2-signature}),
%% while those in an \verb|axioms| block are restricted
%% to declarations of variables, equations, and transitions
%% (Chapter \ref{sec:p2-axioms}).
where module elements in a \verb|signature| block
are restricted to declarations of sorts and operators (Chapter \ref{sec:p2-signature}),
while those in an \verb|axioms| block are restricted
to declarations of variables, equations, and transitions
(Chapter \ref{sec:p2-axioms}).

\verb|imports|,
\verb|signature|, and \verb|axioms| blocks may appear more than once in a
single module. \verb|signature| may be abbreviated to \verb|sig|, and
\verb|axioms| to \verb|axs|.\index{\texttt{sig}}\index{\texttt{axs}}

These block constructs are for the sake of
legibility, and have no semantic connotation. For example,
\label{exs:simple-nat}
\begin{vvtm}
\begin{ccode}
  module SIMPLE-NAT {
    signature {
      [ Zero NzNat < Nat ]
      op 0  : -> Zero
      op s : Nat -> NzNat 
      op _+_ : Nat Nat -> Nat
    }
    axioms {
      vars N N' : Nat
      eq 0 + N = N .
      eq s(N) + N' = s(N + N') .
    }  
  }
\end{ccode}
\end{vvtm}
is exactly the same module declaration as
\begin{vvtm}
\begin{ccode}
  module SIMPLE-NAT {
    [ Zero NzNat < Nat ]
    op 0  : -> Zero
    op s : Nat -> NzNat 
    op _+_ : Nat Nat -> Nat
    vars N N' : Nat
    eq 0 + N = N .
    eq N + s(N') = s(N + N') .
  }
\end{ccode}
\end{vvtm}
or minutely blocked
\begin{vvtm}
\begin{ccode}
    module SIMPLE-NAT {
    signature {
      [ Zero NzNat < Nat ]
    }
    signature {
      op 0  : -> Zero
      op s : Nat -> NzNat 
    }
    signature {
      op _+_ : Nat Nat -> Nat
    }  
    axioms {
      vars N N' : Nat
    }
    axioms {
      eq 0 + N = N .
      eq N + s(N') = s(N + N') .
    }
  }
\end{ccode}
\end{vvtm}
\begin{warning}
In inspecting modules by \verb|show| command
(Section \ref{sec:p2-show-command}),
you may notice that the system uses these block constructs,
even if you did not supply them (cf. Chapter \ref{sec:p2-inspect-module}).
\end{warning}

\section{Tight Modules, Loose Modules}\label{sec:p2-obj-th}

In \cafeobj, a module plays two different r{\^ o}les, depending on where it
appears or what it contains. In one guise, a module denotes a unique
(up to iso) model ({\em tight denotation}).\index{tight denotation}
In the other, it denotes a class of models ({\em loose denotation}).
\index{loose denotation} The latter is the case when
a module is used as parameter (see Section \ref{sec:p2-parameter});
when it defines behavioural properties (Section \ref{sec:p2-hsort-beget-axs}),
and so on. We do not go into the detail in this manual, but the distinction
is very important. You should consult \cite{cafeobj-rep} or other
technical materials at least once.

Sometimes it is necessary or convenient to restrict the r{\^ o}le of
a module. Alternative module declarations below allow you to do that.

\begin{bsyntax} module for tight denotation \Hline
\texttt{module!} \textit{module\_name} ``\texttt{\{}
~~~~\textit{module\_element} $*$
``\texttt{\}}''
\end{bsyntax}

\begin{bsyntax} module for loose denotation \Hline
\texttt{module*} \textit{module\_name} ``\texttt{\{}
~~~~\textit{module\_element} $*$
``\texttt{\}}''
\end{bsyntax}

The syntax inside is the same as declarations that start
with \verb|module|.

When a module is declared with ``\verb|module!|'', it always denotes a
unique model. When declared with ``\verb|module*|'', it always denotes a
class of models.

%\begin{warning}
%  There may be several syntactical criteria to decide which module
%  should or should not be a tight denotation or a loose denotation.
%  The current implementation is laissez-faire and
%  does not impose syntactic restrictions on ``\verb|module!|'' or
%  ``\verb|module*|''.
%\end{warning}

\section{Comment}\label{sec:p2-comment-syntax}

A comment\index{comment} of \cafeobj~is one of the followings.
\begin{itemize}
\item[a.] From ``\texttt{**}'' to the end of line (eol).\index{\texttt{**}}
\item[b.] From ``\texttt{**>}'' to the eol.\index{\texttt{**>}}
\item[c.] From ``\texttt{--}'' to the eol.\index{\texttt{--}}
\item[d.] From ``\texttt{-->}'' to the eol.\index{\texttt{-->}}
\end{itemize}
Comments may be inserted either between module declarations or
between module elements.

A comment that starts with ``\texttt{**>}'' or ``\texttt{-->}''
is displayed when it is input to the
system. This facility is useful when a file is being read, or when
you want to state the expected results of evaluations. For example,
if you are excessively uneasy about what is going on, you may prepare
a file that contains
\begin{vvtm}
\begin{ccode}
**> immediately above TEST
module TEST {
--> just entered into TEST
**> now sort declaration
[ Elt ] -- this comment should be supressed
**> sort declaration ended
--> operator declaration starts
op a : -> Elt -- this comment should be supressed
--> operator declaration ended
**> finishing TEST declarartion
}
--> finished!
\end{ccode}
\end{vvtm}
and feed the file --- call it \kbd{test} here --- to the system.
The result is as follows.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> in test

  processing input : ./test.cafe
  **> immediately above TEST
  -- defining module TEST
  -- just entered into TEST.

  ** now sort declaration..

  ** sort declaration ended.

  -- operator declaration starts..

  -- operator declaration ended.

  ** finishing TEST declarartion._* done

  --> finished!
  CafeOBJ>
\end{ccode}
\end{vvtm}
As shown above, ``\kbd{>}'' is stripped when the comment appeared within
a module declaration.

As an aside, you may have noticed a couple of
``\kbd{.}'''s in the system messages. These dots indicate that the
system is running hard. More dots mean more labour.
``\kbd{\_}'' and ``\kbd{*}'' just before ``\kbd{done}''
were also from the system.

\section{Import Declaration} \label{sec:p2-import-decl}

An import declaration\index{import declaration} is [sic] to import
declarations from another module.

\begin{bsyntax} import declaration \Hline
$\{$ \texttt{protecting $|$ extending $|$ using $|$ including} $\}$ ``('' \textit{module\_expression} ``)''
\end{bsyntax}

\verb|protecting| etc. are called {\em importation mode\/}s,
\index{importation mode} and indicate how to import the designated module.
You may abbreviate the modes to \kbd{pr}, \kbd{ex}, \kbd{inc}, and \kbd{us}
respectively.
A module expression is a designation of a module, and is explained later
(Section \ref{sec:p2-module-expression}).
For the current purpose, it is enough to know that an individual module name
is by itself a module expression.

To illustrate the meaning of import declarations, here is a contrived example.
\begin{vvtm}
\begin{ccode}
   module BARE-NAT {
     [ Nat ]
     op 0 : -> Nat
     op s : Nat -> Nat
   }

   module BARE-NAT-AGAIN {
     protecting (BARE-NAT)
   }
\end{ccode}
\end{vvtm}
The declaration of \kbd{BARE-NAT-AGAIN} is equivalent to
\begin{vvtm}
\begin{ccode}
   module BARE-NAT-AGAIN {
     [ Nat ]
      op 0 : -> Nat
      op s : Nat -> Nat 
   }
\end{ccode}
\end{vvtm}
i.e. it is a copy, a sad shadow, of \kbd{BARE-NAT}. Only the name is
changed.

To explain the precise meaning of importation modes, we have to delve into
a model-theoretic theatre, which is situated outside of this manual. So
let us offer only a cursory glance here.
The modes state to what extent the intended models of the imported modules
are preserved within those of the importing modules. Intuitively,
when \kbd{M'} is imported,
\begin{itemize}
\item[-] \texttt{protecting}\index{\texttt{protecting}} is the strongest
  commandment.
  This mode requires all the intended models of \kbd{M'} be preserved
  as they are.
\item[-] \texttt{extending}\index{\texttt{extending}} allows the models of
  \kbd{M'} to be inflated, but does not allow them to be
  collapsed.
\item[-] \texttt{including}\index{\texttt{including}} does not
  introduce any restrictions. 
\item[-] \texttt{using}\index{\texttt{using}} simlilar to
  \kbd{including}, allows total destruction.
\end{itemize}

\begin{warning}
  To prove model-theoretic properties is very hard, and the
  system does not check whether indeed these restrictions are
  observed. It is on the user to choose correct modes.
\end{warning}

As a special case, a couple of built-in modules are implicitly imported
with \kbd{protecting} mode. In particular, \kbd{BOOL}\index{\texttt{BOOL}}
is of practical importance. It defines Boolean operators. It
is imported to admit conditional axioms. You may prohibit
implicit importation by \kbd{set} command, as\index{\texttt{set}}
\index{\texttt{include} (\texttt{BOOL})}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set include BOOL off
\end{ccode}
\end{vvtm}
but be careful:
Boolean operators are indispensable to write conditional axioms
(Section \ref{sec:p2-eq-decl-cond}), and an attempt to use them
will cause errors if \kbd{BOOL} is not imported.

Import declarations define a module hierarchy. We shall probe it
later (Chapter \ref{sec:p2-module-hierarchies}).

\chapter{Signature}\label{sec:p2-signature}

A signature\index{signature}
decides what is and is not a well-formed term (see
Section \ref{sec:p2-wff-terms} for detail). A
very basic definition would tell you that it consists of sort
(name)s and operator (symbol)s paired with ranks.
A signature for \cafeobj~is more elaborate. As briefly stated
in the introductory chapter,
\begin{itemize}
\item The set of sorts may be partially ordered under inclusion, and
\item There are two distinct kinds of sorts, with different concepts of
  equivalences.
\end{itemize}
These complications are reflected in the syntactic elements
in several ways.

\section{Sort Declaration}\label{sec:p2-sort-declaration}

A sort\index{sort} is a set of classified elements, such as
a set of designers, of supermodels, and of politicians.
\cafeobj~has two kinds of sorts, hereafter called {\em visible sort\/}s
and {\em hidden sort\/}s.\index{visible sort}\index{hidden sort}
We leave it to you to decide whether the sort of politicians
is visible or hidden.

\subsection{Sort Declaration}\label{sec:p2-sort-decl-syntax}

The simplest sort declaration is as follows.

\begin{bsyntax} visible sort declaration
\index{\texttt{[},\texttt{]} (visible sort declarations)}
``\texttt{[}'' \textit{list\_of\_sort\_names} ``\texttt{]}''
\end{bsyntax}

A sort name is an arbitrary character sequence, and a list of sort names
is a list of such names separated by blanks. For example,
\begin{vvtm}
\begin{ccode}
  [ Nat ]
\end{ccode}
\end{vvtm}
declares a single visible sort \texttt{Nat}, while
\begin{vvtm}
\begin{ccode}
  [ Nat Int Rat ]
\end{ccode}
\end{vvtm}
declares visible sorts \texttt{Nat}, \texttt{Int}, and \texttt{Rat}.
By replacing ``\verb|[|'' and ``\verb|]|'' with ``\verb|*[|'' and
``\verb|]*|'' respectively, you get a hidden sort declaration.

\begin{bsyntax} hidden sort declaration \Hline
\index{\texttt{*[},\texttt{]*} (hidden sort declarations)}
``\texttt{*[}'' \textit{list\_of\_sort\_names} ``\texttt{]*}''
\end{bsyntax}

In declaring operators (Section \ref{sec:p2-op-decl}) and
axioms (Chapter \ref{sec:p2-axioms}), you have to
distinguish visible sorts and hidden sorts. They
give rise to different kinds of models, and are totally
disjoint. Syntactically, you must not use the same name for
both a visible and a hidden sort.

\begin{warning}
  The current implementation simply ignores dual declarations.
  For example, in the presence of a visible sort \kbd{S}, the
  declaration
  \begin{ccode}
    [ S ]
  \end{ccode}
  is silently ignored. But declaring diffrent type produces
  a warning message, for example
  \begin{snugshade}
  \begin{ccode}
    CafeOBJ> module M { *[ S ]* [ S ] }
    -- defining module M
    [Warning]: declaring a visible sort "S", there already be a sort
        with the same name but of differenct type (visible/hidden).
        ...ignored.._* done.
  \end{ccode}
\end{snugshade}
\end{warning}

\subsection{Subsort Declaration}

You may define a partial order over sets of sorts, which is
interpreted as set inclusion.\index{partial order (over sorts)}
Such an order is denoted with ``\verb|<|''. If \verb|A < B|,
we say \verb|A| is a {\em subsort}\index{subsort} of \verb|B|,
and \verb|B| a {\em supersort}\index{supersort}
of \verb|A|. To declare this relation, you use

\begin{bsyntax} subsort declaration \index{\texttt{<}} \Hline
``\texttt{[}'' \textit{list\_of\_sort\_names} ``\texttt{<}'' \textit{list\_of\_sort\_names} $\{$ ``\texttt{<}'' \textit{list\_of\_sort\_names} $\}$ $*$ ``\texttt{]}''
``\texttt{*[}'' \textit{list\_of\_sort\_names} ``\texttt{<}'' \textit{list\_of\_sort\_names} $\{$ ``\texttt{<}'' \textit{list\_of\_sort\_names} $\}$ $*$ ``\texttt{]*}''
\end{bsyntax}

``\verb|[|'', ``\verb|]|'' enclose visible sorts and ``\verb|*[|'',
``\verb|]*|'' hidden ones, as before.
A list of sort names is as in a sort declaration, but it can be
qualified (qualification is explained in Section
\ref{sec:p2-naming-and-qualification}). The above syntax means
that each sort in the first list is a subsort of each sort in the
second, each sort in the second is a subsort of each sort in
the third, and so on. Note that ``\verb|<|'', although looking a
strict relation, is non-strict, and means ``less than or equal to'', or
``subset of or equal to''.

For example, the usual inclusion of natural numbers \verb|Nat| into
integers \verb|Int|, and \verb|Int| into rationals \verb|Rat|, may be
written down as
\begin{vvtm}
\begin{ccode}
   [ Nat < Int < Rat ]
\end{ccode}
\end{vvtm}
or
\begin{vvtm}
\begin{ccode}
   [ Int < Rat ]
   [ Nat < Int ]
\end{ccode}
\end{vvtm}
or
\begin{vvtm}
\begin{ccode}
   [ Nat Int < Rat ]
   [ Nat < Int ]
\end{ccode}
\end{vvtm}
For a briefer description, you may put more than one declarations within
a single bracket pair, using commas for separation. For example, the last
declarations above may be abbreviated to
\begin{vvtm}
\begin{ccode}
   [ Nat Int < Rat, Nat < Int ]
\end{ccode}
\end{vvtm}
It is also possible to combine sort and subsort declarations into a
single bracket pair, as
\begin{vvtm}
\begin{ccode}
   [ Nat Int Rat, Nat < Int < Rat ]
\end{ccode}
\end{vvtm}
which is equivalent to
\begin{vvtm}
\begin{ccode}
   [ Nat Int Rat ]
   [ Nat < Int < Rat ]
\end{ccode}
\end{vvtm}
\begin{warning}
  In subsort declarations, if new sort names appear, they are
  assumed to be declared implicitly. If \texttt{Nat}, \texttt{Int} and
  \texttt{Rat} have not been declared, therefore,
  \begin{vvtm}
  \begin{ccode}
    [ Nat < Int < Rat ]
  \end{ccode}
  \end{vvtm}
  and
  \begin{vvtm}
  \begin{ccode}
    [ Nat Int Rat,  Nat < Int < Rat ]
  \end{ccode}
  \end{vvtm}
  are interpreted identically. Beware, especially, of mistyping
  upper/lower cases. For example, if you imported a sort
  \verb|Nat| and declared
  \begin{vvtm}
  \begin{ccode}
    [ NAT < Int ]
  \end{ccode}
  \end{vvtm}
  \verb|NAT| is regarded as a newly declared sort, not an imported
  one.
\end{warning}

It is abnormal for subsort relation to be circular, and if they were
circular, you should not expect the system to behave correctly.
Subsort relation is set inclusion, so circular relation
means that all the sorts involved are the same. But \cafeobj~does not
recomment such indirect ``renaming'', and may refuse to
support this interpretation.

% \begin{warning}
% In general, checks on circularity are hard to implement efficiently, so
% the system only checks obvious cases. If circularity is detected, you
% are severely warned.
% \end{warning}

Note that it is impossible to make a visible sort a subsort of
a hidden sort, or vice versa. You cannot put a hidden sort in
plain brackets, nor a visible sort in asterisked brackets.
This impossibility reflects the fact
that visible sorts are disjoint from hidden sorts.

\section{Operator Declaration}\label{sec:p2-operator}

In traditional algebraic specification languages, an operator\index{operator}
is a function, i.e. an unambiguous, static mapping.
\cafeobj~extends the concept in two directions.
An operator may {\em transform} an element into another.
Such an operator is defined by transition relations
(Section \ref{sec:p2-trans-decl}). Moreover, an operator
may change an {\em internal state} of an element. Such an
operator is defined from an observational viewpoint.

\subsection{Operator Declaration}\label{sec:p2-op-decl}

Like the other strongly-typed languages, \cafeobj~requires you to make
explicit the domains and
codomains of operators, and only allows terms constructed accordingly.
Since \cafeobj~is order-sorted, however, well-formedness involves
subtle considerations (see Section \ref{sec:p2-wff-terms}).

In addition to domains and codomains, operator declarations determine
term constructs.
\cafeobj~allows you to employ various notations in writing terms,
such as infix (e.g. $2 + 4$), prefix ($- 4$), and postfix ($2!$).
Hence in declaring operators, you have a way to adopt your favourite
notational practice. If you do not show any preference, you get
a standard notation for function application.
For example, given a (ternary) operator \verb|f|,
a term thereof is constructed out of parenthesised, comma separated
arguments, such as \verb|f(a,b,c)|.
A declaration for such an operator is called {\em standard}.

\begin{bsyntax} standard operator declaration \index{\texttt{op}} \Hline
\index{standard operator declaration}
\texttt{op} \textit{standard\_operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names} ``\texttt{->}'' \textit{sort\_name}
\end{bsyntax}

A standard operator symbol is an arbitrary character string that
does not contain an underbar ``\verb|_|''. A list of
sort names is a blank-separated list and designates the arity\index{arity}
of the operator. The sort name after ``\verb|->|'' designates its
coarity\index{coarity}.
Sort names in arities and coarities may be qualified
(cf. Section \ref{sec:p2-naming-and-qualification}).
The pair of the arity and the coarity is called the rank\index{rank}
of the operator. An operator with the empty arity is a
constant\index{constant}.

\begin{warning}
  It is possible for a standard operator symbol to contain blanks. For
  example, in
  \begin{vvtm}
  \begin{ccode}
    op a constant of sort S : -> S
  \end{ccode}
  \end{vvtm}
  the whole ``\verb|a constant of sort S|'' is a symbol. More precisely,
  the system treats the symbol as a blank-separated list of non-blank
  character strings, and arbitrary numbers of blanks may be inserted.

  But parsing terms that contain such symbols tends to be erroneous, and
  you often have to enclose the symbol with parentheses. For this reason,
  it is advisable not to use blanks, unless your aesthetics so forces.
\end{warning}

If not standard, a declaration is called {\em mixfix}.

\begin{bsyntax} mixfix operator declaration \Hline
\index{mixfix operator declaration}
\texttt{op} \textit{mixfix\_operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names} ``\texttt{->}'' \textit{sort\_name}
\end{bsyntax}

A mixfix operator symbol may contain underbars. Arities and coarities
are the same as in standard operator declarations. In fact,
the only difference from standard declarations is the presence of
underbars. Underbars reserve the places where arguments are inserted.
The leftmost underbar is for the first argument, the next leftmost the
second, and so on. The number of underbars must match the number
of sort names in the arity.

\begin{warning}
  The single underbar cannot be an operator symbol; it would introduce
  invisible operator applications. Such a declaration is
  ignored, and you are ridiculed by the system.
\end{warning}

For example, addition is usually written in the infix notation. Declare
\begin{vvtm}
\begin{ccode}
  op _+_ : Nat Nat -> Nat
\end{ccode}
\end{vvtm}
and terms such as ``\texttt{N + M}'', ``\texttt{s(0) + N}'' are admissible.
Another representative example is a conditional expression.
\begin{vvtm}
\begin{ccode}
  op if_then_else_fi : Bool Nat Nat -> Nat
\end{ccode}
\end{vvtm}
According to the definition, this declaration allows you to write
\begin{vvtm}
\begin{ccode}
  if N < M then N else M fi
\end{ccode}
\end{vvtm}
and
\begin{vvtm}
\begin{ccode}
  if true then 0 else s(0) fi
\end{ccode}
\end{vvtm}
Since \cafeobj~allows operator overloading, it is
possible to use the same operator symbol for different operators.
For example, the symbol \verb|_+_| may be overloaded as follows.
\begin{vvtm}
\begin{ccode}
  op _+_ : Nat Nat -> Nat
  op _+_ : Set Set -> Set
\end{ccode}
\end{vvtm}
An operator symbol, whether standard or mixfix, does not only define
term constructs, but acts as an operator name. What an operator name
refers to is a nontrivial question, due to overloading possibilities
(see Section \ref{sec:p2-operator-reference} for detail).

You can declare several operators simultaneously, if they have exactly
the same rank:
use \verb|ops| instead of \verb|op|, as\index{\texttt{ops}}
\begin{vvtm}
\begin{ccode}
  ops (_+_) (_*_) : Nat Nat -> Nat
\end{ccode}
\end{vvtm}
which means the same as
\begin{vvtm}
\begin{ccode}
  op _+_ : Nat Nat -> Nat
  op _*_ : Nat Nat -> Nat
\end{ccode}
\end{vvtm}
Note that, in simultaneous declarations, parentheses are sometimes necessary
to separate operator symbols.

\begin{warning}
  A general advice: if you are in doubt, enclose with parentheses.
  Parentheses help you avoid many parsing ambiguities.
\end{warning}

\subsection{Behavioural Operator Declaration}\label{sec:p2-beh-op-decl}

For hidden sorts, you need a special kind of operators, called
{\em behavioural operator\/}s.\index{behavioural operator}

\begin{bsyntax} behavioural operator declaration \index{\texttt{bop}} \Hline
\texttt{bop} \textit{standard\_operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names} ``\texttt{->}'' \textit{sort\_name}
\texttt{bop} \textit{mixfix\_operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names} ``\texttt{->}'' \textit{sort\_name}
\end{bsyntax}

Standard operator symbols, mixfix operator symbols, lists of sort names
and sort names are as in \verb|op| in the previous section.
It is required that
\begin{itemize}
\item The arity of a behavioural operator contain exactly one
  hidden sort.
\end{itemize}
Intuitively, you may regard a hidden sort as consisting of objects, which
have internal states. Then a behavioural operator
is an {\em attribute}\index{attribute} or a {\em method}\index{method},
if you really, really want to adopt the parlance of a certain community.
As an illustration,
consider bank account objects, whose balances change upon deposits and
withdrawals.
\begin{vvtm}
\begin{ccode}
  *[ Account ]*
  bop deposit : Account Nat -> Account
  bop withdraw : Account Nat -> Account
  bop balance : Account -> Nat
\end{ccode}
\end{vvtm}
Here \verb|deposit|, \verb|withdraw| are operations that modify
internal states --- balances --- of accounts (so they are methods),
while \verb|balance| reads the current balances of accounts
(so an attribute).

The above intuition tells you why a behavioural operator should have
exactly one hidden sort in its arity. It does not make sense to
retrieve attributes from two objects. And it is nonsense to talk about
attributes of nothing. Technically, behavioural operators, and only them,
make behavioural contexts (see Section \ref{sec:p2-hsort-beget-axs}).

There is a counterpart to \verb|ops|, with which you may
declare several behavioural operators at once.
Two of the above declarations may be
replaced by\index{\texttt{bops}}
\begin{vvtm}
\begin{ccode}
  bops deposit withdraw : Account Nat -> Account
\end{ccode}
\end{vvtm}
Note that an operator symbol may be overloaded among behavioural operators,
and/or among the mixture of usual and behavioural operators. Note
further that a non-behavioural operator declaration with
\verb|op| is {\em not} required to contain or not to contain
hidden sorts. You may declare non-behavioural operators on hidden sorts, as
\begin{vvtm}
\begin{ccode}
  op deposit : Account Nat -> Account
\end{ccode}
\end{vvtm}
The effects are, however, very different. Do take care.

\subsection{Predicate Declaration}\label{sec:p2-pred-decl}

A {\em predicate}\index{predicate}, in \cafeobj, is nothing more
than an operator which has a special sort \verb|Bool| as its coarity.
This sort is contained in the module \verb|BOOL|, which is imported
everywhere (Section \ref{sec:p2-import-decl}).
\verb|Bool| is important in several respects, and is accorded a privilege
by the following shorthand constructs.

\begin{bsyntax} predicate declaration \index{\texttt{pred}} \Hline
\texttt{pred} \textit{standard\_operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names}
\texttt{pred} \textit{mixfix\_operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names}
\end{bsyntax}

Operator symbols etc. are as in operator declarations. Predicate
declarations are equivalent to operator declarations with
coarity \verb|Bool|. For example,
\begin{vvtm}
\begin{ccode}
  pred _<_ : Nat Nat
\end{ccode}
\end{vvtm}
has the same meaning as
\begin{vvtm}
\begin{ccode}
  op _<_ : Nat Nat -> Bool
\end{ccode}
\end{vvtm}
\begin{warning}
  The system does not distinguish predicates as such.
  You should think of them as mere shorthands. Nothing more.
\end{warning}

To complete the picture,
\verb|bpred| is a shorthand of \verb|bop| with coarity \verb|Bool|.

\begin{bsyntax} behavioural predicate declaration \index{\texttt{bpred}} \Hline
\texttt{bpred} \textit{standard\_operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names}
\texttt{bpred} \textit{mixfix\_operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names}
\end{bsyntax}

\section{Terms}\label{sec:p2-terms}

\subsection{Well-formed Terms}\label{sec:p2-wff-terms}

As well as adopting arbitrary notational practices, you may
use the same notation to denote different operators, such as
$1 + 2$ for addition and $\{ a \} + \{ a, b \}$ for
direct sum. These flexibilities greatly enhance the
legibility of \cafeobj~codes, and we believe it worthwhile to support
them.

One disadvantage of this liberty is the extra amount of processing time
in parsing terms. Another, and more important, problem is that a term may
be parsed in more than one ways. We make recourse to the following
definition.
\begin{quote}
A term is {\em well-formed}\index{well-formed term} iff it has
exactly one least parse tree.
\end{quote}
Several parse trees are okay, so long as all of them are of
related sorts, and one of them has a {\em least sort}.\index{least sort}
The least sort is the smallest set to which the element belongs.
Dual membership is a seed of troubles, just as dual marriage is.

A signature is {\em regular}\index{regular signature} iff all the
terms have least sorts, and a module is regular iff its signature is.
With the above observations in mind, you understand
this is an important property.
\cafeobj~has a mechanism to regularise signatures. To invoke this
mechanism, you may use

\begin{bsyntax} \texttt{regularize} command \index{\texttt{regularize}} \Hline
\texttt{regularize} \textit{module\_name}
\end{bsyntax}

or set a switch for automatic invocation to \verb|on| by\index{\texttt{set}}
\index{\texttt{signature}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set regularize signature on
\end{ccode}
\end{vvtm}
\index{\texttt{signature}}
The default is \verb|off|. To regularise a signature, additional sorts and
operator declarations may be declared. These addidions ensure the existence
of ``lowest'' operators. For a trivial example, in
\begin{vvtm}
\begin{ccode}
  module INTB {
    [ NonPos Nat < Int ]
    op 0 : -> NonPos
    op 0 : -> Nat
  }
\end{ccode}
\end{vvtm}
\label{exs:intb}
the constant \verb|0| belongs both to \verb|NonPos| and to \verb|Nat|.
In general it is possible to overload constants, there is a way to
distinguish them (see Section \ref{sec:p2-parsing-qualifier}), and
there is no harm in that. But in this example, since \verb|NonPos|
and \verb|Nat| are both subsorts of \verb|Int|, the constant must
in fact denote the same element. As a consequence, the term \verb|0|
does not have a least parse (even qualified,
as in Section \ref{sec:p2-parsing-qualifier}).
A remedy is to add a common subsort of \verb|NonPos| and \verb|Nat|,
and declare \verb|0| of that sort.
Using \verb|regularize| command, you do get a module modified along
this line:
\begin{vvtm}
\begin{ccode}
  module INTB {
    [ NonPos^Nat < NonPos Nat < Int ]
    op 0 : -> NonPos
    op 0 : -> Nat
    op 0 : -> NonPos^Nat
  }
\end{ccode}
\end{vvtm}
Two old declarations of \verb|0| are redundant by now, but system 
does not remove these \verb|0|s in automatic.

% \begin{warning}
%   The current version does not remove redundant \verb|0|'s.
% \end{warning}

More generally, the system searches for operators that may create
terms with no least parse, and declare such operators on least sorts
after, if necessary, adding new common subsorts. What the system
checks is a sufficient, but {\em not} necessary, condition. There are
cases the system is overprotective. As an example, consider
\begin{vvtm}
\begin{ccode}
  module INTB' {
    [ NonPos Nat < Int ]
    op _+_ : NonPos NonPos -> NonPos
    op _+_ : Nat Nat -> Nat
    op _+_ : Int Int -> Int
    op 1 : -> Nat
    op -1 : -> NonPos
  }
\end{ccode}
\end{vvtm}
\label{exs:intb'}
\verb|INTB'| is regular: a term is of the form of a binary tree where
all the nodes contain \verb|+| and all the leaves contain \verb|1| or
\verb|-1|, and is of sort \verb|NonPos| iff every leaf is \verb|-1|,
of sort \verb|Nat| iff every leaf is \verb|1|, and of sort \verb|Int|
iff otherwise. If you invoke \verb|regularize| command, however, you get
a modified module:
\begin{vvtm}
\begin{ccode}
  module INTB' {
    [ NonPos^Nat < NonPos Nat < Int ]
    op _+_ : NonPos^Nat NonPos^Nat -> NonPos^Nat
    op _+_ : NonPos NonPos -> NonPos
    op _+_ : Nat Nat -> Nat
    op _+_ : Int Int -> Int
    op 1 : -> Nat
    op -1 : -> NonPos
  }
\end{ccode}
\end{vvtm}
The reason is as follows. If \verb|Nat|, \verb|NonPos| are both
inhabited, there is a danger that their intersection is not
empty. If it is indeed non-empty,
an application of ``\verb|_+_|'' on any terms in it
creates a term both of sort
\verb|Nat| and of \verb|NonPos|. So it is safe to add a new common
subsort, and declare ``\verb|_+_|'' on it.

To check the non-emptiness is too hard to solve mechanically.
For example, if you insert an equation (Section \ref{sec:p2-equation-decl})
\begin{vvtm}
\begin{ccode}
  eq 1 = -1 .
\end{ccode}
\end{vvtm}
into \verb|INTB'|, there does exist an element, namely \verb|1|
(or \verb|-1|), which belongs to both \verb|NonPos| and \verb|Nat|.
Thus a general solution requires a complete equational calculus,
which is beyond the power of \cafeobj. It is for this reason that
the system always bets on the safer side, even if the results are dull:
the system (and you) will not lose a penny, since the modified
module has exactly the same model(s) as before (when you take reducts).

If one of \verb|NonPos| or \verb|Nat| were empty, the system would have done
nothing. For example, if you delete the declaration
\begin{vvtm}
\begin{ccode}
  op 1 : -> Nat
\end{ccode}
\end{vvtm}
from \verb|INTB'|, \verb|Nat| is not inhabited any more: the system
adds nothing this time.

For those who only want to be warned
of the danger, it is also possible just to check if the signature is regular
(cf. Section \ref{sec:p2-check-command}).

\subsection{Parsing Terms}\label{sec:p2-parsing-qualifier}

As suggested above, a symbol sequence may be parsed in more than one ways.
A salient example is a constant symbol. With the two declarations below,
\verb|empty| is a term both of \verb|Stack| and \verb|Set|.
\begin{vvtm}
\begin{ccode}
  op empty : -> Stack
  op empty : -> Set
\end{ccode}
\end{vvtm}
In such cases, you have to supply additional information by qualification.
Other ambiguities may be eliminated by parentheses. Let us see a couple of
examples.

To see whether a term is unambiguous, the following command is handy.

\begin{bsyntax} parsing command \index{\texttt{parse}} \Hline
\index{\texttt{.} (term stopper)}
\texttt{parse} $[$\texttt{in} \textit{module\_expression} ``\texttt{:}''$]$ \textit{term} ``\texttt{.}''
\end{bsyntax}

If \verb|in| option is omitted, the current module\index{current module}
(cf. Section \ref{sec:p2-current-module}) is assumed. Module expressions
are explained in Section \ref{sec:p2-module-expression}. It is enough
here to know that a module name is a module expression.

\begin{warning}
  Do not forget the last period, preceded by a blank. This is the only
  way for the system to detect the end of a term: usual parsing techniques
  would not do, due to flexible term constructs. The same convention is
  used in other commands and declarations.
\end{warning}

To see how this command works, here is an example where an ambigouous term
is parsed.
\label{exs:simple-int}
\begin{vvtm}
\begin{ccode}
  module SIMPLE-INT {
    protecting (SIMPLE-NAT)
    [ Nat NegInt < Int ]
    op -_ : NzNat -> NegInt
    op _+_ : Int Int -> Int
    op _-_ : Int Int -> Int
    op s : Int -> Int
    vars M M' : Int
  }
\end{ccode}
\end{vvtm}
The above module gives a signature for integer operations
(\verb|SIMPLE-NAT| was in Section \ref{exs:simple-nat}).
\verb|vars| declares
variables (Section \ref{sec:p2-variable-decl}). After declaring
the above module, you may get a session like
%\newpage
\begin{vvtm}
\begin{ccode}
  CafeOBJ> parse in SIMPLE-INT : M - M' - s(0) .
  [Warning]: Ambiguous term:
      please try `check regularity' command.
      if the signature is regular, there possibly be 
      some name conflicts between operators and variables.
  [1] _-_ : Int Int -> Int ------------------------((M:Int - M':Int) - s(0))
  [2] _-_ : Int Int -> Int ------------------------(M:Int - (M':Int - s(0)))
  [Error] no successful parse
    ("ambiguous term"):SyntaxErr
\end{ccode}
\end{vvtm}
If you \kbd{set} a switch \kbd{verbose} to \kbd{on}, 
you see a more visible tree structure of possible parses like
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set verbose on
  CafeOBJ> parse in SIMPLE-INT : M - M' - s(0) .

  [Warning]: Ambiguous term:* Please select a term from the followings:
  [1] _-_ : Int Int -> Int --------------------------------------------
            _-_:Int        
        /             \     
     _-_:Int       s:NzNat
    /       \         |     
  M:Int  M':Int    0:Zero  
                          
  [2] _-_ : Int Int -> Int --------------------------------------------
       _-_:Int             
    /            \          
  M:Int       _-_:Int      
            /         \     
         M':Int    s:NzNat
                      |     
                   0:Zero  

  [Error] no successful parse
    ("ambiguous term"):SyntaxErr

  CafeOBJ> 
\end{ccode}
\end{vvtm}
If the term is ambiguous, as in this example, the system gives a
warning, as showed in the above.
And if you \kbd{set} switch \kbd{select term} to \kbd{on}, 
you have an option to select a parse from possible choces.
\begin{vvtm}
\begin{ccode}
CafeOBJ> set verbose off
CafeOBJ> set select term on
CafeOBJ> parse in SIMPLE-INT : M - M' - s(0) .
[Warning]: Ambiguous term:
    please try `check regularity' command.
    if the signature is regular, there possibly be 
    some name conflicts between operators and variables.
* Please select a term from the followings:
[1] _-_ : Int Int -> Int ------------------------((M:Int - M':Int) - s(0))
[2] _-_ : Int Int -> Int ------------------------(M:Int - (M':Int - s(0)))
* Please input your choice (a number from 1 to 2, default is 1)? 2
Taking the second as correct.
(M - (M' - s(0))):Int
CafeOBJ> 
\end{ccode}
\end{vvtm}
The number after the message ``\verb|*| \verb|Please ...|'' is
your input.

\begin{warning}
  The system is impatient. If you hesitate long, it automatically
  selects the default (in the above case, \verb|1|).
\end{warning}

The result of the parsing was
\begin{vvtm}
\begin{ccode}
  (M - (M' - s(0))) : Int
\end{ccode}
\end{vvtm}
where the term is parenthesised to reveal connectivity.
\verb|Int| on the right of ``\verb|:|'' is its least sort.

\subsection{Qualifying Terms}\label{sec:p2-qualifying-terms}

Ambiguity that arises from operator connectivity, e.g.
\begin{vvtm}
\begin{ccode}
  M - M' - s(0)
\end{ccode}
\end{vvtm}
above, can be eliminated by parentheses. On the other hand, ambiguity caused
by overloading cannot be so easily eliminated. It requires additional
sort information. Hence term qualification\index{term qualification}, as
\index{qualified term}

\begin{bsyntax} sort-qualified term \Hline
``\texttt{(}'' \textit{term} ``\texttt{)}'' ``\texttt{:}'' \textit{sort\_name}
\end{bsyntax}

\begin{warning}
  This version, unlike former versions, allows blanks around ``\texttt{:}''.
  The following terms are all valid and parsed as the same.
  \begin{vvtm}
  \begin{ccode}
    (empty):Stack
    (empty): Stack
    (empty) :Stack
    (empty) : Stack
  \end{ccode}
  \end{vvtm}
\end{warning}

\begin{warning}
  Be sure to put parentheses around the qualified. \cafeobj~allows
  inline variable declarations, such as
  \begin{vvtm}
  \begin{ccode}
    M:Nat - s(0)
  \end{ccode}
  \end{vvtm}
  where \verb|M| is regarded (at this place only) as a variable of
  sort \verb|Nat|. Without parentheses, e.g.
  \begin{vvtm}
  \begin{ccode}
    empty:Stack
  \end{ccode}
  \end{vvtm}
  is regarded as a new variable!
\end{warning}

For example, consider the following module declarations.
\begin{vvtm}
\begin{ccode}
  module OCTAL {
    [ OctalDigit ]
    ops 0 1 2 3 4 5 6 7 : -> OctalDigit
  }

  module HEX {
    [ HexDigit ]
    ops 0 1 2 3 4 5 6 7 8 9 : -> HexDigit
    ops A B C D E F : -> HexDigit
  }

  module HEX+OCTAL {
    protecting (OCTAL)
    protecting (HEX)
  }
\end{ccode}
\end{vvtm}
Since \verb|HEX+OCTAL| contains declarations either in \verb|OCTAL| or in
\verb|HEX|, the digits \verb|0| through \verb|7| are ambiguous there:
they are constants both of \verb|OctalDigit| and \verb|HexDigit|.
Indeed, try parsing \verb|0| and you get a warning.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> parse in HEX+OCTAL : 0 .
  [Warning]: Ambiguous term:
      please try `check regularity' command.
      if the signature is regular, there possibly be 
      some name conflicts between operators and variables.
  [1] 0 :  -> HexDigit --------------------------------0
  [2] 0 :  -> OctalDigit ----------------------------0
  [Error] no successful parse
    ("ambiguous term"):SyntaxErr
  CafeOBJ> 
\end{ccode}
\end{vvtm}
To eliminate this ambiguity, you may qualify by sorts. Try again with
\begin{vvtm}
\begin{ccode}
  CafeOBJ> parse in HEX+OCTAL : (0):OctalDigit .
\end{ccode}
\end{vvtm}
and the system will oblige with
\begin{vvtm}
\begin{ccode}
  0 : OctalDigit
\end{ccode}
\end{vvtm}

%% \section{Record Declaration}\label{sec:p2-record-declaration}

%% A {\em record} declaration\index{record declaration} defines a record-type
%% data structure. A record type consists of fields, and an element of the
%% type is completely determined by the value of each field.
%% In \cafeobj, a field is called {\em slot}\index{slot}.

%% \subsection{Plain Record Declaration}\label{sec:p2-plain-record-decl}

%% A record declaration without inheritance (see the next section) is as
%% follows.

%% \begin{bsyntax} plain record declaration \index{\texttt{record}} \Hline
%% \texttt{record} \textit{record\_name} ``\texttt{\{}'' \textit{list\_of\_slot\_declarations} ``\texttt{\}}''
%% \end{bsyntax}

%% where a list of slot declarations is a blank-separated list.
%% A slot declaration has the following construct.

%% \begin{bsyntax} slot declaration \Hline
%% \textit{slot\_name} ``\texttt{:}'' \textit{sort\_name}
%% \end{bsyntax}

%% where a slot name is a character string and a sort name is
%% the name of an already declared sort. For example, if \verb|Nat|
%% is a sort of natural numbers with usual digit notations,
%% \begin{vvtm}
%% \begin{ccode}
%%   record Date {
%%     year  : Nat
%%     month : Nat
%%     day   : Nat
%%   }
%% \end{ccode}
%% \end{vvtm}
%% is a sloppy definition of records that consist of years, months, and days.
%% (Sloppy because it admits e.g. 554/32/1984 as a date.)

%% In ordinary programming languages, once a record is declared,
%% notation/functions to access fields are automatically determined.
%% The dotted notation \verb|d.day|, where \verb|d| is a record variable
%% and \verb|day| is a field name, is typical.
%% \cafeobj~also provides access functions. In fact, a record is nothing more
%% than a special sort. The effects of a record declaration are as follows.
%% \begin{itemize}
%% \item A sort with the record name is declared. A record is a sort,
%%   so the name can appear wherever a sort name can.
%% \item A mixfix operator is declared, so that a term of the form
%%   \begin{vvtm}
%% \begin{ccode}
%%      record-name { slot-name1 = value1, slot-name2 = value2, ... }
%%   \end{ccode}
%% \end{vvtm}
%%   is an element of \verb|record-name|.
%%   Using the above example,
%%   \begin{vvtm}
%% \begin{ccode}
%%      Date { year = 1984, month = 1, day = 1 }
%%   \end{ccode}
%% \end{vvtm}
%%   is a term of sort \verb|Date|. Moreover, the slot-value pairs
%%   in the braces may be written in whatever order, and you may even
%%   omit some of them. Thus
%%   \begin{vvtm}
%% \begin{ccode}
%%      Date { month = 1, day = 1, year = 1984 }
%%      Date { year = 1984 }
%%   \end{ccode}
%% \end{vvtm}
%%   are well-formed terms of sort \verb|Date|. Note that \verb|Date| in
%%   these terms is part of an operator symbol, not the sort name
%%   which happens to be the same character string.
%% \item For each slot, two access functions are declared and defined.
%%   In case of \verb|Date|, it is as if the declarations
%%   \begin{vvtm}
%% \begin{ccode}
%%      op year : Date -> Nat
%%      op set-year : Date Nat -> Date
%%      -- similarly for month and day
%%   \end{ccode}
%% \end{vvtm}
%%   are given. Accordingly, to get the value of \verb|year| slot
%%   from a term \verb|d| of sort \verb|Date|, you can write \verb|year(d)|;
%%   and to set the slot to \verb|y|, write \verb|set-year(d,y)|.
%% \end{itemize}
%% Strictly speaking, since the definitions of access functions are by
%% axioms (axioms are to be explained in Chapter \ref{sec:p2-axioms}), a
%% record declaration involve axioms as well as signatures.
%% You may investigate all the above effects by \verb|show| command
%% (cf. Section \ref{sec:p2-record-inspection}).

%% \subsection{Inheriting Records}\label{sec:p2-record-inheritance}

%% You can extend a record to create a new record.
%% The same access functions can be used as before.
%% The process of extending a record is called
%% {\em record inheritance}\index{record inheritance},
%% {\` a} la peculiar parlance of some community, and
%% is denoted by the following construct.

%% \begin{bsyntax} record declaration with inheritance \index{\texttt{record}} \Hline
%% \texttt{record} \textit{record\_name} ``\texttt{[}'' \textit{list\_of\_upper\_records} ``\texttt{]}'' ``\texttt{\{}'' \textit{list\_of\_slot\_declarations} ``\texttt{\}}''
%% \end{bsyntax}

%% A list of slot declarations is as in a plain record declaration.
%% A list of upper records is comma-separated. An upper record is of
%% the form

%% \begin{bsyntax} upper record \Hline
%% \textit{record\_name} $[$``\texttt{*}'' ``\texttt{(}'' \textit{slot\_mapping} ``\texttt{)}''$]$
%% \end{bsyntax}

%% where a slot mapping is

%% \begin{bsyntax} slot mapping \Hline
%% \textit{slot\_name} ``\texttt{->}'' \textit{slot\_name} $\{$ ``\texttt{,}'' \textit{slot\_name} ``\texttt{->}'' \textit{slot\_name} $\}$ $*$
%% \end{bsyntax}

%% where slot names before ``\verb|->|'' must be the ones belonging to the
%% given record, while names after ``\verb|->|'' are arbitrary (so long as
%% not conflicting).

%% Under a record declaration with inheritance,
%% the newly declared record inherits all the slots from
%% the upper records. Slot mappings, which specify renaming,
%% are to be used to avoid name conflicts.
%% \cafeobj~does not allow slots of the same name to be inherited
%% twice. If there is no conflict, slot mappings may be omitted.

%% An %boring 
%% example of inheritance, using \verb|Date| of the previous
%% section, is
%% \begin{vvtm}
%% \begin{ccode}
%%    record Time [ Date ] {
%%      hour   : Nat
%%      minute : Nat
%%    }
%% \end{ccode}
%% \end{vvtm}
%% This code declares \verb|Time| to have slots \verb|year|, \verb|month|,
%% and \verb|day|, as well as \verb|hour| and \verb|minute|.
%% Access functions \verb|year|, \verb|set-year|, and so on are
%% applicable to terms of \verb|Time| exactly as they are
%% to those of \verb|Date|.
%% The effects of the declaration are equivalent to
%% \begin{vvtm}
%% \begin{ccode}
%%    record Time {
%%      year   : Nat
%%      month  : Nat
%%      day    : Nat
%%      hour   : Nat
%%      minute : Nat
%%    }
%% \end{ccode}
%% \end{vvtm}
%% Here is another example, which needs slot renaming.
%% \begin{vvtm}
%% \begin{ccode}
%%    record Week {
%%      day : Nat
%%    }
%%    record Time'
%%     [ Date * ( day -> day-of-the-month ), Week * ( day -> day-of-the-week ) ]
%%    {
%%       hour   : Nat
%%       minute : Nat
%%    }
%% \end{ccode}
%% \end{vvtm}
%% Since \verb|day| was the slot name of both \verb|Date| and \verb|Week|,
%% each slot was accorded a more accurate, distinct name.

\chapter{Axioms}\label{sec:p2-axioms}

\cafeobj~inherits the essences of algebraic specification techniques,
where axioms are given as equations. Several extensions, however,
lead to the following complications. (1) Equations may be conditional.
(2) Not only equations, but transitions are available.
(3) Visible sorts and hidden sorts demand different kinds of equivalences,
so that, as well as ordinary equations, behavioural equations are
available. All of these extensions are orthogonal, as witnessed by
$8 = 2^3$ syntatical constructs.

\section{Variable Declaration}\label{sec:p2-variable-decl}

Axioms require representations of classes of elements, as well as
specific elements. You have to be able to say, e.g., that
the successor of {\em any} natural number is greater than that number.
A {\em variable}\index{variable} represents this ``any''.
In \cafeobj, every variable belongs to a sort, and represents an arbitrary
term of that sort.
Variables are declared as follows.

\begin{bsyntax} variable declaration \index{\texttt{var}}\index{\texttt{vars}} \Hline
\texttt{var} \textit{ariable\_name} ``\texttt{:}'' \textit{sort\_name}
\texttt{vars} \textit{list\_of\_variable\_names} ``\texttt{:}'' \textit{sort\_name}
\end{bsyntax}

A variable name is a character string, and a list of variable names
is blank-separated. Here is an example.
\begin{vvtm}
\begin{ccode}
  var N : Nat 
  vars A B C : Nat
\end{ccode}
\end{vvtm}
\begin{warning}
  In former versions, \verb|var| and \verb|vars| are interchangeable.
  This version becomes linguistically more strict.
  \verb|var| is for exactly one variable, while \verb|vars| is for
  one or more variables.
\end{warning}

\begin{warning}
  In former versions, commas could be used as separators, so that the
  above  declaration may be replaced with
  \begin{vvtm}
\begin{ccode}
    vars A, B, C : Nat
  \end{ccode}
\end{vvtm}
  But this construct no longer works: the system would regard \verb|,| as
  another variable.
\end{warning}

A simple way to know the typing discipline of a language is to see
variable declarations. \cafeobj~adopts a {\em strong typing}
\index{strong typing} discipline,
in that each variable has a syntactically determined type (sort). Another
point of view comes from the definition of well-formedness. A term
is well-formed iff it has a unique least parse
(Section \ref{sec:p2-wff-terms}). A variable is a term.
Hence it must have a unique least sort, the sort given in the
declaration.

The scope of a variable is within the module where it is declared, or
more precisely, in the rest of the module after the declaration.
For example,
\begin{vvtm}
\begin{ccode}
  module M {
    [ S ]
    op f : S -> S
    -- axioms using X -- a.
    var X : S
    -- axioms using X -- b.
  }
\end{ccode}
\end{vvtm}
would be an error, if you put axioms in \verb|a.| involving \verb|X|.
The correct place for such axioms is \verb|b.|

It is illegal to declare a variable of the same name for different sorts.
(And it is meaningless to re-declare the variable for the same sort.)
Sometimes it is 
% b.c.b.g.\footnote{
% Bon chic, bon genre.
% } 
convenient 
to use common variable names, such as
\verb|X|, for different sorts. And sometimes it is economical to
use an ephemeral variable, valid only to the place where it appears.
For these reasons, another construct for variable declaration is available.

\begin{bsyntax} variable declaration on the fly \Hline
\textit{variable\_name}``\texttt{:}''\textit{sort\_name}
\end{bsyntax}

\begin{warning}
  Do not insert blanks on either side of the colon.
  \begin{vvtm}
\begin{ccode}
    N: Nat
  \end{ccode}
\end{vvtm}
  or
  \begin{vvtm}
\begin{ccode}
    N :Nat
  \end{ccode}
\end{vvtm}
  is unacceptable. Only \verb|N:Nat| will do.
\end{warning}

The following session illustrates the utility of declarations of
this form. Recall from Section \ref{exs:simple-int} a module called
\verb|SIMPLE-INT|.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> parse in SIMPLE-INT : X:Int - s(0) .

  (X - s(0)) : Int
  CafeOBJ>
\end{ccode}
\end{vvtm}
The variable \verb|X| was declared on the fly. If you only want
to check syntactic ambiguity, it is a bother to declare
variables separately, just for that purpose.
The system treats an ephemeral variable declaration as a term ---
nothing more, nothing less ---,
so you can declare on the fly wherever you can write a term.
For the exact scope of on-the-fly declarations, see the next
section.

\section{Equation Declaration}

\subsection{Unconditional Equation Declaration}\label{sec:p2-equation-decl}

A plain equation is an axiom. Anticipating conditional cases,
we call it {\em unconditional}.\index{unconditional equation}

\begin{bsyntax} unconditional equation declaration \index{\texttt{eq}} \Hline
\index{\texttt{=} (in equations)}
\texttt{eq} $[$\textit{label}$]$ \textit{term} ``\texttt{=}'' \textit{term} ``\texttt{.}''
\end{bsyntax}

The last period, preceded by a blank, is a must. It is the way to
notify the system of the end of a term. ``\verb|=|'' separates
the lefthand side from the righthand.

\begin{warning}
  ``\verb|=|'' in equations is used by the system to detect the
  end (and start) of a term. You should supply blanks on both
  ends, as in
  \begin{vvtm}
\begin{ccode}
    eq X + 0 = X .
  \end{ccode}
\end{vvtm}
  Without blanks, the system thinks the lefthand side is continuing.
  For example,
  \begin{vvtm}
\begin{ccode}
    eq X + 0= X .
  \end{ccode}
\end{vvtm}
  causes the system to treat the entire text after \verb|eq| (and
  the subsequent text, until it encounters a lonely ``\verb|=|'') as
  the term on the lefthand side.
\end{warning}

Since an equation is a statement that the two sides are equal, they
must belong to a common universe of discourse. For example, to say that
Marie Antoinette equals 3.1416 is nonsense\footnote{
Or are they both pie?
}.
In many-sorted logic, this consideration is formalised as
``two terms must be of the same sort''. \cafeobj, which is based on
order-sorted logic, is more accommodating:
\begin{quote}
  The sorts of the terms must belong to the same connected component
  (in the graph defined by the sort ordering).
\end{quote}
Accordingly, $1$ may be equal to $1.0$, to $2/2$, to $\sqrt 1$,
and to $0i + 1$ (under the usual number hierarchy). We also require
that
\begin{quote}
  The terms be of visible sorts.
\end{quote}
For terms of hidden sorts, behavioural equations
(Section \ref{sec:p2-beh-eq-decl}) should be used.

Labels do not affect the semantics, and may be omitted. If not
omitted, it must be of the form

\begin{bsyntax} label in axioms \Hline
``\/\texttt{[}'' \textit{label\_name} ``\texttt{]}'' ``\texttt{:}''
\end{bsyntax}

where a label name is a character string without blanks.

Since most non-trivial equations involve variables, and since
unambiguous parsing is a non-trivial question, in examples below
we put variable declarations near equation declarations.

To state that \verb|0| is a right identity of addition, you may write
\begin{vvtm}
\begin{ccode}
  var N : Nat
  eq [ r-id ] : N + 0 = N .
\end{ccode}
\end{vvtm}
or, using an on-the-fly declaration,
\begin{vvtm}
\begin{ccode}
  eq [ r-id ] : N:Nat + 0 = N .
\end{ccode}
\end{vvtm}
Look at the second occurrence of \verb|N| in this equation. In general,
the scope of an on-the-fly declaration is the whole enclosing
term (or more precisely, in the rest of the term).
For example, the second \verb|N| of
\begin{vvtm}
\begin{ccode}
  N:Nat + s(N)
\end{ccode}
\end{vvtm}
is the same \verb|N| as declared on the fly, since
they are both in the same term. As a special rule, a variable
declared within an axiom is valid throughout that axiom. The
above equation illustrates this special rule.

On-the-fly declarations may overwrite the previous declarations.
For example, in
\begin{vvtm}
\begin{ccode}
  module S {
    [ S T ]
    op f : S -> S
    var X : T
    eq f(f(X:S)) = f(X) .
  }
\end{ccode}
\end{vvtm}
the variable \verb|X| was declared as of sort \verb|T|,
but re-declared on the fly as of sort \verb|S|. Remember that
overwriting variable declarations {\em terra firma} are illegal
(Section \ref{sec:p2-variable-decl}). On-the-fly declarations
are not subject to this prohibition. Moreover, on-the-fly
declarations may themselves be overwritten.
The following example uses \verb|X| first as of sort \verb|S|,
then as of \verb|T|.
\begin{vvtm}
\begin{ccode}
  module S {
    [ S T ]
    op f : S T -> T
    eq f(X:S,X:T) = X .
  }
\end{ccode}
\end{vvtm}

\begin{warning}
  In spite of the above remark, it is advisable not to
  overwrite on-the-fly's by on-the-fly's. It would easily
  lead to confusion. Accordingly, the system gives a warning when
  it encounters such cases.
\end{warning}

\subsection{Conditional Equation Declaration}\label{sec:p2-eq-decl-cond}

An equation may be {\em conditional}.\index{coditional equation}
A conditional equation is of the form

\begin{bsyntax} conditional equation declaration \index{\texttt{ceq}} \Hline
\index{\texttt{if}}
\texttt{ceq} $[$\textit{label}$]$ \textit{term} ``\texttt{=}'' \textit{term} \texttt{if} \textit{boolean\_term} ``\texttt{.}''
\end{bsyntax}

Labels and terms are as in \verb|eq|.
As stated often enough, the last blank-period lets the system know the
end of a term, and is a must. Note that a declaration starts with
\verb|ceq|, not \verb|eq|. \verb|ceq| may be abbreviated to \verb|cq|.
\index{\texttt{cq}}

\begin{warning}
  Like the last period, ``\verb|=|'' and \verb|if| demarcate terms. You
  should put blanks around them.
\end{warning}

\begin{warning}
  In former versions, conditions were preceded by \verb|:if|, not \verb|if|.
\end{warning}

A boolean term\index{boolean term} is a term of sort \verb|Bool|,
which is declared in
a built-in module called \verb|BOOL| (to be more precise, in a built-in
module imported by \verb|BOOL|)\index{\texttt{BOOL}}.
A conditional equation states that the two terms are equal if
the boolean term is true (i.e. it equals the constant \verb|true|).
We may say, therefore, that a boolean term {\em is} a condition.
\index{condition (of an equation)} As mentioned earlier
(Section \ref{sec:p2-import-decl}), every
module implicitly imports the module \verb|BOOL|, unless you have locked
it out. A major reason is that \verb|BOOL| provides you with boolean terms.
\verb|BOOL| contains all the usual boolean operators, so that,
as conditions, the following terms may be used
(if \verb|B|, \verb|B'| are boolean terms).
\begin{vvtm}
\begin{ccode}
  true
  false
  not B
  B and B'
  B or B'
\end{ccode}
\end{vvtm}
A complete listing may be obtained by \verb|show| command
(see Section \ref{sec:p2-inspect-module}).


\subsection{Behavioural Equation Declaration}\label{sec:p2-beh-eq-decl}

To state behavioural equality explicitly, the following constructs are
available.

\begin{bsyntax} behavioural equation declaration \Hline
\index{behavioural equation}\index{\texttt{beq}}\index{\texttt{bceq}}
\texttt{beq} $[$\textit{label} $]$ \textit{term} ``\texttt{=}'' \textit{term} ``\texttt{.}''
\texttt{bceq} $[$\textit{label}$]$ \textit{term} ``\texttt{=}'' \textit{term} \texttt{if} \textit{boolean\_term} ``\texttt{.}''
\end{bsyntax}

\verb|bceq| may be abbreviated to \verb|bcq|.\index{\texttt{bcq}}
Labels etc. are as in \verb|eq| or \verb|ceq|. Also as in \verb|eq|
or \verb|ceq|, both terms must belong to the same connected
component.
%In addition, we require that
%\begin{quote}
%  Any operator in the terms, if it has a hidden sort in its arity,
%  be behavioural
%\end{quote}
%i.e. it should have been declared with \verb|bop|, not with \verb|op|
%(Sections \ref{sec:p2-op-decl}, \ref{sec:p2-beh-op-decl}).
%For example, if \verb|S| is a hidden sort and \verb|T| a visible one,
%\begin{vvtm}
%\begin{ccode}
%  bop f : S -> T
%  bop g : S T -> S
%\end{ccode}
%\end{vvtm}
%are allowed since they are declared behavioural;
%\begin{vvtm}
%\begin{ccode}
%  op c : -> T
%  op d : -> S
%  op h : T -> T
%  op k : T -> S
%\end{ccode}
%\end{vvtm}
%are also allowed, since they do not act on \verb|S|; but
%\begin{vvtm}
%\begin{ccode}
%  op u : S -> T
%  op v : S T -> T
%\end{ccode}
%\end{vvtm}
%are prohibited, since they act on \verb|S| but are not declared bahavioural.

\begin{warning}
According to the above definition, you can write behavioural equations over
visible sort. There is no harm in that: such equations are treated
just like equations with \verb|eq| or \verb|ceq|.
But do avoid using \verb|beq| if \verb|eq| is what you mean.
Legality does not imply good manners.
\end{warning}

Note that in many cases, behavioural equality is defined, indirectly,
with ordinary equations (declared with \verb|eq| or \verb|ceq|), not with
behavioural ones (cf. Section \ref{exs:counter}).
Behavioural equations are reserved for cases
where explicit statements are desirable: typically, when
you state theorems, or want to define behavioural operators in terms of
others.

\section{Transition Declaration}\label{sec:p2-trans-decl}

Equality is an equivalence relation, obeying three basic properties
of binary relations: reflexivity, symmetry, and transitivity.
Dropping one of these properties engenders interesting relations.
Partial equivalence is one of them. By dropping symmetry, we get
a {\em transition}\index{transition} relation.

The following constructs define such a transition relation.
As with equations, there are conditional and unconditional transitions,
and ordinary and behavioural ones. Crossing these, you get

\begin{bsyntax} transition declaration \Hline
\index{\texttt{trans}}\index{\texttt{ctrans}}\index{\texttt{btrans}}
\index{\texttt{bctrans}}\index{\texttt{=>} (in transitions)}
\texttt{trans} $[$\textit{label}$]$ \textit{term} ``\texttt{=>}'' \textit{term} ``\texttt{.}''
\texttt{ctrans} $[$\textit{label}$]$ \textit{term} ``\texttt{=>}'' \textit{term} \texttt{if} \textit{boolean\_term} ``\texttt{.}''
\texttt{btrans} $[$\textit{label}$]$ \textit{term} ``\texttt{=>}'' \textit{term} ``\texttt{.}''
\texttt{bctrans} $[$\textit{label}$]$ \textit{term} ``\texttt{=>}'' \textit{term} \texttt{if} \textit{boolean\_term} ``\texttt{.}''
\end{bsyntax}

Syntactically, transitions are the same as equations, if you
replace the equality sign by the arrow ``\verb|=>|''. Similar restrictions
apply here also. For example, the sorts of two terms must be in the same
connected component.
%, and terms in behavioural transitions should not
%contain non-behavioural operators on hidden sorts.
\verb|trans| may be abbreviated to \verb|trns|,
\verb|ctrans| to \verb|ctrns|, \verb|btrans| to \verb|btrns|, and
\verb|bctrans| to \verb|bctrns|.
\index{\texttt{trns}}\index{\texttt{ctrns}}\index{\texttt{btrns}}\index{\texttt{bctrns}}

The following little example illustrates the difference between equations
and transitions.\label{exs:choice}
\begin{vvtm}
\begin{ccode}
  module CHOICE {
    [ State ]
    ops a b : -> State
    op _|_  : State State -> State
    vars X Y : State
    trans X | Y => X .
    trans X | Y => Y .
  }
\end{ccode}
\end{vvtm}
``\verb+_|_+'' denotes an indeterminate state, turning out to be either
argument (which itself may be indeterminate). The above rules
say that an indeterminate state may become more and more
determinate, but not conversely. It is obvious that,
if these rules were equations, all the states would be the same, so
that \verb|State| would be an uninteresting singleton.

A traditional way to describe the above choice operator is to
define an explicit transition function. The technique works at times,
but in this nondeterministic example, it would lead to something like
\begin{vvtm}
\begin{ccode}
  module CHOICE {
    [ State ]
    ops a b : -> State
    op _|_  : State State -> State
    op choose : State -> State
    vars X Y : State
    eq choose(X | Y) = X .
    eq choose(X | Y) = Y .
    eq choose(a) = a .
    eq choose(b) = b .
  }
\end{ccode}
\end{vvtm}
which, alas, is a specification of singletons.

\section{Internalising Axioms}\label{sec:p2-internal-axioms}

Axioms define certain kinds of relations when we construct models.
For example, axioms introduced by \verb|eq| or \verb|ceq| define
minimal congruence relations between reachable (term-generated)
elements of visible sorts. These relations reside outside of \cafeobj
~descriptions:
the mark ``\verb|=|'' is just a notation.

For various purposes, it is convenient if these relations can be
manipulated within the syntactical framework of \cafeobj. In general,
it is impossible to give general decision procedures for these
relations, but under certain conditions, or in some restricted
sense, it is possible to implement procedures that realise or
surrogate these relations. \cafeobj~provides four predicates
for this purpose.
\begin{itemize}
\item \verb|==| for equality.
\item \verb|==>| for transition relations.
\item \verb|=*=|, \verb|=b=| for behavioural equivalence.
\end{itemize}
The latter three are mainly used in theorem proving
(cf. Section \ref{sec:p2-theorem-proving-exs}).

In addition, the system supports a sort predicate ``\verb|:is|''.

\subsection{Equality Predicate}\label{sec:p2-equality-pred}

The predicate for (ordinary) equality, written ``\verb|==|'',\index{\texttt{==}}
is a binary operator defined on each visible sort.
An explicit declaration of the operator would be of the form
\begin{vvtm}
\begin{ccode}
  op _==_ : S S -> Bool
\end{ccode}
\end{vvtm}
or
\begin{vvtm}
\begin{ccode}
  pred _==_ : S S
\end{ccode}
\end{vvtm}
for each sort \verb|S|. ``\verb|_==_|'' is defined in terms of
evaluation (Chapter \ref{sec:p2-term-evaluation}).
For ground terms \verb|t|, \verb|t'| of sort \verb|S|,
``\verb|t == t'|'' equals \verb|true| iff \verb|t|, \verb|t'| evaluate to
a common term. It takes care of equational theories,
such as associativity (Section \ref{sec:p2-equational-theory}). Due to this
definition, ``\verb|_==_|'' works correctly only if the
term rewriting system\index{term rewriting system}
is terminating and
confluent (Section \ref{sec:p2-executable-module}).

The converse of ``\verb|_==_|'' is ``\verb|_=/=_|'',\index{\texttt{=/=}}
which returns
\verb|true| iff ``\verb|_==_|'' returns \verb|false| on the same arguments.

The exact mechanism for defining these operators is tricky, but all
are declared and defined in a built-in module \verb|BOOL|.
This module contains usual boolean operators, such as conjunction,
and, as mentioned earlier, is implicitly imported by other modules
(Section \ref{sec:p2-import-decl}).

Note the difference between equations, such as
\begin{vvtm}
\begin{ccode}
  eq N + 0 = N .
\end{ccode}
\end{vvtm}
and applications of the {\em operator} ``\verb|_==_|'', such as
\begin{vvtm}
\begin{ccode}
  N + 0 == N
\end{ccode}
\end{vvtm}
The sign ``\verb|=|'' in the former {\em denote\/}s an equivalence relation,
and this relation per se steer wide of syntactic manipulation.
``\verb|_==_|'' is an operator that generates terms, which are subject to
manipulation within the language processors. Still, they are related as
follows:
if the underlying term rewriting system is confluent and terminating,
\begin{quotation}
  \verb|X = X'| holds iff \verb|X == X' = true| does.
\end{quotation}

%There is another massively polymorphic equality predicate, which,
%unlike ``\verb|_==_|'', does not evaluate arguments.
%Its name is ``\verb|_===_|''. This operator is declared and defined in
%a built-in module called \verb|IDENTICAL|. The converse is
%``\verb|_=/==_|''.
%
%\begin{warning}
%  At the time of writing, the authors do not know why these two
%  operators are necessary or useful. These came from OBJ3.
%\end{warning}

\subsection{Transition Predicate}\label{sec:p2-transition-pred}

The predicate for transition relation, written ``\verb|==>|'',
\index{\texttt{==>}} is a binary
operator defined on each visible sort. As with ``\verb|==|'' in the
previous section, an explicit declaration would be of the form
\begin{vvtm}
\begin{ccode}
   pred _==>_ : S S
\end{ccode}
\end{vvtm}
for each sort \verb|S|. This predicate is in fact declared on
the ``universal'' sort, in a module called \verb|RWL|.
\verb|RWL| is imported implicitly, when a module contains
transition declarations (Section \ref{sec:p2-trans-decl}).
As with \verb|BOOL| (Section \ref{sec:p2-import-decl}), it is
possible to switch off this implicit importation, by the command
\index{\texttt{set}}\index{\texttt{include}}\index{\texttt{RWL}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set include RWL off
\end{ccode}
\end{vvtm}

A transition relation is reflexive, transitive, and is closed under
operator application. When \verb|RWL| is imported, the system
supplies a set of axioms.
Firstly, for each visible sort \verb|S|, an axiom
\begin{vvtm}
\begin{ccode}
  eq X:S ==> X = true .
\end{ccode}
\end{vvtm}
is declared. (In fact, a single equation declared in \verb|RWL| works
for any \verb|S|.) This axiom states reflexivity.
Secondly, for each unconditional tranision
\begin{vvtm}
\begin{ccode}
  trans t => t' .
\end{ccode}
\end{vvtm}
the system declares
\begin{vvtm}
\begin{ccode}
  eq t ==> t' = true .
\end{ccode}
\end{vvtm}
and for each conditional transition
\begin{vvtm}
\begin{ccode}
  ctrans t => t' if c .
\end{ccode}
\end{vvtm}
the system declares
\begin{vvtm}
\begin{ccode}
  ceq t ==> t' = true if c .
\end{ccode}
\end{vvtm}
These declarations correspond to one-step transitions.

Thirdly, for each operator declaration
\begin{vvtm}
\begin{ccode}
  op f : S1 ... Sn -> S
\end{ccode}
\end{vvtm}
the system declares
\begin{vvtm}
\begin{ccode}
  ceq f(X1:S1, ..., Xn:Sn) ==> f(X1':S1, ..., Xn':Sn) = true
     if X1 ==> X1' and ... and Xn ==> Xn' .
\end{ccode}
\end{vvtm}
which states that ``\verb|_==>_|'' is closed under \verb|f|'s
application.

As to transitivity, a straightforward declaration would not do:
an axiom of the form
\begin{vvtm}
\begin{ccode}
  ceq X:S ==> X':S = true if X ==> X'':S and X'' ==> X' .
\end{ccode}
\end{vvtm}
introduces an extra variable in the condition, which makes it
inappropriate for the purpose of evaluation (cf. Section
\ref{sec:p2-executable-module}). Considering that the main usage of
the predicate ``\verb|==>|'' is to prove theorems with evaluation mechanism,
this fact renders such an axiom useless. In its place the system add
the following axiom.
\begin{vvtm}
\begin{ccode}
  ceq X:S ==> X':S = true if X =(*)=> X' .
\end{ccode}
\end{vvtm}
Attached to the operator ``\verb|_=(*)=>_|'' is a systematic search
procedure for determining whether the first argument transits to
the second in an arbitraty number of steps. More on this and related
operators in Section \ref{sec:p2-proving-trans-2}.

\subsection{Behavioural Equivalence Predicate}\label{sec:p2-beh-equiv-pred}

The predicate for behavioural equivalence, written ``\verb|=*=|'',
\index{\texttt{=*=}} is a binary
operator defined on each hidden sort. As with ``\verb|==|'' and
``\verb|==>|'' in previous sections, an explicit declaration would be of the
form
\begin{vvtm}
\begin{ccode}
   pred _=*=_ : S S
\end{ccode}
\end{vvtm}
for a given sort \verb|S|.

Remember that behavioural operators are declared with \verb|bop|, and each
such operator has exactly one hidden sort in its arity
(Section \ref{sec:p2-beh-op-decl}).
On the assumption that ``\verb|a =*= a'|'' implies
``\verb|f1(a) == f1(a')|'' for any ``attribute'' \verb|f| and for
any \verb|a|, if ``\verb|=*=|'' turns out to be congruent wrt all the
``method''s, the system declares an axiom
\begin{vvtm}
\begin{ccode}
  eq A =*= A' = f1(A) == f1(A') and ... and fn(A) == fn(A') .
\end{ccode}
\end{vvtm}
where \verb|f1|, \ldots, \verb|fn| are the attributes.

Recalling an example of bank accounts
\begin{vvtm}
\begin{ccode}
  *[ Account ]*
  bop deposit : Account Nat -> Account
  bop withdraw : Account Nat -> Account
  bop balance : Account -> Nat
\end{ccode}
\end{vvtm}
the above assumption is
\begin{vvtm}
\begin{ccode}
  ceq balance(A:Account) = balance(A':Account) if A =*= A' .
\end{ccode}
\end{vvtm}
and ``\verb|=*=|'' is congruent if two equations
\begin{vvtm}
\begin{ccode}
  eq deposit(a,n) =*= deposit(a',n) = true .
  eq withdraw(a,n) =*= withdraw(a',n) = true .
\end{ccode}
\end{vvtm}
hold, on the hypothesis that
\begin{vvtm}
\begin{ccode}
  eq a =*= a' = true .
\end{ccode}
\end{vvtm}
for arbitrary \verb|a|, \verb|a'|, and \verb|n|.

If the switch ``\kbd{accept} \verb|=*=| \kbd{proof}'' is \kbd{on}
(the default is \kbd{off}),
the system tries to prove these two equations
by evaluation (Chapter \ref{sec:p2-term-evaluation}).
If ``\verb|_=*=_|'' does turn out to be a congruence, the system
adds the axiom
\begin{vvtm}
\begin{ccode}
  ceq A:Account =*= A':Account if balance(A) == balance(A') .
\end{ccode}
\end{vvtm}
Intuitively, this axiom states that two terms of \verb|Account| are
indistinguishable if they are indistuiguishable by a single
application of \verb|balance|.

Note that, if ``\verb|=*=|'' is not turned out to be congruent,
no axiom defines ``\verb|=*=|''. In such a case, ``\verb|=*=|''
is not even reflexive.

%\begin{warning}
%The existence of completely undefined ``\verb|=*=|'' is annoying.
%In future, this predicate may be defined as above, whether or not
%it is congruent.
%\end{warning}

Another predicate for behavioural equivalence is ``\verb|=b=|,''
\index{\texttt{=b=}}
which is to behavioural equations as ``\verb|==|'' is to plain ones, and is
defined to \verb|true| iff both hand sides evaluate to a common
term. The difference between ``\verb|==|'' and ``\verb|=b=|''
is in the applicability of behavioural axioms
(See \ref{sec:p2-evaluation-command} for detail).

\subsection{Sort Predicate}\label{sec:p2-sort-pred}

The system supplies a predicate that checks whether a given
term is of a given sort. It is of the form
\begin{vvtm}
\begin{ccode}
  t :is S
\end{ccode}
\end{vvtm}
and evaluates to \verb|true| if \verb|t| belongs to \verb|S|.
You can supply explicit axioms for the predicate. An example is
\begin{vvtm}
\begin{ccode}
  vars N N' : Nat
  ceq N + N' :is NzNat = true if N :is NzNat .
  ceq N + N' :is NzNat = true if N' :is NzNat .
\end{ccode}
\end{vvtm}

\begin{warning}
  This feature is introduced as a surrogate of membership relation.
  We stress that it is a surrogate, not a real thing.
%   The existence (and implementation) of this predicate is highly
%   tentative, and maybe dropped entirely at any time.
  You should not use this feature unless absolutely necessary.
  There are switches such as ``\verb|mel sort|'' related to
  this predicate. They are also highly tentative, and you should not
  use them unless absolutely necessary.
\end{warning}

\chapter{Inspecting Modules}\label{sec:p2-inspect-module}

It is time we show some examples that combine all of the
declarations explained so far. This chapter also illustrates
the module inspection command \verb|show| (Section \ref{sec:p2-show-command}).

\section{Using Inspection Commands}\label{sec:p2-insp-basic}

\subsection{Printing Whole Modules}\label{sec:p2-print-whole-module}

We first recall \verb|SIMPLE-NAT|, which defines natural number addition
(Section \ref{exs:simple-nat}).
\begin{vvtm}
\begin{ccode}
  module SIMPLE-NAT {
    [ Zero NzNat < Nat ]
    op 0  : -> Zero
    op s : Nat -> NzNat 
    op _+_ : Nat Nat -> Nat
    vars N N' : Nat
    eq 0 + N = N .
    eq s(N) + N' = s(N + N') .
  }
\end{ccode}
\end{vvtm}
Everything in this module has been already explained, so you should
know that this is indeed a standard recursive definition of addition.
A subtle point is in the use of subsort relation. Here the set of
natural numbers is the union of \verb|Zero|, which contains \verb|0|
(and nothing else), and \verb|NzNat|, which contains
\verb|s(0)|, \verb|s(s(0))|, and so forth.

Suppose this definition is in the file \verb|simple-nat.cafe|. Then
you may get the following session.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> input simple-nat

  -- processing input : ./simple-nat.cafe
  -- defining module SIMPLE-NAT....._..* done.
  CafeOBJ> show SIMPLE-NAT  
  module SIMPLE-NAT {
    imports {
      protecting (BOOL)
    }
    signature {
      [ Nat, Zero NzNat < Nat,
        NzNat, NzNat < Nat,
        Zero, Zero < Nat ]
      op 0 : -> Zero
      op s : Nat -> NzNat
      op _ + _ : Nat Nat -> Nat { strat: (1 0 2) }
    }
    axioms {
      var N : Nat
      var N' : Nat
      eq 0 + N = N .
      eq s(N) + N' = s(N + N') .
    }
  }

  CafeOBJ>
\end{ccode}
\end{vvtm}
When invoked with a module name, \verb|show| command prints the entire
contents of the module. You may notice that
\begin{itemize}
\item Block constructs \verb|imports|, \verb|signature|, and
  \verb|axioms| (Section \ref{sec:p2-blocks-in-mod}) are used,
  even though you did not use them.
\item The module \verb|BOOL| is imported automatically. As explained
  earlier, \verb|BOOL| defines Boolean operators and is imported unless
  prohibited by a switch (Section \ref{sec:p2-import-decl}).
\item There is a bracketed text after the declaration of ``\verb|_+_|''.
  This is an operator attribute, to be explained later
 (Section \ref{sec:p2-op-properties}).
\end{itemize}
\begin{warning}
  Display of sort declarations is often knotted. This is due to
  implementation restriction; an ``optimal'' display is very hard to
  define anyway.
\end{warning}

\subsection{Print Part of Modules}\label{sec:p2-print-part-of-module}

To print partial contents, such as sort declarations only, of
a module, you may supply further arguments to \verb|show| command.
Continuing the above session, you get
\begin{vvtm}
\begin{ccode}
  CafeOBJ> show sorts SIMPLE-NAT
  * visible sorts :
    Zero, Zero < Nat
    NzNat, NzNat < Nat
    Nat, Zero NzNat < Nat

  CafeOBJ> show ops SIMPLE-NAT
  ..................................(0)..................................
    * rank: -> Zero
  ..................................(s)..................................
    * rank: Nat -> NzNat
  ................................(_ + _)................................
    * rank: Nat Nat -> Nat { strat: (1 0 2) }
      - axioms:
        eq 0 + N = N
        eq s(N) + N' = s(N + N')

  CafeOBJ>
\end{ccode}
\end{vvtm}
The arguments \verb|sorts|, \verb|ops|, etc. specify the parts of
the module to be shown. To summarise the mostly obvious,
\begin{center}
\begin{tabular}{ll}
 \verb|sorts| & sort and subsort declarations \\
 \verb|ops| & operator declarations \\
 \verb|vars| & variable declarations \\
 \verb|axioms| & axiom declarations \\
 \verb|params| & parameter declarations (to be introduced later) \\
 \verb|subs| & import declarations (for `sub'modules) \\
 \verb|sign| & \verb|sorts| and \verb|ops| combined (i.e. the signature) \\
\end{tabular}
\end{center}

It is possible to list declarations in imported modules also. For
an example for example's sake,
\begin{vvtm}
\begin{ccode}
  CafeOBJ> module SHADOW-NAT {
    protecting (SIMPLE-NAT)
  }

  -- defining module SHADOW-NAT._* done.
  CafeOBJ> show sorts SHADOW-NAT

  CafeOBJ> show all sorts SHADOW-NAT
  * visible sorts :
    Zero, Zero < Nat
    NzNat, NzNat < Nat
    Nat, Zero NzNat < Nat

  CafeOBJ> 
\end{ccode}
\end{vvtm}
\verb|SHADOW-NAT| simply imported declarations of \verb|SIMPLE-NAT|
and added nothing. The plain \verb|sorts| argument prints nothing,
while \verb|all sorts| prints sort declarations in the imported
\verb|SIMPLE-NAT|.

\begin{warning}
  \verb|all| does not print anything in the implicitly imported modules.
  Even if you import \verb|BOOL| explicitly, the system still refuses to
  print the declarations in them.
\end{warning}

In case of axioms, instead of crying \verb|all| to \verb|show| command,
you may change a switch called ``\verb|all axioms|'', as
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set all axioms on
\end{ccode}
\end{vvtm}

If you are inspecting a particular module, it is convient to set
it as current (Section \ref{sec:p2-current-module}), so that the
module name may be omitted.\index{current module}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select SIMPLE-NAT

  SIMPLE-NAT> show sorts
  * visible sorts :
    Zero, Zero < Nat
    NzNat, NzNat < Nat
    Nat, Zero NzNat < Nat

  SIMPLE-NAT> show ops
  ..................................(0)..................................
    * rank: -> Zero
  ..................................(s)..................................
    * rank: Nat -> NzNat
  ................................(_ + _)................................
    * rank: Nat Nat -> Nat
      - attributes:  { strat: (1 0 2) }
      - axioms:
        eq 0 + N = N
        eq s(N) + N' = s(N + N')

  SIMPLE-NAT>
\end{ccode}
\end{vvtm}
Note that the prompt has changed, to indicate what module is current.

It is possible to focus on a single sort, operator or imported module.
For example,
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> show sort Nat
  Sort Nat declared in the module SIMPLE-NAT
    - subsort relation :
  
       ?Nat    
         |      
        Nat    
      /     \   
    Zero  NzNat
              
  

  SIMPLE-NAT> show op _+_
  ................................(_ + _)................................
    * rank: Nat Nat -> Nat
      - attributes { strat: (1 0 2) }
      - axioms:
        eq 0 + N = N
        eq s(N) + N' = s(N + N')

  SIMPLE-NAT>
\end{ccode}
\end{vvtm}
Here the subsort relation is shown graphically. \verb|?Nat| is
an error sort, and you should ignore it for now (cf. Section
\ref{sec:p2-flexible-typing}).

A switch controls whether the sort of each variable is displayed.
\index{\texttt{set}}{\texttt{show}}\index{\texttt{var}}\index{\texttt{sorts}}
Continuing the session, you get
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> set show var sorts on

  SIMPLE-NAT> show op _+_
  ................................(_ + _)................................
    * rank: Nat Nat -> Nat
      - attributes { strat: (1 0 2) }
      - axioms:
        eq 0 + N:Nat = N:Nat
        eq s(N:Nat) + N':Nat = s(N:Nat + N':Nat)

  SIMPLE-NAT>
\end{ccode}
\end{vvtm}
\begin{warning}
  This switch does not have a total control. In cases when sorts
  are not apparent --- when an axiom is from an imported module, or
  when variables are redeclared on the fly, and so on --- the system displays
  them willynilly.
\end{warning}

\subsection{Deep Inspection}\label{sec:p2-deep-inspection}

If you want more detailed explanations of the module contents, use
\verb|describe|, in place of \verb|show|.
This command is useful when you are evaluating terms
(Chapter \ref{sec:p2-term-evaluation}). Since we have not yet
explained term evaluation mechanisms, you should not expect to
understand the following output. It is enough to know the
flavour of difference between \verb|show| and \verb|describe|.
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> describe op _+_
  ======================================================================
  name                : (_ + _)
  module              : SIMPLE-NAT
  number of arguments : 2
  default attributes  :
   rewrite strategy   : not specified
   syntax             :
     precedence       : not specified
     computed prec.   : 41
     form             : (arg:41) "+" (arg:41) 
   theory             : 
  ----------------------------------------------------------------------
  rank                : ?Nat ?Nat -> ?Nat
    module            : SIMPLE-NAT
    theory            : 
    rewrite strategy  : (1 2 0)
    precedence        : 41
    lower oprations   :
      Nat Nat -> Nat
    axioms            :
  ----------------------------------------------------------------------
  rank                : Nat Nat -> Nat
    module            : SIMPLE-NAT
    theory            : 
    rewrite strategy  : (1 0 2 0)
    precedence        : 41
    axioms            :
    - equation 
      lhs             : 0 + N:Nat
      rhs             : N:Nat
      top operator    : Nat Nat -> Nat
    - equation 
      lhs             : s(N:Nat) + N':Nat
      rhs             : s(N:Nat + N':Nat)
      top operator    : Nat Nat -> Nat

  SIMPLE-NAT> 
\end{ccode}
\end{vvtm}

%% \newpage
%% \subsection{Inspecting Records}\label{sec:p2-record-inspection}

%% As explained in Section \ref{sec:p2-plain-record-decl}, a record
%% declaration has the same effects as several related declarations
%% of sorts and operators. You may be anxious to know how the system
%% handles record declarations. If you are, put the record \verb|Date|
%% into a module declaration, and inspect it.\label{exs:date}
%% \begin{vvtm}
%% \begin{ccode}
%% CafeOBJ> module DATE {
%%   protecting (SIMPLE-NAT)
%%   record Date {
%%     year  : Nat
%%     month : Nat
%%     day   : Nat
%%  } }
%%   -- defining module DATE.._* done.
%%   CafeOBJ> select DATE
%%   DATE> show sorts
%%   * visible sorts :
%%     Date, Date < RecordInstance
%%     RecordDate, RecordDate < RecordId
%%     Slotyear, Slotyear < AttrId
%%     Slotmonth, Slotmonth < AttrId
%%     Slotday, Slotday < AttrId
%%   DATE>
%% \end{ccode}
%% \end{vvtm}
%% \verb|SIMPLE-NAT| (Section \ref{exs:simple-nat}) should be familiar.
%% The record \verb|Date| was indeed declared as a sort, as we stated.
%% But it seems that a lot more sorts are involved. They are used to define
%% the operators. To see what operators were declared, you may inspect
%% further. But hold your breath:
%% \begin{vvtm}
%% \begin{ccode}
%% DATE> show ops
%% ................................(_ { })................................
%%   * rank: RecordDate -> Date
%%     - attributes:  { constr }
%% ...............................(_ { _ })...............................
%%   * rank: RecordDate Attributes -> Date
%%     - attributes:  { constr }
%% ................................(Date)................................
%%   * rank: -> RecordDate
%%     - attributes:  { constr }
%% ..............................(makeDate)..............................
%%   * rank: Attributes -> Date
%%     - axioms:
%%       eq makeDate(ATTRS-6:Attributes) = #!! (make-record-instance 'date
%%                                              attrs-6)
%% ..............................(makeDate)..............................
%%   * rank: -> Date
%%     - axioms:
%%       eq makeDate = #!! (make-record-instance 'date)
%% ................................(year)................................
%%   * rank: -> Slotyear
%%     - attributes:  { constr }
%% ................................(year)................................
%%   * rank: Date -> Nat
%%     - axioms:
%%       eq year(RID-5:RecordDate { (VAR-SLOTYEAR-2:Slotyear = VAL-11:Nat, 
%%           ATTRS-6:Attributes) }) = VAL-11:Nat
%% ..............................(set-year)..............................
%%   * rank: Date Nat -> Date
%%     - axioms:
%%       eq set-year(RID-5:RecordDate { (VAR-SLOTYEAR-2:Slotyear = VAL-11:Nat, 
%%           ATTRS-6:Attributes) },NEW-VAL-12) = RID-5:RecordDate
%%           { (VAR-SLOTYEAR-2:Slotyear =  NEW-VAL-12 , ATTRS-6:Attributes) }
%% \end{ccode}
%% \end{vvtm}
%% The print continues for \verb|month|, \verb|set-month| and so on.
%% We do not explain the above in detail, and only say that these
%% declarations are necessary for the flexible syntax you may use, and
%% for realising record inheritances. Remember that a record may be written as
%% \begin{vvtm}
%% \begin{ccode}
%%   Date { year = 1984, month = 1, day = 1 }
%% \end{ccode}
%% \end{vvtm}
%% or
%% \begin{vvtm}
%% \begin{ccode}
%%   Date { month = 1, day = 1, year = 1984 }
%% \end{ccode}
%% \end{vvtm}
%% interchangeably; you may also omit uninteresting slots, as
%% \begin{vvtm}
%% \begin{ccode}
%%   Date { year = 1984 }
%% \end{ccode}
%% \end{vvtm}
%% where \verb|month| and \verb|date| disappear;
%% and \verb|set|, \verb|set-year| etc. will be declared for every record
%% that inherits \verb|Date|.

%% Finally, look at axioms.
%% \begin{vvtm}
%% \begin{ccode}
%%   DATE> show axioms
%%   - Equations
%%     eq day(RID-5:RecordDate { (VAR-SLOTDAY-4:Slotday = VAL-7:Nat , 
%%            ATTRS-6:Attributes) }) = VAL-7:Nat
%%     eq set-day(RID-5:RecordDate { (VAR-SLOTDAY-4:Slotday = VAL-7:Nat , 
%%            ATTRS-6:Attributes) }, NEW-VAL-8) 
%%        = RID-5:RecordDate { (VAR-SLOTDAY-4:Slotday = NEW-VAL-8 , 
%%            ATTRS-6:Attributes) }
%% \end{ccode}
%% \end{vvtm}
%% Again we omitted the rest of the (long) output. The above two equations
%% define \verb|day| and \verb|set-day|. Their simplified forms are
%% \begin{vvtm}
%% \begin{ccode}
%%   eq day (Date { day = D, month = M, year = Y }) = D .
%%   eq set-day (Date { day = D, month = M, year = Y }, D') =
%%         Date { day = D', month = M, year = Y } .
%% \end{ccode}
%% \end{vvtm}
%% which look exactly like the access functions to \verb|day|.

\section{Some Typical Modules}\label{sec:p2-typical-modules}

\subsection{Unique Models}\label{sec:p2-unique-model}

When you write a specification of natural numbers (Section
\ref{sec:p2-print-whole-module}), your probable intention is
to specify ``the'' natural numbers. For example, you do not
want a singleton $\{ 0 \}$ to constitute a model of
your specification (the elements are too few), nor a colossal
sum $\mathcal{N} + \mathcal{N} + \ldots + \mathcal{N}$ (too many).
You want exactly the set $\{ 0, 1, 2, \ldots \}$ to be the
model of your specification.

In the terminology of \cafeobj, such a module should be interpreted to have
tight denotation: it has exactly one model --- the usual term
model. A module introduced with ``\verb|module!|'' is always so interpreted.
So perhaps it is more to your taste if we have written
\begin{vvtm}
\begin{ccode}
  module! SIMPLE-NAT {
  ...
  }
\end{ccode}
\end{vvtm}
As another example of tight denotation, consider indeterminate
choice (cf. Section \ref{exs:choice}) of natural numbers\footnote{
The current implementation imports a
builtin sort of the same name, so you need a lot of qualifications
for this example to work correctly.

}.
\label{exs:choice-nat}
\begin{vvtm}
\begin{ccode}
  module! CHOICE-NAT {
    extending (SIMPLE-NAT)
    op _|_ : Nat Nat -> Nat
    vars N N' : Nat
    trans N | N' => N .
    trans N | N' => N' .
  }
\end{ccode}
\end{vvtm}
In the model you have in mind,
\begin{itemize}
\item[] \verb+0 | s(0)+ may transit to \verb|0|
\item[] \verb+0 | s(0)+ may transit to \verb|s(0)|
\end{itemize}
but
\begin{itemize}
\item[] \verb+0 | s(0)+ should not transit to \verb|s(s(0))|
\end{itemize}
\verb|module!| ensures that the last transition is not in the model.
To cope with transition relations, the model must have a 2-categorical
structure\footnote{
In fact, since \cafeobj~does not distinguish transitions between the
same two elements, a more restricted structure --- essentially,
partial orders and monotonic functions --- serves as well.
}; otherwise, everything is a straightforward extension to usual
algebraic semantics.

\subsection{Inspecting Transition Axioms}\label{sec:p2-trans-beget-axs}

When you declare a transition, a couple of axioms are automatically
generated (Section \ref{sec:p2-transition-pred}). Let us use
\verb|CHOICE-NAT| for illustration.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> module! CHOICE-NAT {
      extending (SIMPLE-NAT)
      op _|_ : Nat Nat -> Nat
      vars N N' : Nat
      trans N | N' => N .
      trans N | N' => N' .
    }

  -- defining module! CHOICE-NAT..._._.* done.
  CafeOBJ> select CHOICE-NAT

  CHOICE-NAT> show axioms
  - Equations
    ceq cv1:Nat | cv2:Nat ==> cv3:Nat | cv4:Nat = true 
        if cv1:Nat ==> cv3:Nat and cv2:Nat ==> cv4:Nat
    ceq s(cv1:Nat) ==> s(cv2:Nat) = true if cv1:Nat ==> cv2:Nat
    ceq cv1:Nat + cv2:Nat ==> cv3:Nat + cv4:Nat = true 
        if cv1:Nat ==> cv3:Nat and cv2:Nat ==> cv4:Nat
    eq N | N' ==> N' = true
    eq N | N' ==> N = true
  - Rules
    trans N | N' => N
    trans N | N' => N'

  CHOICE-NAT> show subs
  extending(SIMPLE-NAT)
  protecting(RWL)

  CHOICE-NAT> 
\end{ccode}
\end{vvtm}
As shown above, congruence axioms are added, and a
module called \verb|RWL| is imported automatically. \verb|RWL| is
the module that declares ``\verb|_==>_|''.

\begin{warning}
  By the way, where is the reflexivity axiom? Well, it is hidden
  in the module \verb|RWL|. The current implementation provides
  a ``universal'' reflexivity axiom, and each module does not
  acquire a new axiom. But you should think as if it did.
\end{warning}

\subsection{Non-isomorphic Models}\label{sec:p2-non-iso-model}

There are cases when your favourite models are not unique. Examples
abound in defining algebraic structures. Monoids may be defined as
\label{exs:monoid}
\begin{vvtm}
\begin{ccode}
  module* MONOID {
    [ M ]
    op e : -> M
    op _*_ : M M -> M
    vars X Y Z : M
    eq (X * Y) * Z = X * (Y * Z) .
    eq e * X = X .
    eq X * e = X .
  }
\end{ccode}
\end{vvtm}
When you write down the above module, what is intended is not
(only) a trivial monoid, the singleton $\{ e \}$. But that is
exactly the tight denotation of this module, which you would get
if it were declared with ``\verb|module!|''. In this case, a module
should accommodate any model so long as it has an associative
binary operator with an --- i.e., the --- identity element.
A module introduced with ``\verb|module*|'' is always interpreted as such.

Another example uses behavioural operators.\label{exs:counter}
\begin{vvtm}
\begin{ccode}
  module* COUNTER {
    protecting (SIMPLE-NAT)
    *[ Counter ]*
    bop read : Counter -> Nat
    bop add : Nat Counter -> Counter
    eq read(add(N:Nat, C:Counter)) = N + read(C) .
  }
\end{ccode}
\end{vvtm}
Your intention is to define a counter that is incremented by
the operator \verb|add|. Tight denotation would lead to the model
where, e.g., for a fixed counter \verb|c|,
\begin{vvtm}
\begin{ccode}
  add(s(0), add(s(s(0)), c))
  add(s(s(0)), add(s(0), c))
\end{ccode}
\end{vvtm}
are different elements. Intuitively, this model says that
adding 1, then 2, is different from adding 2, then 1. When your
sole concern is the return values of \verb|read|, this model
works fine (adding 2, then 1 increments the counter by 3;
so does adding 1, then 2). But there is no reason to
preclude a model where the above two terms denote the same
element (the order of addition is immaterial). Hence this
module was introduced with ``\verb|module*|'', as above.

\subsection{Inspecting Hidden Sorts}\label{sec:p2-hsort-beget-axs}

Two terms of a hidden sort is equal, or {\em behaviourally equivalent},
\index{behaviourally equivalent}, iff they behave the same under
any {\em behavioural context} (cf. \cite{hsa}),\index{behavioural context}
\index{context (behavioural)} or {\em observation}\index{observation}.
An observation is a term of a visible sort, which contains
exactly one (occurrence of one) variable of the hidden sort.
(So an observation is a special derived operator --- see
Section \ref{sec:p2-pre-view}.)
In the example of \verb|COUNTER|, the observations for \verb|Counter|
is of the form
\begin{vvtm}
\begin{ccode}
  read(X), read(add(m,X)), read(add(m,add(m',X))), ...
\end{ccode}
\end{vvtm}
where \verb|X| is a variable of sort \verb|Counter|, and
\verb|m|, \verb|m'| are arbitrary terms of sort \verb|Nat|.
For this special case, therefore, the above definition means that
two terms \verb|t|, \verb|t'| of sort \verb|Counter| are
behaviourally equal iff the equations
\begin{vvtm}
\begin{ccode}
  eq read(t) = read(t') .
  eq read(add(m,t)) = read(add(m,t')) .
  eq read(add(m,add(m',t))) = read(add(m,add(m',t'))) .
  ...
\end{ccode}
\end{vvtm}
hold.

Unlike equality over visible sorts, equality over hidden sorts
are unlikely to be determined by straightforward reduction; two terms
may well turn out to be behaviourally equivalent, even if they have
different irreducible forms. It is still possible, however, to
use reduction to {\em help} prove behavioural equivalence.

As explained in Section \ref{sec:p2-beh-equiv-pred}, the system
associates a binary predicate ``\verb|_=*=_|'' to each hidden sort,
and declare an axiom. You may inspect the detail,
as the following example shows.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> module* COUNTER {
      protecting (SIMPLE-NAT)
      *[ Counter ]*
      bop read : Counter -> Nat
      bop add : Nat Counter -> Counter
      eq read(add(N:Nat, C:Counter)) = N + read(C) .
    }

  -- defining module* COUNTER...._.*
  * system already proved =*= is a congruence of COUNTER done.
  CafeOBJ> select COUNTER

  COUNTER> show axioms
  - Equations
    eq read(add(N:Nat,C:Counter)) = N:Nat + read(C:Counter)
    ceq hs1:Counter =*= hs2:Counter = true if read(hs1:Counter) ==
        read(hs2:Counter)

  COUNTER> 
\end{ccode}
\end{vvtm}
In processing \verb|COUNTER| the system added an equation
after checking congruence.

\chapter{Evaluating Terms}\label{sec:p2-term-evaluation}

\cafeobj~has an operational semantics based on term rewriting system
(TRS)s. This chapter introduces the very basics of TRSs and explains
when a \cafeobj~code constitutes a TRS.

\section{Term Rewriting System}\label{sec:p2-trs}

\subsection{What is a TRS}\label{sec:p2-trs-basic}

This section is an intuitive introduction to the computation model of
TRS's\index{TRS}\index{term rewriting system}. First, a preliminary.

\begin{itemize}
\item[] {\em Substitution}\index{substitution}. 
  A substitution is a set $S$ of pairs $(v,t)$ of a variable $v$ and a
  (ground) term $t$, such that no two pairs contain the same variable.
  If $(v,t)$ is in $S$, $t$ is said to be the {\em value} of $v$ under
  $A$.
\item[] {\em Instantiation}\index{instantiation of a term}.
  Given a substitution $S$ and a term $t$, replacing each (occurrence of
  each) variable in $t$ with its value under $S$ is called the
  instantiation of $t$ by $S$.
\item[] {\em Matching}\index{matching}. Given a {\em ground} term
  \index{ground term} $t$ and a
  term $p$, if there is a substitution $S$ such that the instantiation
  of $p$ by $S$ equals $t$, $t$ is said to be matchable to $p$.
  To compute such a substitution is called matching.
\end{itemize}
Given a set $R$ of rewrite rules, computation with $R$ as TRS
proceeds as follows: given a {\em ground} term $t$,
\begin{itemize}
\item[1.] (pattern matching) Find a rewrite rule in $R$ such that a
 subterm $s$ of $t$
 is matchable to its lefthand side.
\item[2.] (rewrite) If such a rewrite rule is found, replace
 $s$ in $t$ with
 the instance of its righthand by the matching substitution, and
 go back to 1. with the resulting new term.
\item[3.] If no such rewrite rule is found, terminate.
\end{itemize}
This procedure is called {\em evaluation}\index{evaluation},
or {\em reduction}\index{reduction}, of $t$. If the procedure terminates,
the resultant term is said to be {\em irreducible}\index{irreducible (term)},
or {\em normal}\index{normal (term)}.
Note well that this procedure is for ground terms only.

If a rewrite rule is conditional, in addition to matchability,
you also have to check the condition. To check the condition,
its instance by the matching substitution is evaluated. The rule is
applicable only when the condition evaluates to (a term denoting)
true. A TRS with conditional rewrite rules is called conditional
TRS.

Another refinement of the above procedure is to match terms
not only syntactically, but modulo an equational theory $E$.
Such a mathching procedure is called $E$-matching\index{E-matching}.
A typical equational theory is associativity. Modulo associativity
on an operator ``\verb|_*_|'', for example,
``\verb|a * (b * c)|'' matches ``\verb|(X * b) * Y|'',
where \verb|X|, \verb|Y| are variables, since the former term is
equal to ``\verb|(a * b) * c|''. \cafeobj~does support this kind of
matching (cf. Section \ref{sec:p2-equational-theory}).

There may be cases where more than one rules match with
more than one subterms --- so the above procedure
is, in fact, hardly a procedure at all. Which one to choose, and when, is a
significant issue. \cafeobj~allows you to control the selection, operator
by operator. See Section \ref{sec:p2-rew-strategy}.

\subsection{How a Module Defines a TRS}\label{sec:p2-executable-module}

The axioms of \cafeobj~are equations and transitions, which define
equivalence and transition relations. In operational semantics,
these axioms are regarded, uniformly, as directed rewrite rules,
as follows. If we denote a rewrite rule by \verb|t -> t'|,
for relevant terms \verb|t|, \verb|t'|, and \verb|b|,
\begin{itemize}
\item[] \verb|eq t = t' .| is a rewrite rule \verb|t -> t'|.
\item[] \verb|ceq t = t' if b .| is a rewrite rule \verb|t -> t'|
  with the condition \verb|b|.
\item[] \verb|trans t => t' .| is a rewrite rule \verb|t -> t'|.
\item[] \verb|ctrans t => t' if b .| is a rewrite rule \verb|t -> t'|
  with the condition \verb|b|.
\end{itemize}
Behavioural axioms are translated similarly.
Then the TRS defined by a module is the set of axioms regarded
as rewrite rules as above. Note that the axioms of the imported
modules are included in this definition.

For example, \verb|SIMPLE-NAT| (Section \ref{exs:simple-nat})
defines a TRS that contains two rewrite rules
\begin{vvtm}
\begin{ccode}
  0 + N -> N
  s(N) + N' -> s(N + N')
\end{ccode}
\end{vvtm}
where \verb|N|, \verb|N'| are variables of sort \verb|Nat|.
Since \verb|BOOL| is implicitly imported, its axioms (as rewrite rules)
are also in this TRS. \verb|show| command may be used to list all
the rules (see examples in Section \ref{sec:p2-eval-exs-1}).

Two kinds of axioms are excluded from TRS's, solely
by syntactic criteria. For an axiom to be a rewrite rule,
\begin{itemize}
\item[(1)] Every variable that occurs in the righthand side or in the
  condition must occur in the lefthand side also. Otherwise the terms
  under computation may become non-ground.
\item[(2)] The lefthand side must not be a single variable. Otherwise
  every term (of a relevant sort) is matchable, so the computation never
  stops.
\end{itemize}
For order-sorted TRS, there might be other constraints, such as
sort-decreasing property. But \cafeobj~does not impose such a constraint.

There are two important properties of TRSs.
If computation always terminates, the TRS is said to be {\em terminating}.
\index{terminating} If, whenever a term is rewritten to two different
terms, they can be further rewritten to a same term, the TRS is said to
be {\em confluent}\index{confluent}. If terminating and confluent, it is
{\em canonical}.\index{canonical (TRS)}

In general, the declarative meaning of
an axiom set differs from the operational one (i.e. TRS). But
there {\em is} a coincidence if we restrict ourselves to tight
denotation and equations.
If the set, regarded as TRS, is canonical, i.e. terminating and confluent,
\begin{quote}
Two (ground) terms are equal iff they are reducible to a common term.
\end{quote}
For this reason, it is important to distinguish a subset of
a TRS derived only from equations (cf. \verb|reduce| command in
Section \ref{sec:p2-evaluation-command}). It also follows that
for loose denotation, reduction per se does not suggest anything
of much import. (For theorem proving, it {\em is} useful --- see
Section \ref{sec:p2-theorem-proving-exs}).

\section{Do the Evaluation}

\subsection{Evaluation Commands}\label{sec:p2-evaluation-command}

There are three commands for evaluating terms.

\begin{bsyntax} \texttt{reduce} command \index{\texttt{reduce}} \Hline
\texttt{reduce} $[$\texttt{in} \textit{module\_expression} ``\texttt{:}''$]$ \textit{term} ``\texttt{.}''
\end{bsyntax}

\begin{bsyntax} \texttt{breduce} command \index{\texttt{breduce}} \Hline
\texttt{breduce} $[$\texttt{in} \textit{module\_expression} ``\texttt{:}'' $]$ \textit{term} ``\texttt{.}''
\end{bsyntax}

\begin{bsyntax} \texttt{execute} command \index{\texttt{execute}} \Hline
\texttt{execute} $[$\texttt{in} \textit{module\_expression} ``\texttt{:}''$]$ \textit{term} ``\texttt{.}''
\end{bsyntax}

As is ever the case, the period after a blank is a must.
\verb|reduce| can be abbreviated to \verb|red|, \verb|breduce| to
\verb|bred|, and
\verb|execute| to \verb|exec|. Module expressions are introduced in
Section \ref{sec:p2-module-expression}, and we only consider
module names here. These commands evaluate the term with a TRS defined
by the given module; or by the current module
(Section \ref{sec:p2-current-module}),\index{current module}
if the module expression is omitted.

These three commands differ on (1) which axioms constitute the TRS
and (2) applicability of some rewrite rules.
\begin{itemize}
\item[(1)]
  \begin{itemize}
  \item For \verb|reduce| or \verb|breduce|, only --- possibly conditional,
    possibly behavioural --- equations are taken to constitute the TRS.
    Transitions are excluded. This ensures that under certain conditions
    (Section \ref{sec:p2-executable-module}) \verb|reduce| gives a
    decision procedure for equational theory.
  \item For \verb|execute|, all the axioms constitute the TRS.
  \end{itemize}
\item[(2)]
  \begin{itemize}
  \item For \verb|reduce| or \verb|execute|, a rewrite rule that
    come from a behavioural axiom is applicable only when the
    redex in enclosed in an observation. This ensures the
    soundness of evaluation.
  \item For \verb|breduce|, there is no such restriction.
  \end{itemize}
\end{itemize}
The point (1) comes from the fact that \verb|reduce| (\verb|breduce|) is
to get a term equal (behaviourally equivalent)
to the input, while \verb|execute| is to get a term
that the input may eventually transit to.
The point (2) comes from the fact that \verb|breduce| is to get a term
behaviourally equivalent to the input, while \verb|reduce| is to get a
term equal to the input. These points are illustated in
Sections \ref{sec:p2-eval-exs-2} and \ref{sec:p2-eval-exs-3}.

%On the point (2), consider the following declarations.
%\begin{vvtm}
%\begin{ccode}
%  *[ S ]*
%   [ T ]
%  ops a b : -> S
%  bop f : S -> T
%  beq [ a-sim-b ] a = b .
%\end{ccode}
%\end{vvtm}
%The axiom \verb|a-sim-b| asserts that \verb|a| is behaviourally
%equivalent to \verb|b|, but does not say that they are equal.
%Therefore such an axiom should not be used to conclude
%that \verb|a| equals \verb|b|. On the other hand, since
%\verb|a| and \verb|b| are behaviourally equivalent, every
%observation of the two terms is equal. A forteriori
%\verb|f(a)| equals \verb|f(b)|. In reasoning the equality,
%the axiom \verb|a-sim-b| is safely used. This is the gist of
%the restriction stated in (2).

During evaluation, it is sometimes desirable to see the rewrite sequences,
not just the results. For example, to enhance efficiency, you may want to
know where redundant computations of subterms occur. For this purpose,
\cafeobj~provides trace switches, which can be set by\index{\texttt{set}}
\index{\texttt{trace}}\index{\texttt{trace whole}}\index{\texttt{whole}}
\index{trace (of evaluation)}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set trace whole on
\end{ccode}
\end{vvtm}
by which the resultant term of each rewrite step is printed, or
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set trace on
\end{ccode}
\end{vvtm}
by which the rule, substitution, and replacement are printed. The
effects of these switches shall be illustrated by examples
below.

\subsection{Replacing Equals by Equals}\label{sec:p2-eval-exs-1}

Recall \verb|SIMPLE-NAT| (Section \ref{exs:simple-nat}) again,
make it current, and do some evaluations.
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> reduce 0 .

  -- reduce in SIMPLE-NAT : 0
  0 : Zero
  (0.000 sec for parse, 0 rewrites(0.000 sec), 0 matches)
  SIMPLE-NAT> reduce 0 + s(0) .

  -- reduce in SIMPLE-NAT : 0 + s(0)
  s(0) : NzNat
  (0.000 sec for parse, 1 rewrites(0.000 sec), 1 matches)

  SIMPLE-NAT> reduce s(0) + 0 .

  -- reduce in SIMPLE-NAT : s(0) + 0
  s(0) : NzNat
  (0.010 sec for parse, 2 rewrites(0.000 sec), 3 matches)
  SIMPLE-NAT>
\end{ccode}
\end{vvtm}
The output from the system has three parts, showing
the system's understanding of what to do (the line starting with
``\verb|--|''), the result of evaluation (the second line), and
what looks like statistics (in parentheses). The result is of the form
\begin{vvtm}
\begin{ccode}
  term : sort
\end{ccode}
\end{vvtm}
where \verb|sort| is the least sort (Section \ref{sec:p2-wff-terms})
of \verb|term|.

You may print the rules of \verb|SIMPLE-NAT| as follows.\index{\texttt{show}}
\index{\texttt{rules}}
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> show rules
   -- rewrite rules in module : SIMPLE-NAT
    1 : eq 0 + N = N
    2 : eq s(N) + N' = s(N + N')

  SIMPLE-NAT> 
\end{ccode}
\end{vvtm}
Note that all the axioms of the implicitly imported \verb|BOOL|
are also in the TRS, but were not printed above. It is possible to
print all the rules, including those declared in the imported modules,
by an extra argument to \verb|show|.
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> show all rules
   -- rewrite rules in module : SIMPLE-NAT
    1 : eq 0 + N = N
    2 : eq s(N) + N' = s(N + N')
    3 : eq not true = false
    4 : eq not false = true
    5 : eq false and A:Bool = false
    6 : eq true or A:Bool = true
    7 : eq true and-also A:Bool = A:Bool
    8 : eq A:Bool and-also true = A:Bool
    9 : eq false and-also A:Bool = false
   10 : eq A:Bool and-also false = false
   11 : eq true or-else A:Bool = true
   12 : eq A:Bool or-else true = true
   13 : eq false or-else A:Bool = A:Bool
   14 : eq A:Bool or-else false = A:Bool
   15 : eq A:Bool implies B:Bool = not A:Bool or B:Bool
   16 : eq true xor true = false
   17 : eq CXU : Id:SortId = #!! (coerce-to-bool
                                  (test-term-sort-membership cxu id))
   18 : eq if true then CXU else CYU fi = CXU
   19 : eq if false then CXU else CYU fi = CYU
   20 : eq CXU == CYU = #!! (coerce-to-bool (term-equational-equal cxu cyu))
   21 : eq HXU =b= HYU = #!! (coerce-to-bool (term-equational-equal hxu hyu))
   22 : eq CXU =/= CYU = #!! (coerce-to-bool
                              (not (term-equational-equal cxu cyu)))

  SIMPLE-NAT> 
\end{ccode}
\end{vvtm}

\begin{warning}
  The righthand sides of the rules \verb|17| and so on contain
  a strange symbol \verb|#!!|, and the terms that follow
  suspiciously resemble Lisp's S-expressions. These are examples of
  system-dependent definitions of operators. If you are not
  confident enough about implementation issues, do not touch
  these definitions.
\end{warning}

Since the axioms of \verb|SIMPLE-NAT| are all equations, the results of
\verb|reduce| and \verb|execute| should be the same. Indeed, you have
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> execute 0 + s(0) .

  -- execute in SIMPLE-NAT : 0 + s(0)
  s(0) : NzNat
  (0.010 sec for parse, 1 rewrites(0.000 sec), 1 matches)
  SIMPLE-NAT> execute s(0) + 0 .

  -- execute in SIMPLE-NAT : s(0) + 0
  s(0) : NzNat
  (0.000 sec for parse, 2 rewrites(0.000 sec), 3 matches)
  SIMPLE-NAT> 
\end{ccode}
\end{vvtm}

The statistics may be suppressed by a switch.\index{\texttt{set}}
\index{\texttt{stats}}
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> set stats off

  SIMPLE-NAT> reduce s(0) + 0 .

  -- reduce in SIMPLE-NAT : s(0) + 0
  s(0) : NzNat
  SIMPLE-NAT>
\end{ccode}
\end{vvtm}

\begin{warning}
  \verb|stats| is not an abbreviation.
\end{warning}

\subsection{Equations and Transitions}\label{sec:p2-eval-exs-2}

To see the difference between \verb|execute| and \verb|reduce|,
we switch to \verb|CHOICE-NAT| (Section \ref{exs:choice-nat}).
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> select CHOICE-NAT

  CHOICE-NAT> set stats on

  CHOICE-NAT> reduce s(0) | (s(s(0)) + s(s(s(0)))) .

  -- reduce in CHOICE-NAT : s(0) | (s(s(0)) + s(s(s(0))))
  s(0) | s(s(s(s(s(0))))) : Nat
  (0.010 sec for parse, 3 rewrites(0.000 sec), 5 matches)

  CHOICE-NAT> execute s(0) | (s(s(0)) + s(s(s(0)))) .

  -- execute in CHOICE-NAT : s(0) | (s(s(0)) + s(s(s(0))))
  s(0) : NzNat
  (0.000 sec for parse, 1 rewrites(0.000 sec), 1 matches)

  CHOICE-NAT> show all rules
   -- rewrite rules in module : CHOICE-NAT
    1 : ceq cv1:Nat | cv2:Nat ==> cv3:Nat | cv4:Nat = true if cv1:Nat ==> 
      cv3:Nat and cv2:Nat ==> cv4:Nat
    2 : ceq s(cv1:Nat) ==> s(cv2:Nat) = true if cv1:Nat ==> cv2:Nat
    3 : ceq cv1:Nat + cv2:Nat ==> cv3:Nat + cv4:Nat = true if cv1:Nat ==> 
      cv3:Nat and cv2:Nat ==> cv4:Nat
    4 : eq N | N' ==> N' = true
    5 : eq N | N' ==> N = true
    6 : trans N | N' => N
    7 : trans N | N' => N'
    8 : eq 0 + N = N
    9 : eq s(N) + N' = s(N + N')
   10 : ...
\end{ccode}
\end{vvtm}
We omitted the rest of the listing, which contains axioms in
\verb|BOOL|. \verb|reduce| command ignores transition declarations
\verb|6| and \verb|7|, so the reduction stopped after rewriting
the second argument of \verb+_|_+. \verb|execute| applied the
rule \verb|6| immediately, and just one rewrite (see the statistics)
led to the result.

\begin{warning}
  Technically, the TRS faithful to the underlying model
  should be a TRS, derived entirely from transitions, over equivalence
  classes of terms, determined by equations. The current system
  does not distinguish transitions and equations during evaluation,
  and acts faithfully only when certain conditions are satisfied.
  For detail, see \cite{rew-logic}.
\end{warning}

\subsection{Using Behavioural Equations}\label{sec:p2-eval-exs-3}

As a matter of course, behavioural equations can be
used to prove behavioural equivalence. With judicious use, they can also be
used to prove equality. Consider the following example.
\label{exs:nat-stream}
\begin{vvtm}
\begin{ccode}
  module* NAT-STREAM {
    protecting (SIMPLE-NAT)
    *[ Stream ]*
    bop __ : Nat Stream -> Stream
    bop hd : Stream -> Nat
    bop tl : Stream -> Stream
    op zeros : -> Stream
    var N : Nat
    var S : Stream
    eq hd(N S) = N .
    beq tl(N S) = S .
    eq hd(zeros) = 0 .
    beq tl(zeros) = zeros .
  }
\end{ccode}
\end{vvtm}
A behavioural equation asserts that \verb|tl(n s)| is behaviourally
equivalent to \verb|s| for any \verb|n| and \verb|s|, but does not
assert that they are equal. Therefore, on the one hand,
it is incorrect to reason
that \verb|tl(s(0) zeros)| equals \verb|zeros| from this axiom.
On the other hand, it is correct to reason
that \verb|hd(tl(s(0) zeros))| is equal to \verb|hd(zeros)| and hence
to \verb|0|, since \verb|hd|, being an observation on \verb|Stream|,
gives the same answer if applied to behaviourally equivalent terms.

In processing \verb|reduce|, the system tries to apply behavioural
equations (as rewrite rules) only when the redex is under an
observation, as shown below.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select NAT-STREAM

  NAT-STREAM> reduce hd(tl(s(0) zeros)) .

  -- reduce in NAT-STREAM : hd(tl(s(0) zeros))
  0 : Zero
  (0.010 sec for parse, 2 rewrites(0.000 sec), 3 matches)
  NAT-STREAM> reduce tl(s(0) zeros) .

  -- reduce in NAT-STREAM: tl(s(0) zeros)
  tl(s(0) zeros) : Stream
  (0.000 sec for parse, 0 rewrites(0.000 sec), 0 matches)
  NAT-STREAM> 
\end{ccode}
\end{vvtm}
Compare the above result to the case when \verb|breduce| is
invoked instead. Since this command is to get an behaviourally
equivalent term, the system applies behavioural equations
indiscriminately, as
\begin{vvtm}
\begin{ccode}
  NAT-STREAM> breduce tl(s(0) zeros) .

  -- behavioural reduce in NAT-STREAM : tl(s(0) zeros)
  zeros : Stream
  (0.000 sec for parse, 1 rewrites(0.000 sec), 1 matches)
  NAT-STREAM> 
\end{ccode}
\end{vvtm}

\subsection{Evaluation Traces}\label{sec:p2-eval-trace}

We continue the session of the previous section.
The statistics contained the number of rewrites and match attempts.
Reduction of ``\verb|0 + s(0)|'' and ``\verb|s(0) + 0|'' in Section
\ref{sec:p2-eval-exs-1} amounts to computing $0 + 1$ and $1 + 0$
respectively, and the statistics showed that the efforts of computation
were greater with $1 + 0$. You probably know why. To confirm your reasoning,
try trace switches.\index{\texttt{trace whole}}\index{trace (of evaluation)}
\begin{vvtm}
\begin{ccode}
  CHOICE-NAT> select SIMPLE-NAT

  SIMPLE-NAT> set trace whole on

  SIMPLE-NAT> reduce 0 + s(0) .

  -- reduce in SIMPLE-NAT : 0 + s(0)
  [1]: 0 + s(0)
   ---> s(0)
  s(0) : NzNat
  (0.000 sec for parse, 1 rewrites(0.000 sec), 1 matches)
  SIMPLE-NAT> reduce s(0) + 0 .

  -- reduce in SIMPLE-NAT : s(0) + 0
  [1]: s(0) + 0
   ---> s(0 + 0)
  [2]: s(0 + 0)
   ---> s(0)
  s(0) : NzNat
  (0.000 sec for parse, 2 rewrites(0.010 sec), 3 matches)
  SIMPLE-NAT> 
\end{ccode}
\end{vvtm}
The system printed the reduction traces. They show that the
first reduction immediately cancelled a right identity zero,
while the second reduction, which could not rely on the knowledge
that zero is also a left identity, took two rewrites to
get the result.

Sometimes more elaborate traces are desirable.\index{\texttt{trace}}
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> set trace whole off

  SIMPLE-NAT> set trace on

  SIMPLE-NAT> reduce s(0) + 0 .

  -- reduce in SIMPLE-NAT : s(0) + 0
   1>[1] rule: eq s(N:Nat) + N':Nat = s(N:Nat + N':Nat)
       { N':Nat |-> 0, N:Nat |-> 0 }
   1<[1] s(0) + 0 --> s(0 + 0)
   1>[2] rule: eq 0 + N:Nat = N:Nat
       { N:Nat |-> 0 }
   1<[2] 0 + 0 --> 0
  s(0) : NzNat
  (0.000 sec for parse, 2 rewrites(0.000 sec), 3 matches)
  SIMPLE-NAT> 
\end{ccode}
\end{vvtm}
This time, each rewrite step was explained in more detail.
The three lines starting with ``\verb|1>|'' correspond to a
single step. They show the rewrite rule (i.e. equation or
transition) applied, the substitution used, and the replacement.

``\verb|trace whole|'' switch traces the entire term, while
replacements shown by \verb|trace| switch focus on the
changed subterms. This difference was illustrated by the last
step of this example, where ``\verb|trace whole|'' printed
\begin{vvtm}
\begin{ccode}
  [2] s(0 + 0) --> s(0)
\end{ccode}
\end{vvtm}
while \verb|trace| printed
\begin{vvtm}
\begin{ccode}
  [2] 0 + 0 --> 0
\end{ccode}
\end{vvtm}

\subsection{Examples of Conditionals}\label{sec:p2-ex-cond}

To illustrate the r{\^ o}le of conditions, we first define an operator
that computes greatest common divisors by filling more meat in the bony
\verb|SIMPLE-NAT|.\label{exs:simple-nat+}\label{exs:gcd}
\begin{vvtm}
\begin{ccode}
  module SIMPLE-NAT+ {
    protecting (SIMPLE-NAT)
    op _-_ : Nat Nat -> Nat
    op _<_ : Nat Nat -> Bool
    -- ---------------------
    vars N M : Nat
    eq 0 - M = 0 .
    eq N - 0 = N .
    eq s(N) - s(M) = N - M .
    eq 0 < s(N) = true .
    eq N < 0 = false .
    eq s(N) < s(M) = N < M .
  }

  module GCD {
    protecting (SIMPLE-NAT+)
    op gcd : Nat Nat -> Nat
    -- --------------------
    vars N M : Nat
    ceq gcd(N, M) = gcd(M, N) if N < M .
    eq gcd(N, 0) = N .
    ceq gcd(s(N), s(M)) = gcd(s(N) - s(M), s(M))
        if not (N < M) .
  }
\end{ccode}
\end{vvtm}
The definitions of the pseudo-subtraction and the less than relation are
more or less standard. \verb|gcd| is defined by conditional equations.
Note that \verb|BOOL| is imported implicitly, so that all the operators
in it, like ``\verb|not_|'' here, are available.

To see how these definitions work, continue the session in the previous
section. Feed the modules to the system, and try as follows.
\begin{vvtm}
\begin{ccode}
  SIMPLE-NAT> set trace off

  SIMPLE-NAT> select GCD

  GCD> reduce gcd(s(s(s(s(s(s(0)))))), s(s(s(s(0))))) .

  -- reduce in GCD : gcd(s(s(s(s(s(s(0)))))),s(s(s(s(0)))))
  s(s(0)) : NzNat
  (0.000 sec for parse, 44 rewrites(0.010 sec), 113 matches)
  GCD>  
\end{ccode}
\end{vvtm}
The reduction amounts to computing the greatest common divisor of
$6$ and $4$. The statistics show that the system worked much harder
than ever. You may get traces as before. Since the output is largish,
we show traces of simpler computations (but this is still large).
\begin{vvtm}
\begin{ccode}
  GCD> set trace whole on

  GCD> reduce gcd(s(s(s(s(0)))), s(s(0))) .

  -- reduce in GCD : gcd(s(s(s(s(0)))),s(s(0)))
  [1(cond)]: s(s(s(s(0)))) < s(s(0))
     --> s(s(s(0))) < s(0)
  [2(cond)]: s(s(s(0))) < s(0)
     --> s(s(0)) < 0
  [3(cond)]: s(s(0)) < 0
     --> false
  [4(cond)]: not s(s(s(0))) < s(0)
     --> not s(s(0)) < 0
  [5(cond)]: not s(s(0)) < 0
     --> not false
  [6(cond)]: not false
     --> true
  [7]: gcd(s(s(s(s(0)))),s(s(0)))
   ---> gcd(s(s(s(s(0)))) - s(s(0)),s(s(0)))
  [8]: gcd(s(s(s(s(0)))) - s(s(0)),s(s(0)))
   ---> gcd(s(s(s(0))) - s(0),s(s(0)))
  [9]: gcd(s(s(s(0))) - s(0),s(s(0)))
   ---> gcd(s(s(0)) - 0,s(s(0)))
  [10]: gcd(s(s(0)) - 0,s(s(0)))
   ---> gcd(s(s(0)),s(s(0)))
  [11(cond)]: s(s(0)) < s(s(0))
     --> s(0) < s(0)
  [12(cond)]: s(0) < s(0)
     --> 0 < 0
  [13(cond)]: 0 < 0
     --> false
  [14(cond)]: not s(0) < s(0)
     --> not 0 < 0
  [15(cond)]: not 0 < 0
     --> not false
  [16(cond)]: not false
     --> true
  [17]: gcd(s(s(0)),s(s(0)))
   ---> gcd(s(s(0)) - s(s(0)),s(s(0)))
  [18]: gcd(s(s(0)) - s(s(0)),s(s(0)))
   ---> gcd(s(0) - s(0),s(s(0)))
  [19]: gcd(s(0) - s(0),s(s(0)))
   ---> gcd(0 - 0,s(s(0)))
  [20]: gcd(0 - 0,s(s(0)))
   ---> gcd(0,s(s(0)))
  [21(cond)]: 0 < s(s(0))
     --> true
  [22]: gcd(0,s(s(0)))
   ---> gcd(s(s(0)),0)
  [23(cond)]: s(s(0)) < 0
     --> false
  [24]: gcd(s(s(0)),0)
   ---> s(s(0))
  s(s(0)) : NzNat
  (0.000 sec for parse, 24 rewrites(0.070 sec), 60 matches)
  GCD> 
\end{ccode}
\end{vvtm}
The apparent difference from the previous traces is the presence of
``\verb|[(#)cond]|'' steps. As explained in Section
\ref{sec:p2-trs-basic}, the system reduces conditions when it checks
applicability of conditional rewrite rules. The above trace was the
\index{conditional rewrite rule}
result of following all of those recursive evaluations. For brevity
we now resort to a very simple computation,
and show only the initial part of the initial trace.
\begin{vvtm}
\begin{ccode}
  GCD> set trace whole off

  GCD> set trace on

  GCD> reduce gcd(s(s(0)),s(s(0))) .

   -- reduce in GCD : gcd(s(s(0)),s(s(0)))
   1>[1] apply trial #1
   -- rule: ceq gcd(N:Nat,M:Nat) = gcd(M:Nat,N:Nat) if N:Nat < M:Nat
       { M:Nat |-> s(s(0)), N:Nat |-> s(s(0)) }
   2>[1] rule: eq s(N:Nat) < s(M:Nat) = N:Nat < M:Nat
       { M:Nat |-> s(0), N:Nat |-> s(0) }
   2<[1] s(s(0)) < s(s(0)) --> s(0) < s(0)
   2>[2] rule: eq s(N:Nat) < s(M:Nat) = N:Nat < M:Nat
       { M:Nat |-> 0, N:Nat |-> 0 }
   2<[2] s(0) < s(0) --> 0 < 0
   2>[3] rule: eq N:Nat < 0 = false
       { N:Nat |-> 0 }
   2<[3] 0 < 0 --> false
   1>[4] -- rewrite rule exhausted (#1)
   1>[4] apply trial #2
   -- rule: ceq gcd(s(N:Nat),s(M:Nat)) = gcd(s(N:Nat) - s(M:Nat),s(M:Nat)
         ) if not N:Nat < M:Nat
       { M:Nat |-> s(0), N:Nat |-> s(0) }
   2>[4] rule: eq s(N:Nat) < s(M:Nat) = N:Nat < M:Nat
       { M:Nat |-> 0, N:Nat |-> 0 }
   2<[4] s(0) < s(0) --> 0 < 0
   2>[5] rule: eq N:Nat < 0 = false
       { N:Nat |-> 0 }
   2<[5] 0 < 0 --> false
   2>[6] rule: eq not false = true
       {}
   2<[6] not false --> true
   1>[7] match success #2
   1<[7] gcd(s(s(0)),s(s(0))) --> gcd(s(s(0)) - s(s(0)),s(s(0)))
\end{ccode}
\end{vvtm}
Note the appearances of ``\verb|2>|''. The number indicates the depth
of recursion: evaluating conditions may lead to recursively
evaluating conditions, and so on and on.
Most of the output should be self-explanatory.
The above trace shows two conditional rules were checked,
first unsuccessfuly and second successfuly.

\section{Stepper}\label{sec:p2-stepper}

By taking traces, you may inspect in detail how reductions proceed,
and modify axioms if they are not going as expected.
The set of commands introduced in this section is for controlling
reductions in more detail, and help you ``debug'' modules.

\subsection{Step Mode}\label{sec:p2-step-mode}

You may enter into/leave the step\index{step mode} mode by a switch.
\index{\texttt{set}}\index{\texttt{step}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set step on
\end{ccode}
\end{vvtm}
In this mode, evaluation commands apply rewrite rules
step by step. We first define multiplication.\label{exs:mult}
\begin{vvtm}
\begin{ccode}
  module MULT {
    protecting (SIMPLE-NAT)
    op _*_ : Nat Nat -> Nat
    vars N M : Nat
    eq 0 * N = 0 .
    eq s(N) * M = M + (N * M) .
  }
\end{ccode}
\end{vvtm}
After feeding \verb|SIMPLE-NAT| and \verb|MULT|,
you may get the following session.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select MULT

  MULT> set step on

  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> stepper term: s(s(0)) * s(s(s(0)))
  STEP[1]? 
\end{ccode}
\end{vvtm}
The new prompt indicates you are in the step mode.
You may list the commands available in this mode
by the help command ``\verb|:?|''.\index{\texttt{:?}}
\begin{vvtm}
\begin{ccode}
  STEP[1]? :?
  -- Stepper command help :
    ?               print out this help
    n(ext)          go one step
    g(o) <number>   go <number> step
    c(ontinue)      continue rewriting without stepping
    q(uit)          leave stepper continuing rewrite
    a(bort)         abort rewriting
    r(ule)          print out current rewrite rule
    s(subst)        print out substitution
    l(imit)         print out rewrite limit count
    p(attern)       print out stop pattern
    stop [<term>] . set(unset) stop pattern
    rwt [<number>] .set(unset) max number of rewrite
  -- the followings are subset of cafeobj interpreter commands
    show -or-
    describe        print various info., for further help, type `show ?'
    set             set toplevel switches, for further help: type `set ?'
    cd <directory>  change current directory
    ls <directory>  list files in directory
    pwd             print current directory
    lisp -or-
    lispq <lisp>    evaluate lisp expression <lisp>
    ! <command>     fork shell <command>. Under Unix only
  STEP[1]? 
\end{ccode}
\end{vvtm}
Some of them, such as \verb|show|, \verb|set|, and \verb|cd|, should be
familiar. They are not particular to the step mode. Particular to the
mode are the commands prefixed by ``\verb|:|'', in addition to
\verb|rwt| and \verb|stop|.

The prefix ``\verb|:|'' may be omitted, and there are longer forms
for some step mode commands. Here is a summary of synonyms.
\index{\texttt{:h}}\index{\texttt{?}}\index{\texttt{h}}
\index{\texttt{:help}}\index{\texttt{help}}
\index{\texttt{:n}}\index{\texttt{n}}\index{\texttt{:next}}\index{\texttt{next}}
\index{\texttt{:g}}\index{\texttt{g}}\index{\texttt{:go}}\index{\texttt{go}}
\index{\texttt{:c}}\index{\texttt{c}}\index{\texttt{:continue}}\index{\texttt{continue}}
\index{\texttt{:q}}\index{\texttt{q}}
\index{\texttt{:a}}\index{\texttt{a}}\index{\texttt{:abort}}\index{\texttt{abort}}
\index{\texttt{:r}}\index{\texttt{r}}\index{\texttt{:rule}}\index{\texttt{rule}}
\index{\texttt{:s}}\index{\texttt{s}}\index{\texttt{:subst}}\index{\texttt{subst}}
\index{\texttt{:l}}\index{\texttt{l}}\index{\texttt{:limit}}\index{\texttt{limit}}
\index{\texttt{:p}}\index{\texttt{p}}\index{\texttt{:pattern}}\index{\texttt{pattern}}
\index{\texttt{:rew}}\index{\texttt{rew}}\index{\texttt{:rewrite}}\index{\texttt{rewrite}}
\index{\texttt{:stop}}\index{\texttt{stop}}
\begin{center}
\begin{tabular}{llll}
\verb|:?|, \verb|:h| & \verb|?|, \verb|h| & \verb|:help| & \verb|help| \\
\verb|:n| & \verb|n| & \verb|:next| & \verb|next| \\
\verb|:g| & \verb|g| & \verb|:go| & \verb|go| \\
\verb|:c| & \verb|c| & \verb|:continue| & \verb|continue| \\
\verb|:q| & \verb|q| & & \\
\verb|:a| & \verb|a| & \verb|:abort| & \verb|abort| \\
\verb|:r| & \verb|r| & \verb|:rule| & \verb|rule| \\
\verb|:s| & \verb|s| & \verb|:subst| & \verb|subst| \\
\verb|:l| & \verb|l| & \verb|:limit| & \verb|limit| \\
\verb|:p| & \verb|p| & \verb|:pattern| & \verb|pattern| \\
\verb|:rwt| & \verb|rwt| & \verb|:rewrite| & \verb|rewrite| \\
& & \verb|:stop| & \verb|stop| \\
\end{tabular}
\end{center}

\begin{warning}
  The command names are tentative, and are subject to change.
\end{warning}

\subsection{Evaluation Under the Step Mode}\label{sec:p2-eval-step-mode}

Continuing the session in the previous section, we illustrate the
effects of each command.\index{\texttt{:n}}
\begin{vvtm}
\begin{ccode}
  STEP[1]? :n

  >> stepper term: s(s(s(0))) + (s(0) * s(s(s(0))))
  STEP[2]? :n

  >> stepper term: s(s(0)) + (s(0) * s(s(s(0))))
  STEP[3]? :n
  >> stepper term: s(0) + (s(0) * s(s(s(0))))
  STEP[4]? 
\end{ccode}
\end{vvtm}
``\verb|:n|'' prints a kind of traces, but beware that the printed term
is a subterm under replacement. You may print the current form of
the entire term as\index{\texttt{show}}\index{\texttt{term}}
\begin{vvtm}
\begin{ccode}
  STEP[4]? show term
  s(s((s(0) + (s(0) * s(s(s(0))))))) : NzNat
  STEP[4]? 
\end{ccode}
\end{vvtm}
Or you may get a better (if longer) trace if
that is what you want, by setting ``\verb|trace whole|'' to \verb|on|.
Starting from the first step, the output is
\begin{vvtm}
\begin{ccode}
  MULT> set trace whole on

  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> stepper term: s(s(0)) * s(s(s(0)))
  STEP[1]? :n

  [1]: s(s(0)) * s(s(s(0)))
   ---> s(s(s(0))) + (s(0) * s(s(s(0))))
  >> stepper term: s(s(s(0))) + (s(0) * s(s(s(0))))
  STEP[2]? :n

  [2]: s(s(s(0))) + (s(0) * s(s(s(0))))
   ---> s(s(s(0)) + (s(0) * s(s(s(0)))))
  >> stepper term: s(s(0)) + (s(0) * s(s(s(0))))
  STEP[3]? :n

  [3]: s(s(s(0)) + (s(0) * s(s(s(0)))))
   ---> s(s(s(0) + (s(0) * s(s(s(0))))))
  >> stepper term: s(0) + (s(0) * s(s(s(0))))
  STEP[4]? 
\end{ccode}
\end{vvtm}
which shows the stepper is focusing more and more inside. To skip
several steps, use \verb|:g|.\index{\texttt{:g}}
\begin{vvtm}
\begin{ccode}
  STEP[4]? set trace whole off

  STEP[4]? :g 5

  >> stepper term: s(0) + (0 * s(s(s(0))))
  STEP[9]? :g 5

  s(s(s(s(s(s(0)))))) : NzNat
  (0.010 sec for parse, 11 rewrites(0.040 sec), 19 matches)
  MULT> 
\end{ccode}
\end{vvtm}
\verb|show| command may take arguments \verb|term| {\em and} \verb|tree|.
Then a tree form of the term is printed
(See Section \ref{sec:p2-choose-command} for an example).

The rest of the commands act as follows.
\begin{vvtm}
\begin{ccode}
  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> stepper term: s(s(0)) * s(s(s(0)))
  STEP[1]? :a     

  s(s(0)) * s(s(s(0))) : Nat
  (0.000 sec for parse, 1 rewrites(0.000 sec), 2 matches)
  MULT> 
\end{ccode}
\end{vvtm}
``\verb|:a|'' stops the evaluation immediately.\index{\texttt{:a}}
\begin{vvtm}
\begin{ccode}
  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> stepper term: s(s(0)) * s(s(s(0)))
  STEP[1]? :n

  >> stepper term: s(s(s(0))) + (s(0) * s(s(s(0))))
  STEP[2]? :r
  (s(N:Nat) + N':Nat) = s((N:Nat + N':Nat))
  STEP[2]? :s
  { N':Nat |-> s(0) * s(s(s(0))), N |-> s(s(0)) }
  STEP[2]? :c

  s(s(s(s(s(s(0)))))) : NzNat
  (0.000 sec for parse, 11 rewrites(0.010 sec), 19 matches)
  MULT> 
\end{ccode}
\end{vvtm}
``\verb|:r|'' and ``\verb|:s|'' show the
rule and the substitution to be used in
the {\em next} step (study the above example carefully). ``\verb|:c|''
continues the evaluation non-stop.
\index{\texttt{:r}}\index{\texttt{:s}}\index{\texttt{:c}}

\begin{vvtm}
\begin{ccode}
  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> stepper term: s(s(0)) * s(s(s(0)))
  STEP[1]? :q

  s(s(s(s(s(s(0)))))) : NzNat
  (0.000 sec for parse, 11 rewrites(0.010 sec), 19 matches)
  MULT> reduce s(s(0)) * s(0) .

  -- reduce in MULT : s(s(0)) * s(0)
  s(s(0)) : NzNat
  (0.000 sec for parse, 7 rewrites(0.000 sec), 11 matches)
  MULT> 
\end{ccode}
\end{vvtm}
``\verb|:q|'' forces the system to leave the step mode, as the above
example shows.\index{\texttt{:q}}

For ``\verb|:l|'' and ``\verb|:p|'', see the next section.

\subsection{Controlled Reduction, by Patterns}
\label{sec:p2-control-reduction-pat}

It is possible to stop reductions when a certain pattern is
found.

\begin{bsyntax} \texttt{stop} command \index{\texttt{stop}} \Hline
\texttt{stop} \textit{term} ``\texttt{.}''
\texttt{stop} ``\texttt{.}''
\end{bsyntax}

where a term is a term in the current module context
(Section \ref{sec:p2-current-module}), and may contain variables.
Do not forget the last blank-period stopper. This command causes
reductions to stop when the reductants get to containing subterms
that match the given term.
If no term is given, this restriction is lifted.
Alternatively, you may use \verb|set|\index{\texttt{set}} command,
as\index{\texttt{stop}}\index{\texttt{pattern}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set stop pattern t .
\end{ccode}
\end{vvtm}
where \verb|t| is a term.

\begin{warning}
  This command is fast becoming obsolete, and it is advisable to
  use the above \verb|set| command instead.
\end{warning}

We continue the session with \verb|MULT| (Note that the \verb|step|
switch is still \verb|on|).\index{\texttt{:p}}
\begin{vvtm}
\begin{ccode}
  MULT> set stop pattern 0 * N:Nat .

  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> stepper term: s(s(0)) * s(s(s(0)))
  STEP[1]? :p

  [stop pattern]: (0 * N:Nat)
  STEP[1]? :c

  >> subterm : 0 * s(s(s(0)))
     of term : s(s(s(s(s(s(0))) + (0 * s(s(s(0)))))))
     matches to stop pattern: 0 * N
  << will stop rewriting
  >> stop because matches stop pattern.
  >> stepper term: s(s(s(0))) + (0 * s(s(s(0))))
  STEP[7]? set stop pattern .

  STEP[7]? :c

  s(s(s(s(s(s(0)))))) : NzNat
  (0.010 sec for parse, 11 rewrites(0.030 sec), 19 matches)
  MULT>
\end{ccode}
\end{vvtm}
``\verb|:p|'' prints the term given by \verb|set| command, and
``\verb|:c|'' resumes reduction. The system stopped when a matching
term appeared, as requested. After the restriction was lifted, the
reduction continued uninterrupted.

You may print the current pattern as\index{\texttt{show}}\index{\texttt{stop}}
\begin{vvtm}
\begin{ccode}
  STEP[1]? show stop
  [stop pattern]: (0 * N:Nat)
  STEP[1]? 
\end{ccode}
\end{vvtm}
instead of \verb|:p|. This command can be invoked without entering
the stepper. In fact, pattern restrictions may be used outside the
stepper. For example,\index{\texttt{show}}\index{\texttt{stop}}
\begin{vvtm}
\begin{ccode}
  MULT> set step off

  MULT> set stop pattern 0 * N:Nat .

  MULT> show stop
  [stop pattern]: (0 * N:Nat)

  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> subterm : 0 * s(s(s(0)))
     of term : s(s(s(s(s(s(0))) + (0 * s(s(s(0)))))))
     matches to stop pattern: 0 * N
  << will stop rewriting
  s(s(s(s(s(s(0))) + (0 * s(s(s(0))))))) : NzNat
  (0.000 sec for parse, 6 rewrites(0.010 sec), 12 matches)
  MULT> 
\end{ccode}
\end{vvtm}
The pattern restriction forced the reduction to terminate.
As shown above, \verb|show| command with \verb|stop| argument prints
the specified pattern. You should use this command, instead of ``\verb|:p|''
(the latter is recognised only within the stepper).

\begin{warning}
  It is not possible to specify more than one patterns, or
  more complicated patterns using e.g. regular expressions.
  If demands are strong, the future versions may enhance
  the pattern description facility.
\end{warning}

\subsection{Controlled Reduction, by Number of Steps}
\label{sec:p2-control-reduction-limit}

It is possible to control reductions by limiting rewrite steps.
Enter the stepper again.\index{\texttt{rwt}}\index{\texttt{limit}}
\begin{vvtm}
\begin{ccode}
  MULT> set step on

  MULT> set stop pattern .

  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> stepper term: s(s(0)) * s(s(s(0)))
  STEP[1]? rwt 10

  STEP[1]? :c

  >> aborting rewrite due to rewrite count limit (= 10) <<
  s(s(s(s(s(s(0 * s(s(s(0))))))))) : NzNat
  (0.000 sec for parse, 10 rewrites(0.020 sec), 18 matches)
  MULT> 
\end{ccode}
\end{vvtm}
\verb|rwt| command in the stepper forced the reduction to abort,
after 10 rewrite steps. Note that, unlike ``\verb|:g|'' command,
the system aborted the reduction, not just suspended it.

It is possible to limit rewrite steps outside the stepper.
\index{\texttt{set}}\index{\texttt{rwt}}\index{\texttt{limit}}
\begin{vvtm}
\begin{ccode}
  MULT> set step off

  MULT> set rwt limit 5

  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  >> aborting rewrite due to rewrite count limit (= 5) <<
  s(s(s(s(0) * s(s(s(0)))))) : NzNat
  (0.000 sec for parse, 5 rewrites(0.000 sec), 9 matches)
  MULT> 
\end{ccode}
\end{vvtm}
You should use \verb|set| command, instead of \verb|rwt| command
(the latter is recognised only in the stepper). To lift the
restriction, set the limit to \verb|.|\index{\texttt{show}}\index{\texttt{limit}}
\begin{vvtm}
\begin{ccode}
  MULT> set rwt limit .         

  MULT> show limit
  [rewrite limit]: not specified.

  MULT> reduce s(s(0)) * s(s(s(0))) .

  -- reduce in MULT : s(s(0)) * s(s(s(0)))
  s(s(s(s(s(s(0)))))) : NzNat
  (0.000 sec for parse, 11 rewrites(0.000 sec), 19 matches)
  MULT> 
\end{ccode}
\end{vvtm}
As shown above, \verb|show| command with \verb|limit| argument
prints the specified limit.

If both the pattern and limit restrictions are in force,
the system aborts reductions at the earliest opportunity.

\section{Faster Evaluation}\label{sec:p2-tram-brute}

Such commands as \verb|reduce| treat terms and rewrite rules as
Lisp objects, and the rewrite procedure manipulates these objects
directly. If the rule set is huge, and/or the term is or will grow
large, the system may become uncomfortably slow. A way to overcome
the discomfort is to invest in a faster machine with a larger memory,
of course, but there is another, cheaper way. For faster evaluation,
you may encode rewrite rules into an abstract machine, and
reduce terms by executing that machine, with the following command.

\begin{bsyntax} \texttt{tram} command for evaluation\index{\texttt{tram}}\index{\texttt{reduce}} \Hline
\index{\texttt{execute}}
\texttt{tram} $\{$ \texttt{reduce} $|$ \texttt{execute} $\}$ $[$\texttt{in} \textit{module\_expression} ``\texttt{:}''$]$ \textit{term} ``\texttt{.}''
\end{bsyntax}

\verb|reduce|, \verb|execute| may be abbreviated to \verb|red|, \verb|exec|
respectively.
The command acts like \verb|reduce| or \verb|execute| and reduces
the given term. If the module expression is omitted, the reduction
occurs in the current module.

\begin{warning}
  The compiled code does not distinguish behavioural axioms as such,
  and \verb|reduce| option acts like \verb|breduce| command.
\end{warning}

Upon accepting the command, the system
\begin{itemize}
\item[1.] Compiles the rewrite rules of the module into an abstract
  machine, if they have not been compiled already; Then it
\item[2.] Runs the abstract machine on the given term.
\end{itemize}
The output you get is more or less the same as when \verb|reduce| or
\verb|execute| commands are used. For example, with \verb|MULT|
(Section \ref{exs:mult}), you have
\begin{vvtm}
\begin{ccode}
  MULT> tram reduce s(s(s(0))) * (s(s(s(s(s(0))))) * s(s(s(s(s(0)))))) .
  -- reduce in MULT : s(s(s(0))) * (s(s(s(s(s(0))))) * s(s(s(s(s(0)
      )))))
  s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(
      s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(
      s(s(s(s(s(s(s(s(s(s(s(0))))))))))))))))))))))))))))))))))))))
      ))))))))))))))))))))))))))))))))))))) : NzNat
  (rtime 3 utime 3 stime 0 rewrite 118 gc 0)

  MULT> 
\end{ccode}
\end{vvtm}
For comparison, the corresponding ordinary evaluation works as follows.
\begin{vvtm}
\begin{ccode}
  MULT> reduce s(s(s(0))) * (s(s(s(s(s(0))))) * s(s(s(s(s(0)))))) .

  -- reduce in MULT : s(s(s(0))) * (s(s(s(s(s(0))))) * s(s(s(s(s(0)
      )))))
  s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(
    s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(
    s(s(s(s(s(s(s(s(s(s(0))))))))))))))))))))))))))))))))))))))))))
    ))))))))))))))))))))))))))))))))) : NzNat
  (0.010 sec for parse, 118 rewrites(0.020 sec), 226 matches)
  MULT> 
\end{ccode}
\end{vvtm}
Compilation is done only once, when \verb|tram| command is first used
on the given module.

You may just compile a module as a preparation, by

\begin{bsyntax} \texttt{tram} command for compilation \index{\texttt{tram}} \Hline
\index{\texttt{compile}}
\texttt{tram} \texttt{compile} $[$\texttt{-exec}$]$ $[$\textit{module\_expression}$]$ ``\texttt{.}''
\end{bsyntax}

If the module expression is omitted, the current module is assumed.
If \verb|-exec| is given, transitions as well as equations are
compiled (i.e., for \verb|exec|). For this command,
\verb|-e|, \verb|-all|, and \verb|-a| are all synonymous to \verb|-exec|.

\begin{warning}
  \verb|reduce| and \verb|execute| use different sets of rules.
  Therefore, if you have compiled a module already for \verb|reduce| and
  try \verb|tram| with \verb|execute| option, the system recompile
  the module.
\end{warning}

\begin{warning}
  Do not forget the last period preceded by a blank.
\end{warning}

Compilation into and execution of abstract machines are taken care of
by an indepent program, called \verb|tram| or \verb|brute|. So you have to
tell the system where it is. The command\index{\texttt{switch}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set tram path /home/irene/bin/tram
\end{ccode}
\end{vvtm}
directs the system to the given path for this program. The default is
\begin{vvtm}
\begin{ccode}
  /usr/local/bin/tram
\end{ccode}
\end{vvtm}
\verb|tram| and \verb|brute| have quite different architectures and
they both have limitations. For detail, see README in the distribution
package.

There is another switch related to \verb|tram|, although
you may never use it. The command
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set tram options someoptionsoftram
\end{ccode}
\end{vvtm}
makes the system supply \verb|someoptionsoftram| as options whenever
\verb|tram| is invoked. In normal
usage, you need not know which options \verb|tram| or \verb|brute| takes.

\section{Context Variable}\label{sec:p2-let-command}

To help ease reading and writing terms, a {\em context variable}
\index{context variable} facility is supported.

\begin{bsyntax} \texttt{let} command \index{\texttt{let}} \Hline
\texttt{let} \textit{identifier} ``\texttt{=}'' term ``\texttt{.}''
\end{bsyntax}

The last period preceded by a blank is a must. An identifier
is a character string and a term is a term in the current context
(Section {sec:p2-current-module}).
This command binds the given term to the identifier in the current
context. The example below illustrates the usage, and shows how
to print the binding state.
\begin{vvtm}
\begin{ccode}
  MULT> let a1 = s(0) + (s(s(0)) + s(s(s(0)))) .
  -- setting let variable "a1" to :
      (s(0) + (s(s(0)) + s(s(s(0))))) : Nat

  MULT> let a2 = s(s(s(0))) * (a1 * s(s(s(s(s(0)))))) .
  -- setting let variable "a2" to :
      (s(s(s(0))) * ((s(0) + (s(s(0)) + s(s(s(0))))) * s(s(s(s(s(0)))))))
       : Nat

  MULT> reduce a1 .

  -- reduce in MULT : s(0) + (s(s(0)) + s(s(s(0))))
  s(s(s(s(s(s(0)))))) : NzNat
  (0.000 sec for parse, 5 rewrites(0.010 sec), 8 matches)
  MULT> reduce a2 .


  -- reduce in MULT : s(s(s(0))) * ((s(0) + (s(s(0)) + s(s(s(0)))))
       * s(s(s(s(s(0))))))
  s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(
    s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(
    s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(0))))))))))))
    )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
    ))))))))))))))) : NzNat
  (0.000 sec for parse, 145 rewrites(0.010 sec), 277 matches)
  MULT> show term a1
  (s(0) + (s(s(0)) + s(s(s(0))))) : Nat

  MULT> 
\end{ccode}
\end{vvtm}
A context variable, once bound, may be used as a subterm in
commands \verb|reduce|, \verb|parse|, \verb|let| itself, etc.
Note that \verb|let| binds syntactically.
\verb|reduce| commands above did not change the values of
\verb|a1| or \verb|a2|. \verb|show| command was used to
print the binding of \verb|a1|. To list all the bindings, use
\verb|show| command again:
\index{\texttt{show}}\index{\texttt{let}}\index{\texttt{binding}}
\begin{vvtm}
\begin{ccode}
  MULT> show let
  [bindings] 
  a2 = s(s(s(0))) * ((s(0) + (s(s(0)) + s(s(s(0))))) * s(s(s(s(s(0))))))
  a1 = s(0) + (s(s(0)) + s(s(s(0))))

  MULT> 
\end{ccode}
\end{vvtm}
\verb|let| in the above command may be replaced by \verb|binding|.

Context variables are local to each context. Continuing the above session,
\begin{vvtm}
\begin{ccode}
  MULT> select SIMPLE-NAT

  SIMPLE-NAT> let a1 = 0 .
  -- setting let variable "a1" to :
      0 : Zero

  SIMPLE-NAT> show let
  [bindings] 
  a1 = 0

  SIMPLE-NAT> select MULT

  MULT> show let
  [bindings] 
  a2 = s(s(s(0))) * ((s(0) + (s(s(0)) + s(s(s(0))))) * s(s(s(s(s(0))))))
  a1 = s(0) + (s(s(0)) + s(s(s(0))))

  MULT> 
\end{ccode}
\end{vvtm}
As shown above, context variables in \verb|MULT| and \verb|SIMPLE-NAT|
are kept separately, and the same name may be used for different
bindings.

\begin{warning}
  As explained, context variables belong to individual modules. If you
  attempt to bind a context variable without setting a current module,
  the system complains ---  it has no way to know whither the term came.
\end{warning}

By the way, you encountered not so small a term when \verb|a2| was
reduced. It is very simple for the system to print such terms accurately,
they may sometimes cause you nausea or headache. If you expect
the terms to be large, and need to see only their broad outline,
you can use a switch.
\index{\texttt{print}}\index{\texttt{depth}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set print depth 10
\end{ccode}
\end{vvtm}
tells the system to print terms up to the depth 10 (as trees).
The default is ``unlimited'', and the depth of ``\verb|.|'' is
interpreted as such. Continuing the above session, then, you get
\begin{vvtm}
\begin{ccode}
  MULT> set print depth 10

  MULT> reduce a2 .

  -- reduce in MULT : s(s(s(0))) * ((s(0) + (s(s(0)) + s(s(s(0)))))
       * s(s(s(s(s(0))))))
  s(s(s(s(s(s(s(s(s(s( ... )))))))))) : NzNat
  (0.000 sec for parse, 145 rewrites(0.010 sec), 277 matches)
  MULT> set print depth .

  MULT> reduce a2 .

  -- reduce in MULT : s(s(s(0))) * ((s(0) + (s(s(0)) + s(s(s(0)))))
       * s(s(s(s(s(0))))))
  s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(
    s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(
    s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(s(0))))))))))))
    )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
    ))))))))))))))) : NzNat
  (0.000 sec for parse, 145 rewrites(0.010 sec), 277 matches)
  MULT> 
\end{ccode}
\end{vvtm}

\section{Flexible Typing and Error Handling}\label{sec:p2-flexible-typing}

\cafeobj~has a strong typing discipline. Although useful for static
analyses, strong typing is sometimes too restrictive. There are cases
where type mismatch could never happen, even though expressions are
syntactically illegal. Or, rephrasing in the lexicon of TRS's,
apparently ill-formed terms may reduce to well-formed terms.
\cafeobj~appraises such phenomena, to offer
a ``reasonably'' strong typing discipline.

Consider a case when you try to apply an operator
\begin{vvtm}
\begin{ccode}
  op f : S -> S'
\end{ccode}
\end{vvtm}
to a term of sort \verb|T|. \verb|S| and \verb|T| differ, so such an
attempt should be rejected. Unless, that is, the relation
\begin{vvtm}
\begin{ccode}
  S < T
\end{ccode}
\end{vvtm}
holds. Note well that, if
\begin{vvtm}
\begin{ccode}
  T < S
\end{ccode}
\end{vvtm}
holds, \verb|f| can definitely apply to terms of \verb|T|. That is
an essence of order-sorted logic. What we are saying here is that,
if \verb|S| is a subsort of \verb|T| and a term \verb|t| is
of sort \verb|T|, \verb|f(t)|
may become (by evaluation) a well-formed term, since \verb|t| may
reduce to a term \verb|t'| of sort \verb|S|.

One way to accommodate the above case is to use so-called retract operators
(c.f. \cite{OBJ}).
\cafeobj~has adopted another approach. Let us see how it works.

\subsection{Factorial of Rationals ($!?$)}

A usual definition of the factorial is as follows.
\label{exs:fact}
\begin{vvtm}
\begin{ccode}
  module FACT {
   protecting (RAT)
   op _! : Nat -> NzNat
   eq 0 ! = 1 .
   ceq N:Nat ! = N * (N - 1 !) if N > 0 .
  }
\end{ccode}
\end{vvtm}
where the factorial is declared as a postfix operator \verb|_!|, as
is the convention. \verb|RAT| is a built-in module of rationals.
You may point out that rationals are irrelevant to the factorial. They
are, and this module is certainly artificial: it is only declared to show
that we can compute the factorial of rationals. Well, sometimes.

The sort ordering in \verb|RAT| defines the graph
\begin{center}
% \begin{diagram}
% &&\mbox\texttt{Rat} \\  
% &\ldTo&\dTo \\
% \mbox\texttt{NzRat} && \mbox\texttt{Int} \\
% \dTo&\ldTo&\dTo \\
% \mbox\texttt{NzInt} &&\mbox\texttt{Nat} \\
% \dTo&\ldTo&\dTo\\
% \mbox\texttt{NzNat} &&\mbox\texttt{Zero}
% \end{diagram}
\end{center}
All these sorts are of familiar kind:
\verb|Rat|, \verb|Int|, \verb|Nat| are the sorts of rationals, integers, and
natural numbers respectively, and \verb|Nz| means non-zero. \verb|Zero| is
a one-point set, containing 0. Unlike our \verb|SIMPLE-NAT|, naturals may
be written 1, 43, 107, etc. in this built-in module.

\verb|RAT| defines the division
\begin{vvtm}
\begin{ccode}
   op _/_ : Rat NzRat -> Rat
\end{ccode}
\end{vvtm}
Now
\begin{vvtm}
\begin{ccode}
   (I:Int / J:Int)!
\end{ccode}
\end{vvtm}
is ill-formed, since \verb|I / J| is a rational, while \verb|_!| takes
only natural number arguments. But \cafeobj~parses it as well-formed,
as follows.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> parse in FACT : (I:Int / J:Int)! .

  ((I / J) !) : ?Rat
\end{ccode}
\end{vvtm}
Recall that the result of parsing is a pair of a parenthesised term and
its least sort. Here the least sort is shown to be a questionable
\verb|?Rat|. The naming convention is implementation-dependent and
should not bother you, but you should be bothered to know to that
the name denotes an {\em error sort}\index{error sort}
over \verb|Rat|, i.e. a sort consisting
of ``error'' elements as well as rationals.

For any integers \verb|I| and \verb|J|, then, \verb|(I / J)!| is well-formed,
although its sort has a dubious name. It follows that
\begin{vvtm}
\begin{ccode}
   (4 / 2)!
\end{ccode}
\end{vvtm}
is well-formed. Try parsing, then evaluating the term, and you get
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select FACT     

  FACT> parse (4 / 2)! .

  ((4 / 2) !) : ?Rat
  FACT> reduce (4 / 2)! .

  -- reduce in FACT : 4 / 2 !
  2 : NzNat
  (0.000 sec for parse, 14 rewrites(0.020 sec), 24 matches)
  FACT>
\end{ccode}
\end{vvtm}
The original term is parsed as a term of sort \verb|?Rat|, as before, and
the result of evaluation is a term \verb|2| of sort \verb|NzNat|.
Indeed, this result is the 2's factorial, i.e. $4/2$'s factorial.
And \verb|NzNat| is not dubious.

On the other hand, if you supply a meaningless term, the result remains
dubious.
\begin{vvtm}
\begin{ccode}
  FACT> reduce (4 / 3)! .

  -- reduce in FACT : 4 / 3 !
  4/3 ! : ?Rat
  (0.010 sec for parse, 1 rewrites(0.000 sec), 1 matches)
  FACT>
\end{ccode}
\end{vvtm}
To summarise, in \cafeobj,
\begin{itemize}
\item[(1)] If a term is ill-formed but potentially well-formed,
  it is regarded as a well-formed term of questionable sort.
\item[(2)] On evaluation, the potential is investigated.
  If the result is a term which is unquestionably well-formed,
  it acquires a full citizenship. Otherwise it remains an outcast.
\end{itemize}

\subsection{Stacks}

Stacks are ubiquitous topics in our
community, especially in discussing exception/error handling. The
main reason is that their definition is compact, yet reveals (or
conceals) how \verb|top(empty)|, a raving exception, is treated.
The module below declares a sort of non-empty stacks, and
\verb|top| and \verb|pop| are declared on that sort, not on the sort of
all the stacks. In effect, \verb|top| and \verb|pop| are partial
operators.\index{stack}\index{partial operator}\label{exs:stack-of-nat}
\begin{vvtm}
\begin{ccode}
  module STACK-OF-NAT {
   [ NeStack < Stack ]
   protecting (SIMPLE-NAT) 
   op empty : -> Stack
   op push : Nat Stack -> NeStack
   op top_ : NeStack -> Nat
   op pop_ : NeStack -> Stack
   eq top push(X:Nat, S:Stack) = X .
   eq pop push(X:Nat, S:Stack) = S .
  }
\end{ccode}
\end{vvtm}
``\verb|top push(s(s(0)), empty)|'' is well-formed. It parses and reduces as
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select STACK-OF-NAT

  STACK-OF-NAT> parse top push(s(s(0)), empty) .

 (top push(s(s(0)),empty)) : Nat
  STACK-OF-NAT> reduce top push(s(s(0)), empty) .

  -- reduce in STACK-OF-NAT : top push(s(s(0)),empty)
  s(s(0)) : NzNat
  (0.000 sec for parse, 1 rewrites(0.000 sec), 1 matches)
  STACK-OF-NAT> 
\end{ccode}
\end{vvtm}
Without introducing error sorts, the term
``\verb|top pop push(s(0), push(s(s(0)), empty))| is ill-formed:
\verb|top| requires non-empty stacks as arguments, but the coarity of
\verb|pop| is \verb|Stack|, which contains the empty stack.
\cafeobj~regards this term,
like \verb|(4 / 2)!|, as well-formed, but of an error sort \verb|?Nat|.
On evaluation, it reduces to a well-formed term of a valid sort.
\begin{vvtm}
\begin{ccode}
  STACK-OF-NAT> parse top pop push(s(0), push(s(s(0)), empty)) .

  (top (pop push(s(0),push(s(s(0)),empty)))) : ?Nat
  STACK-OF-NAT> reduce top pop push(s(0), push(s(s(0)), empty)) .

  -- reduce in STACK-OF-NAT : top (pop push(s(0),push(s(s(0)),empty)))
  s(s(0)) : NzNat
  (0.000 sec for parse, 2 rewrites(0.000 sec), 2 matches)
  STACK-OF-NAT> 
\end{ccode}
\end{vvtm}
A meaningless term, as before, remains meaningless.
\begin{vvtm}
\begin{ccode}
  STACK-OF-NAT> parse top pop push(s(0), empty) .

  (top (pop push(s(0),empty))) : ?Nat
  STACK-OF-NAT> reduce top pop push(s(0), empty) .

  -- reduce in STACK-OF-NAT : top (pop push(s(0),empty))
  top empty : ?Nat
  (0.010 sec for parse, 1 rewrites(0.000 sec), 1 matches)

STACK-OF-NAT> 
\end{ccode}
\end{vvtm}

\subsection{Handling Errors as Errors}

The above definition of natural number stacks does not say much about
what to do with errors. It simply demarcates the error boundary.
If you want to be more specific about handling errors,
a standard way is to declare specific error elements
(constants), and equalise errors to them. In case of
the stacks, the code would look something like
\begin{vvtm}
\begin{ccode}
  ...
  op * : -> ?Nat
  op * : -> ?Stack
  ...
  eq top empty = * .
  eq pop empty = * .
  ...
\end{ccode}
\end{vvtm}
where \verb|*| is meant to be a bottom element. A more elaborate
way is to declare such constants as
\begin{vvtm}
\begin{ccode}
  op zero-divisor : -> ?Nat
  op top-of-empty-stack : -> ?Nat
\end{ccode}
\end{vvtm}
They are intended to be error messages.

An error sort is automatically declared for each connected component of
the sort graph, and has an internal name that starts with ``\verb|?|''.
In the examples of factorials and stacks, the names derived from single
sorts, as \verb|?Rat| and \verb|?Nat|. In general, an error sort may
have a complicated name like
\begin{vvtm}
\begin{ccode}
  ?SortA+SortB+SortC
\end{ccode}
\end{vvtm}
The ``summands'' of this name are maximal sorts in a relevant connected
component. In making explicit references, you may use a more compact
notation: just put a question mark before a sort name in connected
components. For example,
if you declared
\begin{vvtm}
\begin{ccode}
  [ A < B, A < C ]
\end{ccode}
\end{vvtm}
the error sort name is internally \verb|?B+C|, but may be referred to
as either \verb|?A|, \verb|?B|, or \verb|?C|.

\begin{warning}
  Unlike the former versions, the current version admits error sorts,
  such as \verb|?Nat|, in operator declarations.
  Since names of error sorts --- in fact, their
  existence at all --- are implementation dependent,
  you should avoid mentioning error sorts unless absolutely necessary.
\end{warning}

\chapter{Operator Attributes}\label{sec:p2-op-properties}

Some properties of operators, such as associativity, can be stated as
axioms, but if they are so common, it is convenient to be able to
use shorthand notations. Moreover, some properties, such as
commutativity, are better {\em not} to be given by axioms,
since, if regarded as rewrite rules, such axioms violate
desirable properties of the TRS. \cafeobj~has a construct for endowing
operators with common properties. Such properties are called
{\em operator attribute\/}s\index{operator attribute}
\index{attribute (of operators)}. Some of them
affect denotational semantics; others affect only parsing; yet others
concern solely with evaluation.

Operator attributes are specified with an optional construct of
operator declarations that were explained in Section \ref{sec:p2-operator}.

\begin{bsyntax} operator declaration with attributes \index{\texttt{op}} \Hline
\texttt{op} \textit{operator\_symbol} ``\texttt{:}'' \textit{list\_of\_sort\_names} ``\texttt{->}'' \textit{sort\_name} ``\texttt{\{}'' \textit{attribute\_list} ``\texttt{\}}''
\end{bsyntax}

where operator symbols et al. are as before (Section \ref{sec:p2-operator}).
We delayed the introduction of this construct, since it is
better explained after evaluation commands.

An attribute list is a list of operator attributes separated by blanks.
An attribute is either (1) an {\em equational theory attribute},
\index{equational theory attribute} which defines an equivalence relation
among terms, (2) a {\em parsing attribute}\index{parsing attribute}, which
specifies connectivity,
(3) an {\em evaluation attribute}, which controls the evaluation
procedure, or (4) neither of these.

Operator declarations introduced by \verb|ops|, \verb|bop|, \verb|bops|,
\verb|pred| may also have this optional construct.

\section{Equational Theory Attribute}\label{sec:p2-equational-theory}
\cafeobj~admits four equational theory attributes, as follows. For
an infix operator $+$,
\begin{itemize}
\item[(1)] Associativity, or $(x + y) + z$ = $x + (y + z)$ for any
  $x$, $y$, and $z$. \\
  Specified with \verb|associative| or \verb|assoc|.
  \index{associativity}\index{\texttt{associative}}\index{\texttt{assoc}}
\item[(2)] Commutativity, or $x + y = y + x$ for any $x$ and $y$. \\
  Specified with \verb|commutative| or \verb|comm|.
  \index{commutativity}\index{\texttt{commutative}}\index{\texttt{comm}}
\item[(3)] Idempotency, or $x + x = x$ for any $x$. \\
  Specified with \verb|idempotent| or \verb|idem|.
  \index{idempotency}\index{\texttt{idempotent}}\index{\texttt{idem}}
\item[(4)] Existence of the identity (here written $0$), or
  $0 + x = x$ and $x + 0 = x$ for any $x$. \\
  Specified with ``\verb|id: 0|''.
  \index{identity}\index{\texttt{id:}}
\end{itemize}

\subsection{Associativity}

We proceed to a couple of examples for futher illustration.
The conjunction ``\verb|_and_|'' is associative.
In \cafeobj, it is written as
\index{\texttt{assoc}}
\begin{vvtm}
\begin{ccode}
   op _and_ : Bool Bool -> Bool { assoc }
\end{ccode}
\end{vvtm}
which means
\begin{itemize}
\item[-] No ambiguity arises with or without parentheses. For example,
  \begin{vvtm}
\begin{ccode}
     true and false and true
  \end{ccode}
\end{vvtm}
  has two parses
  \begin{vvtm}
\begin{ccode}
     (true and false) and true
     true and (false and true)
  \end{ccode}
\end{vvtm}
  but by associativity, they are equal.
\item[-] During evaluation, terms are matched modulo
  \index{modulo (equatioanl theory)}
  associativity. For example, in evaluating \newline
  ``\verb|(true and false) and true|'' in the presence of
  \begin{vvtm}
\begin{ccode}
     eq true and X:Bool = X .
  \end{ccode}
\end{vvtm}
  the given term does not match the lefthand side as it is, since the first
  argument is not \verb|true|. But by associativity,
  the term equals ``\verb|true and (false and true)|'', and this
  equivalent term does match the lefthand side. Matching modulo
  associativity is a procedure to find a matching substitution under
  arbitrary arrangement of parentheses.
\end{itemize}
The built-in equality operator ``\verb|_==_|''
(Section \ref{sec:p2-equality-pred}) takes care of associativity.
For example,
\begin{vvtm}
\begin{ccode}
   true and (false and true) == (true and false) and true
\end{ccode}
\end{vvtm}
evaluates to \verb|true|.

\verb|assoc| makes sense only when the operator is binary,
with arity of the form ``\verb|A A|'' and coarity \verb|C| such that
\verb|C < A|.

\begin{warning}
  Formerly, \cafeobj~admitted the cases when the arity
  consists of different sorts. You are warned if the above stricter
  condition is violated.
\end{warning}

\begin{warning}
  The system assumes an operator with \verb|assoc| attribute to
  be right associative (Section \ref{sec:p2-syntactic-properties}),
  unless declared otherwise.
\end{warning}

\subsection{Commutativity}
The conjunction is also commutative. In \cafeobj, it is written as
\index{\texttt{comm}}
\begin{vvtm}
\begin{ccode}
   op _and_ : Bool Bool -> Bool { assoc comm }
\end{ccode}
\end{vvtm}
Commutativity may be specified with the equation
\begin{vvtm}
\begin{ccode}
   eq X:Bool and Y:Bool = Y and X .
\end{ccode}
\end{vvtm}
which is fine as an equation. As a rewrite rule, however, it is
diabolically problematic, since it generates infinite rewrite sequences.
For this reason, commutativity should be stated by operator attribute.

Like \verb|assoc|, \verb|comm| affects evaluation. For example, the
term ``\verb|false and true|'' does not match the lefthand side of
\begin{vvtm}
\begin{ccode}
   eq X:Bool and false = false .
\end{ccode}
\end{vvtm}
but an equivalent term \verb|true and false| does.

``\verb|_==_|'' takes care of commutativity as well as associativity, so
\begin{vvtm}
\begin{ccode}
   true and (false and true) == (true and true) and false
\end{ccode}
\end{vvtm}
evaluates to \verb|true|.

\verb|comm| makes sense only when the operator is binary and its
arity sorts are the same.

\begin{warning}
  Formerly, \cafeobj~admitted the cases when
  the arity sorts have a common supersort.
\end{warning}

\subsection{Identity}
``\verb|_and_|'' has \verb|true| as (left and right) identity, which is
written in \cafeobj~as\index{\texttt{id:}}
\begin{vvtm}
\begin{ccode}
   op _and_ : Bool Bool -> Bool { assoc comm id: true }
\end{ccode}
\end{vvtm}
The attribute ``\verb|id: true|'' is equivalent to the following equations.
\begin{vvtm}
\begin{ccode}
   eq true and X:Bool = X .
   eq X:Bool and true = X .
\end{ccode}
\end{vvtm}
(In fact, since \verb|comm| is also given, one of the above is enough.)
Identity attributes affect evaluation. Under the above operator
declaration, \verb|false and true| is, {\em without} evaluation,
identified with \verb|false|.

``\verb|id:|'' makes sense only when the operator is binary,
the arity sorts and the coarity sort are the same, and the identity term
belongs to that sort.

\begin{warning}
  Formerly, \cafeobj
  admitted the cases when the coarity sort is different.
%  The current implementation does not check the above condition.
\end{warning}

\begin{warning}
  The current implementation of \cafeobj~applies a completion procedure
  to realise matching modulo identity. The procedure often generates a
  great many of equations, leading to severe performace degeneration,
  or even to non-termination. To prohibit unwanted completion,
  use ``\verb|idr:|''\index{\texttt{idr:}}, instead of ``\verb|id:|''.
  This attribute has the the same meaning as ``\verb|id:|''.
\end{warning}

\subsection{Idempotency}

That ``\verb|_and_|'' is idempotent is stated as follows.\index{\texttt{idem}}
\begin{vvtm}
\begin{ccode}
  op _and_ : Bool Bool -> Bool { assoc comm id: true idem }
\end{ccode}
\end{vvtm}
\verb|idem| is equivalent to the equation
\begin{vvtm}
\begin{ccode}
  eq X:Bool and X = X .
\end{ccode}
\end{vvtm}
Idempotency affects evaluation. For example,
``\verb|true and true|'' and \verb|true| matches modulo idempotency.

\verb|idem| makes sense only when the operator is binary and the
arity sorts and the coarity sort are the same.

\begin{warning}
  Formerly there was no explicit condition.
\end{warning}

\begin{warning}
In the current implementation, an equation like the above is
actually added. The system sometimes misbehaves; the only certainty
about idempotency is that matching modulo the {\em combination} of
associativity, commutativity, and idempotency works correctly.
\end{warning}

\subsection{Inheriting Equational Theory Attributes}

Equational theory attributes are
inherited by operators, if they have the same name and are
declared on lower sorts. For example, when you declare
\begin{vvtm}
\begin{ccode}
  [ Nat < Int ]
  op _+_ : Nat Nat -> Nat 
  op _+_ : Int Int -> Int { assoc }
\end{ccode}
\end{vvtm}
the operator ``\verb|_+_|'' on \verb|Nat| is assumed associative.
Since a subsort is a subset, such attribute inheritance is quite natural:
if associativity holds for all the integers, it a forteriori holds for
all the natural numbers.
As a special case, an identity is inherited only when the identity
term belongs to the lower sort.

\section{Parsing Attribute}\label{sec:p2-syntactic-properties}

Parsing attributes help disambiguate parsing. They are either
\begin{itemize}
\item[(1)] Precedence\index{precedence}, specified by
  ``\verb|prec:| integer'', or
  \index{\texttt{prec:}}
\item[(2)] Left or right associativity, specified by \verb|l-assoc| or
  \verb|r-assoc|, respectively.
 \index{\texttt{r-assoc}}\index{\texttt{l-assoc}}
 \index{left associativity}\index{right associativity}
\end{itemize}

\subsection{Precedence}

A precedence is an integer, and lesser precedences indicate stronger
connectivity. For example,\index{\texttt{prec:}}
\begin{vvtm}
\begin{ccode}
   op _+_ : Int Int -> Int { prec: 33 }
   op _*_ : Int Int -> Int { prec: 31 }
\end{ccode}
\end{vvtm}
states that ``\verb|_*_|'' connects stronger than ``\verb|_+_|'', and
``\verb|1 + 2 * 3|'' parses as ``\verb|1 + (2 * 3)|''.

The default precedences depend on term constructs.
\begin{itemize}
\item Standard operators have precedence 0. Hence the term of
 the form \verb|f(a)| connects strongest.
\item When an operator is mixfix,
 \begin{itemize}
 \item If the operator symbol does not start or end with ``\verb|_|'',
  that is,
  no argument appears outside the term construct, the precedence is zero.
  An example is a singleton operator ``\verb|{_}|'';
 \item if it is a prefix unary operator, the precedence is 15.
  The unary ``\verb|-_|'' offers an example;
 \item Otherwise, the precedence is 41.
 \end{itemize}
\end{itemize}
Let us show examples.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> module PREC-TEST {
    [ S ]
    op _+_ : S S -> S { prec: 33 }
    op _*_ : S S -> S { prec: 31 }
    op -_ : S -> S
    }

  -- defining module PREC-TEST...._* done.
  CafeOBJ> select PREC-TEST

  PREC-TEST> parse X:S + Y:S * Z:S .

  (X + (Y * Z)) : S
  PREC-TEST> parse - X:S + Y:S .

  ((- X) + Y) : S
  PREC-TEST>       
\end{ccode}
\end{vvtm}
According to the default rules, ``\verb|-_|'' has precedence 15,
so connects stronger than ``\verb|_+_|''. Hence the result of the
second parse.

\begin{warning}
  The current implementation accepts precedences between 0 and
  127 (inclusive). Out-of-bound precedences cause warnings,
  and are ignored.
\end{warning}

\subsection{Left/Right Associativity}

\verb|l-assoc| states that the operator, which must be binary,
associates to the left, and \verb|r-assoc| to the right. A
typical usage is as follows. Under the declaration
\begin{vvtm}
\begin{ccode}
  op _+_ : S S -> S
\end{ccode}
\end{vvtm}
``\verb|X:S + X + X|'' has two parses
\begin{vvtm}
\begin{ccode}
  (X + X) + X
  X + (X + X)
\end{ccode}
\end{vvtm}
If you declare\index{\texttt{l-assoc}}
\begin{vvtm}
\begin{ccode}
   op _+_ : S S -> S { l-assoc }
\end{ccode}
\end{vvtm}
the parse is uniquely determined as ``\verb|(X + X) + X|'', while
\index{\texttt{r-assoc}}
\begin{vvtm}
\begin{ccode}
   op _+_ : S S -> S { r-assoc }
\end{ccode}
\end{vvtm}
dictates the parse to be ``\verb|X + (X + X)|''.

\begin{warning}
When equational-theoretic associativity \verb|assoc|\index{\texttt{assoc}}
is declared,
the system has to decide how to decide connectivity. In that case,
``\verb|X + (X + X)|'' is equal to ``\verb|(X + X) + X|'' anyway, but
it is necessary to decide on one or the other,
to store and manipulate terms. In the current implementation,
the system assumes right associativity.
\end{warning}

Left/right associativity is allowed only on operators whose
arities are both supersorts of the coarity.

\begin{warning}
  Note that the conditions for \verb|assoc| and for \verb|l-assoc|,
  \verb|r-assoc| differ. \verb|l-assoc| or \verb|r-assoc| is a
  parsing instruction. There is no inherent reason to
  prohibit these attributes, as long as you feel like it.
  In fact, the above condition only states that, if it does not
  hold, the attribute is almost meaningless.
\end{warning}

\section{Constructor Attribute}\label{sec:p2-constructor-attribute}

The attribute \texttt{constr}\index{\texttt{constr}}\index{constructor (attribute)}
states that the operator is a constructor of
the coarity sort. For example,
\begin{vvtm}
\begin{ccode}
  op nil : -> List { constr }
  op __ : List List -> List { constr }
\end{ccode}
\end{vvtm}
states that \verb|nil| and \verb|__| are constructors of \verb|List|.
The idea of constructors is very important for many purposes, especially
for theorem proving. The current system, however, does not take advantage of
this concept in any way. To the system, \verb|constr| is a comment.

\section{Evaluation Strategy}\label{sec:p2-rew-strategy}

\cafeobj~allows the user to specify evaluation strategies of terms.
In general, evaluation is nondeterministic. In selecting which rule to
apply to which subterm, there is a certain license. And the selection
affects performance. It may even decide whether the evaluation terminates.

\subsection{E-Strategy Attribute}

Many recent functional programming languages are using lazy evaluation
strategies. There are several arguments for this trend, but unfettered
laziness
is not recommended, like in everyday life. One way to avoid its harmful
effects is to incorporate in compilers a mechanism to intermingle eager
evaluation strategies, so long as it does not change the results of
computation. To see if it affects the results, strictness analyses are
employed.

In \cafeobj, you need not be thoroughly lazy or eager. It allows you to
assign different strategies to different operators. This means that
you can have the best of both worlds, or eat and have a cake at once.
Moreover, the system computes
default strategies case by case, based on a rapid strictness analysis.

In accordance to a certain folklore, we sometimes say
{\em E-strategy}\index{E-strategy} for evaluation
strategy\index{evaluation strategy}. E-strategies are operator
attributes, and are written in this form:

\begin{bsyntax} evaluation strategy \index{\texttt{strat:}} \Hline
\texttt{strat:} ``\texttt{(}'' \textit{integer\_list} ``\texttt{)}''
\end{bsyntax}

An integer list is a list of integers separated by blanks.
Each integer in the list represents an argument. 1 is
the first argument, 2 is the second, and so on, and 0 is
the whole term.

E-strategies determine the order of evaluation.
As an informative example, a built-in conditional is
declared as follows.
\begin{vvtm}
\begin{ccode}
  op if_then_else_fi : Bool Int Int -> Int { strat: (1 0) }
\end{ccode}
\end{vvtm}
This E-stragety ordains that the first argument (conditional part) be
evaluated first, then the whole argument. Notice that the second
and third arguments (\verb|then| and \verb|else| parts) do not appear in
the list. These arguments are not evaluated, unless the whole term is
evaluated and they are no longer arguments. Depending on the result of
evaluating the first argument, one of these arguments is entirely
irrelevant to the final result, so this strategy is clearly reasonable.

Another example is an eager strategy.
\begin{vvtm}
\begin{ccode}
  op _+_ : Int Int -> Int { strat: (1 2 0) }
\end{ccode}
\end{vvtm}
The E-strategy requires the two arguments be evaluated before the whole
term.

\subsection{Default Strategy}

If no explicit E-strategy is given, the default strategy is computed
as follows. For each argument,
\begin{quote}
  Evaluate the argument before the whole term,
  if there is a rewrite rule that defines the operator such that,
  in the place of the argument, a non-variable term appears.
\end{quote}
For example, given a binary operator \verb|f| and suitable variables
\verb|X| and \verb|Y|, in the place of the first argument is
a variable in
\begin{vvtm}
\begin{ccode}
  eq f(X,Y) = h(X) .
\end{ccode}
\end{vvtm}
while it does not in
\begin{vvtm}
\begin{ccode}
  eq f(g(X),Y) = h(Y) .
\end{ccode}
\end{vvtm}
If all the rewrite rules are of the former type, the first argument
need not be evaluated immediately. Since any term (of a relevant sort)
matches a variable, matching possibilities are unaffected. Furthermore,
if the only rewrite rule defining \verb|f| is
\begin{vvtm}
\begin{ccode}
  eq f(X,Y) = h(Y) .
\end{ccode}
\end{vvtm}
you are well advised to evaluate it later (or never):
the righthand side does not contain \verb|X|, so evaluating it is futile.

On the other hand, if there are rules that contain non-variable terms in
the argument place, the result of evaluating the argument affects
matchability, so it is safe to evaluate it first.

\begin{warning}
  To be on the safe side, the default strategy always ends with
  \verb|0|. Former versions added last zeros even for
  user-supplied stategies. We concluded that this practice
  reminded us of overprotective nannies, and abandoned it.
\end{warning}

If an operator definition is recursive, \cafeobj~may ignore an explicit
E-strategy, and apply recursive rules successively. This is a kind of
optimisation. To avoid this behaviour, give an E-strategy that does not
have \verb|0| at the head of the list.

\subsection{Lazy Evaluation}

\cafeobj~provides two ways to specify lazy evaluation.
\begin{itemize}
\item[a.] Omit the arguments to be evaluated later, or
\item[b.] Put the corresponding negative integers.
\end{itemize}
Delayed \verb|cons| is thus declared as either
\begin{vvtm}
\begin{ccode}
  op cons : Sexp Sexp -> Sexp { strat: (0) } -- (a)
\end{ccode}
\end{vvtm}
or
\begin{vvtm}
\begin{ccode}
  op cons : Sexp Sexp -> Sexpt { strat: (-1 -2) } -- (b)
\end{ccode}
\end{vvtm}
With the former declaration, both arguments are not evaluated unless
they get outside of \verb|cons|. For example, suppose
\verb|car| is defined as
\begin{vvtm}
\begin{ccode}
  op car : Sexp -> Sexp { strat: (1 0) }
  vars X Y : Sexp
  eq car(cons(X,Y)) = X . -- *
\end{ccode}
\end{vvtm}
and you try to reduce the term
\begin{vvtm}
\begin{ccode}
  car(cons(1 + 0, nil))
\end{ccode}
\end{vvtm}
where \verb|nil| is the usual constant. According to the given E-strategies,
\begin{itemize}
\item[1.] The argument of \verb|car| is to be evaluated first.
\item[2.] But the argument is dominated by \verb|cons|, whose
  arguments are not to be evaluated, since \verb|1|, \verb|2| are
  not in the E-strategy. So ``\verb|cons(1 + 0, nil)|'' is
  returned as it is.
\item[3.] The evaluation for \verb|car| continues, and the next
  argument in the E-strategy --- in fact \verb|0|, the whole term ---
  is to be evaluated.
\item[4.] Using the equation marked \verb|*|, the whole term is
  rewritten to ``\verb|1 + 0|''.
\item[5.] Evaluation continues with this term.
\end{itemize}

With the declaration \verb|(b)|, both arguments are not evaluated until
so forced. Evaluation is forced, when the argument is involved in
matching. For example, to see the applicability of the equation (rewrite
rule)
\begin{vvtm}
\begin{ccode}
  eq cadr(cons(X,cons(Y,Z))) = Y .
\end{ccode}
\end{vvtm}
it is necessary to know whether the second argument of the outer \verb|cons|
is dominated by \verb|cons|. Suppose a term has been rewritten so
far to
\begin{vvtm}
\begin{ccode}
  cadr(cons(1,cdr(cons(2,cons(3,nil)))))
\end{ccode}
\end{vvtm}
This term does not match the lhs as it is, because the second argument of
the outmost \verb|cons| is dominated by \verb|cdr|, not by \verb|cons|.
It does match, however, if the second argument is reduced (with the
usual rule for \verb|cdr|) to \verb|cons(3,nil)|. \verb|-2| in the
strategy states
that the second argument is to be evaluated just at such moments.

Negative integers cannot be used if the operator is declared
associative or commutative. In such cases, reduction ``on demand'', as
explained above, is nigh impossible to implement.

%\begin{warning}
%  The lazy mechanism with negative integers no longer works.
%\end{warning}

\subsection{Interpreting E-Strategies}

To understand the exact meaning of E-strategies, it is instructive to
know the overall algorithm of evaluation. It is shown below.
Remember that an E-strategy is a list of integers.

Given a term $t$,
\begin{itemize}
\item[]1. Let $l$ be the E-strategy of the dominant operator of $t$.
\item[]2. If $l$ is empty, exit with $t$ as result. Otherwise, let
  $n$ be the first element of $l$.
  \begin{itemize}
  \item[]2-1. If $n = 0$, search a rewrite rule applicable to the whole
    $t$. If one such is found, replace $t$ with the substitution
    instance $t'$, and go back to 1.
  \item[]2-2. If $n > 0$, call this procedure recursively with the $n$-th
    argument of $t$ as input. Replace the argument with the result, and
    proceed to 3.
  \item[]2-3. If $n < 0$, mark the $-n$-th argument of $t$ as ``on demand'',
    and proceed to 3.
  \end{itemize}
\item[]3. Remove the first element from $l$ and go back to 2.
\end{itemize}
Note that, after the step 2-1., the control is back to 1., and the rest
of the current strategy is discarded.
Note also that, when a negative integer appears,
the corresponding argument is just marked and nothing else is done.
The mark reveals its effects only during matching.

\section{Memo}\label{sec:p2-memo-attribute}

To evaluate similar terms repetitively is tedious to humans,
but acceptable to the system. To evaluate {\em the same} terms repetitively,
however, is sometimes too much, even to the system. It silently
complains, by taking long time in responding. For the sake of
efficiency, it helps if you state in advance that such and such
evaluations are likely to occur quite often, and that remembering the
previous results is a good idea.

Hence an attribute, called {\em memo}.
This operator attribute tells the
system to remember the results of evaluation where the operator appeared.
More specifically, if you declare\index{\texttt{memo}}
\begin{vvtm}
\begin{ccode}
  op f**k : S S S -> S { memo }
\end{ccode}
\end{vvtm}
and evaluate a term containing \verb|f**k(t1,t2,t3)|, the system
take note of (1) \verb|f**k(t1,t2,t3)| itself, (2) \verb|f**k(r1,r2,r3)|,
where \verb|ri|'s are the results of evaluating \verb|ti|'s, and
(3) the result of evaluating (1). If the need arises to evaluate (1)
again, the system gets the result (3) immediately. This mechanism
not only speeds up the computation, it also saves memory space, when you
evaluate terms that contain common subterms.

The memo attribute can only specified on functions, i.e. operators
not defined by rules (See \label{sec:p2-rule-declaration} for rules).

The system does or does not remember the evaluation results
after each evaluation. It is controlled by a switch, and
\index{\texttt{clean memo}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set clean memo on
\end{ccode}
\end{vvtm}
tell the system to be forgetful. The default is \verb|off|.
It is also possible to initialise memo storages by the following command.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> clean memo
\end{ccode}
\end{vvtm}

The memo attributes may be ignored if you turn a switch off,\index{\texttt{memo}}
as
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set memo off
\end{ccode}
\end{vvtm}
%To see the virtue of remembering, let us define a factorial function on
%our own \verb|Nat|, and modify \verb|SIMPLE-NAT| and \verb|MULT| to
%have operators with memos, as
%\begin{vvtm}
%\begin{ccode}
%  op _+_ : Nat Nat -> Nat { memo }
%  op _*_ : Nat NAt -> Nat { memo }
%\end{ccode}
%\end{vvtm}
%Then
%\begin{vvtm}
%\begin{ccode}
%  CafeOBJ> module FACT {
%    protecting (MUTL)
%    op _! : Nat -> Nat { memo }
%    eq 0 ! = s(0) .
%    eq s(N:Nat) ! = (N !) * s(N).
%  }
%
%  -- defining module FACT.._..* done.
%  CafeOBJ> set clean memo on
%
%  CafeOBJ> set memo off
%
%  CafeOBJ> reduce in FACT : s(s(s(s(s(s(0)))))) ! .
%  -- reduce in FACT : s(s(s(s(s(s(0)))))) !
%  ...The result is the large term, and is omitted...
%  (0.000 sec for parse, 1194 rewrites(0.060 sec), 2227 matches)
%  CafeOBJ> set memo on
%
%  CafeOBJ> reduce in FACT : s(s(s(s(s(s(0)))))) ! .
%
%  -- reduce in FACT : s(s(s(s(s(s(0)))))) !
%
%  ...The result is the same large term, and is omitted...
%  (0.000 sec for parse, 1194 rewrites(0.060 sec), 2227 matches)
%  CafeOBJ> 
%\end{ccode}
%\end{vvtm}

\section{Coherence} \label{sec:p2-coherence}

As explained in Section \ref{sec:p2-evaluation-command} and
\ref{sec:p2-eval-exs-3},
in evaluating a term, application of behavioural axioms is prohibited
unless the redex is enclosed in an observation, and
this restriction is to ensure the soundness of evaluation.
This implies that the system can ignore the restriction
so long as the application does not lead to an incorrect reasoning.

An attribute called \verb|coherent| may be used to tell the system
to loosen the guard. It asserts that the operator acts
indistinguishably on behaviourally equivalent terms, so that
it is in effect a behavioural operator.
For example, the declarations
\begin{vvtm}
\begin{ccode}
  [ T ]
  *[ S ]*
  ops a b : -> S
  bop g : S -> T
  op f : S -> T { coherent }
  beq [ a-sim-b ] a = b .
\end{ccode}
\end{vvtm}
allow the system to apply \verb|a-sim-b| to \verb|f(a)|, where \verb|a|
is not guarded by an observation, as well as to \verb|g(a)|, where
\verb|a| is.

\section{Operator Attributes and Evaluations}\label{sec:p2-op-attr-eval}

Let us see how various attributes affect evaluation. In the case of
an associative operator with identity,\label{exs:az-op}
\begin{vvtm}
\begin{ccode}
  module AZ-OP {
   [ S ]
   ops : a b c phi : -> S
   op __ : S S -> S { associative id: phi }
  }

\end{ccode}
\end{vvtm}
you may compute as follows.
\begin{vvtm}
\begin{ccode}
  phi a phi b phi c ->
  a phi b phi c ->
  a b phi c ->
  a b c
\end{ccode}
\end{vvtm}
where \verb|phi|'s are eliminated wherever they appear.
Indeed the system computes exactly like you.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select AZ-OP

  AZ-OP> set trace on

  AZ-OP> reduce phi a phi b phi c .

  -- reduce in AZ-OP : phi a phi b phi c
  1>[1] rule: eq [ident12] : phi X-ID:S = X-ID:S
      { X-ID:S |-> a phi b phi c }
  1<[1] phi a phi b phi c --> a phi b phi c
  1>[2] rule: eq A2 phi X-ID:S A1 = A2 X-ID:S A1
      { A1 |-> phi c, X-ID:S |-> b, A2 |-> a }
  1<[2] a phi b phi c --> a b phi c
  1>[3] rule: eq A1 phi X-ID:S = A1 X-ID:S
      { X-ID:S |-> c, A1 |-> a b }
  1<[3] a b phi c --> a b c
  a b c : S
  (0.000 sec for parse, 3 rewrites(0.260 sec), 13 matches)
  AZ-OP> 
\end{ccode}
\end{vvtm}
The equations in this trace were generated by the system, to cope with
identity. The exact mechanism need not be your
concern, but beware that these extra equations may cause havoc
(Section \ref{sec:p2-op-attr-limit}).

If you inspect the statistics, it is apparent that the numbers of
matching attempts greatly exceeded those of rewrites. This is a general
fact about evaluation modulo equational theory.

See what happens if the operator is also commutative, as in
\label{exs:acz-op}
\begin{vvtm}
\begin{ccode}
  AZ-OP> module ACZ-OP {
    [ S ]
    ops : a b c phi : -> S
    op __ : S S -> S { associative commutative id: phi }
  }

  -- defining module ACZ-OP....._._* done.
  AZ-OP> select ACZ-OP

  ACZ-OP> reduce phi a phi b phi c .

  -- reduce in ACZ-OP : phi a phi b phi c
  1>[1] rule: eq [ident14] : phi X-ID:S = X-ID:S
      { X-ID:S |-> a b phi phi c }
  1<[1] phi a phi b phi c --> a b phi phi c
  1>[2] rule: eq [ident14] : phi X-ID:S = X-ID:S
      { X-ID:S |-> a b phi c }
  1<[2] a b phi phi c --> a b phi c
  1>[3] rule: eq [ident14] : phi X-ID:S = X-ID:S
      { X-ID:S |-> a b c }
  1<[3] a b phi c --> a b c
  a b c : S
  (0.010 sec for parse, 3 rewrites(0.010 sec), 5 matches)
  ACZ-OP> 
\end{ccode}
\end{vvtm}
Again \verb|phi|'s were eliminated, but different rewrite rules
were used, and, relying on commutativity, the system changed
the order of listing at the first step.

Adding idempotency, we get\label{exs:aciz-op}
\begin{vvtm}
\begin{ccode}
  ACI-OP> module ACIZ-OP {
    [ S ]
    ops a b c phi : -> S
    op __ : S S -> S { assoc comm idem id: phi }
  }

  -- defining module ACIZ....._._* done.
  ACI-OP> reduce in ACIZ-OP : phi a phi b phi c .

  -- reduce in ACIZ-OP : phi a phi b phi c
  1>[1] rule: eq AC U-idem:S U-idem:S = AC U-idem:S
      { AC |-> phi a b c, U-idem:S |-> phi }
  1<[1] phi a phi b phi c --> phi a b c
  1>[2] rule: eq [ident16] : phi X-ID:S = X-ID:S
      { X-ID:S |-> a b c }
  1<[2] phi a b c --> a b c
  a b c : S
  (0.000 sec for parse, 2 rewrites(0.000 sec), 9 matches)
  ACI-OP> 
\end{ccode}
\end{vvtm}
\verb|phi|'s were stripped, but the reason for the first step
(when two \verb|phi|'s were eliminated at once) was not that
\verb|phi| was the identity, but that ``\verb|__|'' was
idempotent.

\section{Further Example: Propositional Calculus}
\label{sec:p2-propositional-calc}

The next example is a decision procedure of propositional logic.
In this example, rewriting modulo associativity and commutativity
is decisive.

\cafeobj~has a built-in module \verb|PROPC|, which is declared as follows.
\label{exs:propc}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> show PROPC
  sys:module! PROPC
        principal-sort Prop
 {
    imports {
      protecting (TRUTH)
    }
    signature {
      [ Prop, Identifier Bool < Prop ]
      op _ and _ : Prop Prop -> Prop { assoc comm constr prec: 55 r-assoc }
      op _ xor _ : Prop Prop -> Prop { assoc comm constr prec: 57 r-assoc }
      op _ or _ : Prop Prop -> Prop { assoc comm prec: 59 r-assoc }
      op not _ : Prop -> Prop { strat: (0 1) prec: 53 }
      op _ -> _ : Prop Prop -> Prop { strat: (0 1 2) prec: 61 }
      op _ <-> _ : Prop Prop -> Prop { assoc prec: 63 r-assoc }
    }
    axioms {
      var p : Prop
      var q : Prop
      var r : Prop
      eq p and false = false .
      eq p and true = p .
      eq p and p = p .
      eq p xor false = p .
      eq p xor p = false .
      eq p and (q xor r) = p and q xor p and r .
      eq p or q = p and q xor p xor q .
      eq not p = p xor true .
      eq p -> q = p and q xor p xor true .
      eq p <-> q = p xor q xor true .
    }
  }

  CafeOBJ>
\end{ccode}
\end{vvtm}
``\verb|sys:module!|'' is an introductory keyword for built-in modules.
\begin{itemize}
\item An atomic proposition is an element of the built-in
  sort \verb|Identifier|, declared in \newline
  \verb|CHAOS:IDENTIFIER|, or of the sort \verb|Bool|,
  declared in \verb|TRUTH|.
  \verb|Identifier| contains character strings.
  \verb|Bool| contains \verb|true| and \verb|false|.
\item Propositional connectives are \texttt{and}, \texttt{or}, \texttt{->},
  \texttt{not}, \texttt{<->}, and \texttt{xor} (exclusive or).
\item An irreducible term is constructed out of \texttt{and}, \texttt{xor},
  \texttt{true}, \texttt{false}, and identifiers.
  It is in disjunctive normal form (by regarding \texttt{xor} as disjunction).
  In particular, tautologies are reducible to \texttt{true}.
\item The precedences of connectives are ordered as
  \texttt{not}, \texttt{and}, \texttt{xor}, \texttt{or}, \texttt{->}, \texttt{<->}.
\end{itemize}
Evaluations in this module proceed as follows. Firstly,
\begin{vvtm}
\begin{ccode}
  a -> b <-> not b -> not a
\end{ccode}
\end{vvtm}
states $a \to b \leftrightarrow \neg b \to \neg a$, a tautology
(equivalence of contrapositives).
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select PROPC

  PROPC> set trace on

  PROPC> reduce a -> b <-> not b -> not a .

  -- reduce in PROPC : a -> b <-> not b -> not a
  1>[1] rule: eq p:Prop -> q:Prop = p:Prop and q:Prop xor p:Prop xor
         true
      { p:Prop |-> a, q:Prop |-> b }
  1<[1] a -> b --> a and b xor a xor true
  1>[2] rule: eq p:Prop -> q:Prop = p:Prop and q:Prop xor p:Prop xor
         true
      { p:Prop |-> not b, q:Prop |-> not a }
  1<[2] not b -> not a --> not b and not a xor not b xor true
  1>[3] rule: eq not p:Prop = p:Prop xor true
      { p:Prop |-> b }
  1<[3] not b --> b xor true
  1>[4] rule: eq not p:Prop = p:Prop xor true
      { p:Prop |-> a }
  1<[4] not a --> a xor true
  1>[5] rule: eq p:Prop and (q:Prop xor r:Prop) = p:Prop and q:Prop 
        xor p:Prop and r:Prop
      { p:Prop |-> b xor true, q:Prop |-> true, r:Prop |-> a }
  1<[5] (b xor true) and (a xor true) --> (b xor true) and true xor
       (b xor true) and a
  1>[6] rule: eq p:Prop and true = p:Prop
      { p:Prop |-> b xor true }
  1<[6] (b xor true) and true --> b xor true
  1>[7] rule: eq p:Prop and (q:Prop xor r:Prop) = p:Prop and q:Prop 
        xor p:Prop and r:Prop
      { p:Prop |-> a, q:Prop |-> true, r:Prop |-> b }
  1<[7] (b xor true) and a --> a and true xor a and b
  1>[8] rule: eq p:Prop and true = p:Prop
      { p:Prop |-> a }
  1<[8] a and true --> a
  1>[9] rule: eq AC xor p:Prop xor p:Prop = AC xor false
      { AC |-> true xor a xor a and b, p:Prop |-> true xor b }
  1<[9] b xor true xor a xor a and b xor b xor true xor true --> true 
      xor a xor a and b xor false
  1>[10] rule: eq p:Prop xor false = p:Prop
      { p:Prop |-> a and b xor true xor a }
  1<[10] true xor a xor a and b xor false --> a and b xor true xor a
    \end{ccode}
  \end{vvtm}
\begin{vvtm}
\begin{ccode}
  1>[11] rule: eq p:Prop <-> q:Prop = p:Prop xor q:Prop xor true
      { p:Prop |-> a and b xor a xor true, q:Prop |-> a and b xor true 
         xor a }
  1<[11] a and b xor a xor true <-> a and b xor true xor a --> a and
       b xor a xor true xor a and b xor true xor a xor true
  1>[12] rule: eq AC xor p:Prop xor p:Prop = AC xor false
      { AC |-> true, p:Prop |-> true xor a and b xor a }
  1<[12] a and b xor a xor true xor a and b xor true xor a xor true
       --> true xor false
  1>[13] rule: eq p:Prop xor false = p:Prop
      { p:Prop |-> true }
  1<[13] true xor false --> true
  true : Bool
  (0.000 sec for parse, 13 rewrites(0.140 sec), 75 matches)
  PROPC> 
\end{ccode}
\end{vvtm}
Observe that associativity and commutativity are frequently used.
To trace everything makes the exposition rather long, so we omit
traces in the sequel.
\begin{vvtm}
\begin{ccode}
  PROPC> set trace off
  PROPC>  reduce not(a or b) <-> not a and not b .
  -- reduce in PROPC : not (a or b) <-> not a and not b
  true : Bool
  (0.000 sec for parse, 11 rewrites(0.020 sec), 70 matches)
  PROPC> reduce c or c and d <-> c .
  -- reduce in PROPC : c or c and d <-> c
  true : Bool
  (0.000 sec for parse, 7 rewrites(0.190 sec), 34 matches)
  PROPC> reduce a <-> not c .
  -- reduce in PROPC : a <-> not c
  a xor c : Prop
  (0.000 sec for parse, 4 rewrites(0.010 sec), 15 matches)
  PROPC> reduce a and b xor c xor b and a .
  -- reduce in PROPC : a and b xor c xor b and a
  c : Identifier
  (0.010 sec for parse, 2 rewrites(0.000 sec), 21 matches)
  PROPC> reduce a <-> a <-> a <-> a .
  -- reduce in PROPC : a <-> a <-> a <-> a
  true : Bool
  (0.010 sec for parse, 9 rewrites(0.000 sec), 18 matches)
  PROPC> reduce a -> b and c <-> (a -> b) and (a -> c) .
  -- reduce in PROPC : a -> b and c <-> (a -> b) and (a -> c)
  true : Bool
  (0.010 sec for parse, 25 rewrites(0.050 sec), 184 matches)
  PROPC> 
\end{ccode}
\end{vvtm}
It is pleasing to see that the usual logical truths are proved
to be true, by just evaluating the corresponding terms.
Here the logical basis of the language is in stark relief.
If you think of rewrite rules as deduction rules, a computation is
a proof. The set of rewrite rules is sound iff all the statements
reducible to \verb|true| are valid. It is complete iff
all the valid statements are reducible to \verb|true|.

\section{Limitation of the Implementation}\label{sec:p2-op-attr-limit}

As a cautious conclusion to operator attributes, we must point to the
major limitations of
the current implementation. As mentioned earlier, the treatment of
idempotency is inadequate. The other two problems concern the
enormity of extra rewrite rules. You should have noticed that, to realise
rewriting modulo identity or associativity, the system adds equations
surreptitiously. Consider first the case of identities.

Suppose in \verb|AZ-OP| in Section \ref{exs:az-op}, there were another
operator declaration
\begin{vvtm}
\begin{ccode}
  op first : S -> S
\end{ccode}
\end{vvtm}
and an equation
\begin{vvtm}
\begin{ccode}
  eq first(X:S X':S) = X .
\end{ccode}
\end{vvtm}
A special case of the equation is
\begin{vvtm}
\begin{ccode}
  eq first(X) = X .
\end{ccode}
\end{vvtm}
where \verb|X'| is bound to \verb|phi| and the identity is cancelled.
The completion procedure for implementing identities does add this
equation, as well as
\begin{vvtm}
\begin{ccode}
  eq first(X') = phi .
\end{ccode}
\end{vvtm}
which is a specialisation to the case when \verb|X| is \verb|phi|.
Thus we get a specification where
\begin{vvtm}
\begin{ccode}
  phi = first(a) = a = first(a b) = phi = ...
\end{ccode}
\end{vvtm}
holds. This result is somewhat unexpected. As a TRS, the two equations
annihilate the Church-Rosser property.

A different problem arises if you
modify the declaration of \verb|xor| in \verb|PROPC| (Section \ref{exs:propc})
as
\begin{vvtm}
\begin{ccode}
  op _xor_ : Prop Prop -> Prop { assoc comm id: false }
\end{ccode}
\end{vvtm}
i.e., adding the identity attribute.
Then in the presence of the equation
\begin{vvtm}
\begin{ccode}
  eq p and (q xor r) = p and q xor p and r .
\end{ccode}
\end{vvtm}
the completion procedure adds
\begin{vvtm}
\begin{ccode}
  eq p and r = (p and false) xor (p and r) .
\end{ccode}
\end{vvtm}
which is a special case, where \verb|q| is replaced by \verb|false|.
This equation is hazardous, since you now get an infinite
rewrite sequence
\begin{vvtm}
\begin{ccode}
  a and b -->
  (a and false) xor (a and b) -->
  (a and false) xor (a and false) xor (a and b) -->
      :
\end{ccode}
\end{vvtm}
Even if such a hazard is avoided, performance may be compromised,
by hundreds of extra unwanted equations. If you encounter misbehaviours,
then, ``\verb|id:|'' is a possible suspect. If it is the culprit,
change to ``\verb|idr:|'',\index{\texttt{idr:}} which does not force completion.

As to associativity, a fateful combination with sort ordering may
generate dozens of unnecessary equations. For example, in the built-in
module \verb|INT|, \verb|Nat| is a subsort of \verb|Int|, and
the addition ``\verb|_+_|'' is declared on both sorts. As a consequence,
an equation
\begin{vvtm}
\begin{ccode}
  eq 0 + I = I .
\end{ccode}
\end{vvtm}
induces an extra equation
\begin{vvtm}
\begin{ccode}
  eq 0 + I + ac_E = ac_E + I .
\end{ccode}
\end{vvtm}
This equation has a lefthand side that is costly to match, yet adds
nothing to the power of evaluation. To check the necessity of
such extra equations is not easy. As of now, the system bets on
the safer side, and adds equations nonchalantly.

\chapter{Module Structure}\label{sec:p2-module-hierarchies}

\section{Names and Contexts}

\subsection{Context and Current Module}\label{sec:p2-current-module}

Import declarations define a hierarchy of modules. As a directed graph,
it is acyclic: a module cannot import itself, either directly or
indirectly. The directed acyclic graph is called
{\em context}\index{context (module)},
and for a paricular module \verb|M| in the
graph, the complete subgraph reachable from \verb|M| is called
the context of \verb|M|. You may regard the context of \verb|M| as
collections of sorts, operators, variables, and axioms, which can
be referred to within \verb|M|.

The concept of current module\index{current module} is to establish
a context in the above sense. Such commands as \verb|reduce| and
\verb|parse| presuppose a context. The current module is set by the
following command.

\begin{bsyntax} \texttt{select} command \index{\texttt{select}} \Hline
\texttt{select} \textit{module\_name}
\end{bsyntax}

You are always reminded of
the current module by the prompt --- you already have seen many
session examples.

You may make the context follow your every step, so that if you
define a module or inspect its contents, the current module switches
to that module, by the command\index{\texttt{set}}\index{\texttt{auto}}
\index{\texttt{context}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set auto context on
\end{ccode}
\end{vvtm}
The default is \verb|off|.
The effects of this switch are illustrated in the following session.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set auto context on

  CafeOBJ> module M { [ S ] op e : -> S }

  -- defining module M.._* done.
  M> module N { [ S ] }

  -- defining module N._* done.
  N> show M
  module M {
    imports {
      protecting (BOOL)
    }
    signature {
      [ S ]
      op e : -> S
    }
  }

  M> show N
  module N {
    imports {
      protecting (BOOL)
    }
    signature {
      [ S ]
    }
  }

  N> 
\end{ccode}
\end{vvtm}
Notice that the prompt changed to \verb|M| (\verb|N|), each time
\verb|M| (\verb|N|) was defined or inspected. The current module ---
hence context --- can be shown as follows.\index{\texttt{context}}
\begin{vvtm}
\begin{ccode}
  N> show context
  -- current context :
  [module] N
  [special bindings]
    $$term    = none.
    $$subterm = no subterm selection is made by `choose'.
  [bindings] empty.
  [selections]  empty.
  [pending actions]  none.
  [stop pattern] not specified.

  N>
\end{ccode}
\end{vvtm}
The output contains the states that are local to the current context.
For example, under \verb|bindings| are listed context variables
(Section \ref{sec:p2-let-command}). The others concern theorem
proving tools, to be explained (Chapter \ref{sec:p2-theorem-proving}).

\verb|show| command is also used to print contexts. To print the context
of \verb|M|, type
\begin{vvtm}
\begin{ccode}
  CafeOBJ> show module tree M
\end{ccode}
\end{vvtm}

A submodule of a module is identified by a name, so during a session
it is possible for the definition of a submodule to
change --- when you redefine that submodule, or when you unintentionally
use the same name for a different module. In such a case, the system
does not take any housekeeping exercise until necessary --- until,
for example, an evaluation command is entered. You may make the
system to be more diligent, by flicking a switch.
\index{\texttt{auto}}\index{\texttt{reconstruct}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set auto reconstruct on
\end{ccode}
\end{vvtm}
When the switch is on, every time a module is redefined, every
context surrounding it is forced to reflect the change at once.

If you are so inclined, you may change the prompt once and for all.
\index{\texttt{prompt}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> prompt Haskell>

  Haskell>
\end{ccode}
\end{vvtm}
In the reset of the session, the prompt would not change until
you invoke the command again\footnote{For an obvious reason, the above change
does not force the system to accept Haskell.}.

\subsection{Module Sharing}\label{sec:p2-module-sharing}

It is possible that some modules are imported several times.
For example, the declarations
\begin{vvtm}
\begin{ccode}
  module M0 { ... }
  module M00 { protecting (M0) ... }
  module M01 { protecting (M0) ... }
  module M001 { protecting (M00) protecting (M01) ... }
\end{ccode}
\end{vvtm}
makes \verb|M001| import \verb|M0| twice. The basic
convention is that, in such cases, \verb|M0|
is regarded as imported only once, and its single copy is
shared throughout. This convention works fine when a module is
imported with \verb|protecting| mode, since a module then has
essentially the same models everywhere. The problem arises
when \verb|extending| or \verb|using| modes appear somewhere.
In general, importation modes are determined as follows.

Let us write \verb|M -m-> M'| if \verb|M| directly imports
\verb|M'| with importation mode \verb|m|. When \verb|M| (directly or
indirectly) imports \verb|M'|, there are several chains
\begin{vvtm}
\begin{ccode}
  M -m1-> M1 -m2-> ... -mn-> Mn = M'
\end{ccode}
\end{vvtm}
to \verb|M'|. Each such chain determines the mode with which
\verb|M| imports \verb|M'|, as the weakest among all the
\verb|mi|'s. For example, in the chain
\begin{vvtm}
\begin{ccode}
  M -pr-> M1 -ex-> M2 -pr-> M'
\end{ccode}
\end{vvtm}
\verb|M'| is imported via \verb|ex| mode.

The mode with which \verb|M'| is imported is the weakest among
all the chains along which \verb|M'| is imported.

\subsection{Qualifying Names}\label{sec:p2-naming-and-qualification}

In Section \ref{sec:p2-parsing-qualifier}, we have shown how to qualify
terms by sort names. You can also qualify sort names and operator names,
this time by module names.

\cafeobj~allows you to use the same name for different sorts.
A typical case is to declare sorts in different but related
modules: variants of stack definitions, for example, are likely to
have a common sort name \verb|Stack|.
So long as they do not appear in the same context, those
sorts do not cause confusion. The problem arises when you import
two modules that contain sorts of the same name.
It is unlikely to import both modules directly, but it is
definitely possible to import them indirectly. To avoid confusion
you can qualify names as follows.

\begin{bsyntax} reference to sort/operator/parameters \Hline
\textit{name}$[$``\texttt{.}''\textit{module\_name}$]$
\end{bsyntax}

where the name is a sort name, an operator name, or a parameter name
(Section \ref{sec:p2-parameter}). According to the above
syntactical rule, the references that
appeared so far, such as \verb|Nat|, could be qualified, such
as ``\verb|Nat.SIMPLE-NAT|''.
A module name may be a parameter name (Section \ref{sec:p2-parameter}).

To avoid ambiguity, if an operator name contains blanks or
periods, it must be parenthesised, as ``\verb|(_._).M|''.

The referent of a qualified name is the one that is in the context
of the qualifier. ``\verb|Nat.SIMPLE-NAT|'' refers to the sort
\verb|Nat| in
the context of \verb|SIMPLE-NAT|. Note that this does {\em not} imply that
\verb|Nat| is declared in \verb|SIMPLE-NAT|: it only says that
{\em somewhere} in the context of \verb|SIMPLE-NAT|, \verb|Nat| is declared.
If, in the context of \verb|SIMPLE-NAT|, more than one \verb|Nat| are
declared, the qualifier fails to identify which. In that case,
you have to be more specific.

\begin{warning}
  The above qualification of operator names are for {\em referring} to
  operators in \verb|show| commands, mappings, etc.
  You cannot use qualification in writing a term.
\end{warning}

\subsection{Referring to Operators}\label{sec:p2-operator-reference}

Operator names appear in renaming and view declarations
(both are to be explained). In these constructs, a single name may
refer to more than one operators, due to overloading.
Special care needs to be taken, therefore, to see which operator
names refer to which operators.

Note first that you have to distinguish operators with different
number of arguments, as
\begin{vvtm}
\begin{ccode}
  op f : Nat -> Nat
\end{ccode}
\end{vvtm}
and
\begin{vvtm}
\begin{ccode}
  op f : Nat Nat -> Nat
\end{ccode}
\end{vvtm}
This problem does not arise if operators are mixfix, since their
symbols contain placeholders ``\verb|_|''s. All in all, you have this
definition.

\begin{bsyntax} operator name \Hline
$\{$ \textit{mixfix\_operator\_symbol} $|$ \textit{standard\_operator\_symbol} $\}[$``\texttt{/}''\textit{number\_of\_arguments}$]$
\end{bsyntax}

You should not insert blanks between the operator symbol and ``\verb|/|'', or
between ``\verb|/|'' and the number of arguments. Using this form,
the above two declarations may be distinguished as
``\verb|f/1|'' and ``\verb|f/2|''.

With this preparation, let us define in detail the relationship between
operator names and their referents. In \cafeobj, an operator name
refers to a group of operators, rather than a single operator.
Given a module \verb|M|, consider, for example, an operator declaration
\begin{vvtm}
\begin{ccode}
  op f : Nat Nat -> Nat
\end{ccode}
\end{vvtm}
in \verb|M|, and let $G$ be the group this operator belongs to.
\begin{enumerate}
\item[1.] Another operator with the same name (i.e. ``\verb|f/2|''), and whose
arity is in the same connected component as \verb|Nat Nat|, belongs to
$G$.
\item[2.]  Yet another operator, with the same name but with arity outside
the connected component, belongs to $G$ only if it is declared in \verb|M|.
\item[3.] No other operator belongs to $G$.
\end{enumerate}
Here the connected component of ``\verb|Nat Nat|'' is taken from
the product graph.
The operator name ``\verb|f/2|'' in the context of \verb|M| refers to
the group $G$, which may contain several distinct operators, due to the
above rules. Accordingly, the qualified name ``\verb|(f/2).M|'' refers to
$G$.

Intuitively, qualification by \verb|M| states that the name is declared
in \verb|M|. Hence 2. precludes operators declared in other modules.
But what about 1.? Consider, for example, the code
\begin{vvtm}
\begin{ccode}
   module NAT {
     [ Nat ]
     ...
     op _+_ : Nat Nat -> Nat
     ...
   }

   module INT {
     protecting (NAT)
     [ Nat < Int ]
     ...
     op _+_ : Int Int -> Int
     ...
   }
\end{ccode}
\end{vvtm}
and the reference ``\verb|(_+_).INT|''. It certainly refers to ``\verb|_+_|''
on \verb|Int|, but it should also refer to ``\verb|_+_|'' on \verb|Nat|, since
\cafeobj~regards an overloaded operator on subsorts as the restriction.
On \verb|Nat|, two ``\verb|_+_|''s must behave identically. Hence the
rule 1.

%To probe the consequences of the above definition, let us introduce contrived
%module declarations. Firstly,
%\begin{vvtm}
%\begin{ccode}
% module M {
%   signature {
%    [ A < B, C D ]
%    op op1 : A A -> A
%    op op1 : B B -> B
%    op _+_ : C C -> C
%    op _+_ : D D -> D
%    op op1 : C C C -> C
%    op op2 : A A -> A
%  }
% }
%\end{ccode}
%\end{vvtm}
%Within \verb|M|, we only need to consider the rules 2. and 3., and get
%the following operator groups.
%\begin{itemize}
%\item[] Group \verb|op1/2|: \verb|{ op1 : A A -> A, op1 : B B -> B }|
%\item[] Group \verb|op1/3|: \verb|{ op1 : C C C -> C }|
%\item[] Group \verb|_+_|:   \verb|{ _+_ : C C -> C, _+_ : D D -> D }|
%\item[] Group \verb|op2/2|: \verb|{ op2 : A A -> A }|
%\end{itemize}
%Secondly,
%\begin{vvtm}
%\begin{ccode}
%  module M' {
%    protecting(M)
%    signature {
%      [ D < E, F ]
%      op _+_ : E E -> E
%      op _+_ : F F -> F
%      op op1 : F F -> F
%      op op2 : E E -> E
%    }
%  }
%\end{ccode}
%\end{vvtm}
%Operators are massively overloaded. To simplify the exposition, use
%qualification by \verb|M| and expand the declarations:
%\begin{vvtm}
%\begin{ccode}
%  signature {
%    [ A.M < B.M, C.M, D.M < E, F ]
%    op op1.M : A.M A.M -> A.M
%    op op1.M : B.M B.M -> B.M
%    op _+_.M : C.M C.M -> C.M
%    op _+_.M : D.M D.M -> D.M
%    op op1.M : C.M C.M C.M -> C.M
%    op op2.M : A.M A.M -> A.M
%    op _+_   : E E -> E
%    op _+_   : F F -> F
%    op op1   : F F -> F
%    op op2   : E E -> E
%  }
%\end{ccode}
%\end{vvtm}
%Using the rules 1., 2. and 3., we get the following group.
%\begin{itemize}
%\item[] Group \verb|op1/2|:
%  \verb|{ op1.M : A.M A.M -> A.M, op1.M : B.M B.M -> B.M }|
%\item[] Group \verb|op1/2|: \verb|{ op1 : F F -> F }|
%\item[] Group \verb|_+_|:
%  \verb|{ _+_ : E E -> E, _+_ : F F -> F, _+_.M : D.M D.M -> D.M }|
%\item[] Group \verb|_+_|: \verb|{ _+_.M : C.M C.M -> C.M }|
%\item[] Group \verb|op1/3|: \verb|{ op1.M : C.M C.M C.M -> C.M }|
%\item[] Group \verb|op2/2|: \verb|{ op2   : E E -> E }|
%\item[] Group \verb|op2/2|: \verb|{ op2.M : A.M A.M -> A.M }|
%\end{itemize}
%Note well how the groups are rearranged, and observe the appearance of
%groups with the same names. We may avoid the name conflict over
%``\verb|op1/2|'' or ``\verb|op2/2|'' by qualifying with \verb|M|, but
%``\verb|_+_|'' would not succumb to this trick. ``\verb|(_+_).M|'' refers to
%the group before rearrangement, not to one of the new groups.
%\cafeobj~does not offer a general solution to this problem.
%
%\begin{warning}
% This section will be entirely deleted from the future version.
%\end{warning}

\section{Parameters and Views}

One of the salient features of \cafeobj~is a parameter mechanism.
By putting aside certain sorts and operators as parameters,
you can declare a generic module. A parameter unit is itself a module
so that, on top of syntactical requirements, semantic constraints may
be imposed on actual parameters. To instantiate a parameterised module is
to replace the parameters with modules that satisfy the syntactic {\em and}
semantic constraints.

\subsection{Parameterised Module}\label{sec:p2-parameter}

To declare a parameterised module, attach a parameter interface
to the module declaration construct.

\begin{bsyntax} parameterised module \index{\texttt{module}} \Hline
\texttt{module} \textit{module\_name} ``\texttt{(}'' \textit{list\_of\_parameters} ``\texttt{)}'' ``\texttt{\{}''
~~~~\textit{module\_element} $*$
``\texttt{\}}''
\end{bsyntax}

A list of parameters is comma-separated. A {\em parameter}\index{parameter}
has the following construct.

\begin{bsyntax} parameter \Hline
$[$ \textit{importation\_mode} $]$ \textit{parameter\_name} ``\texttt{::}'' \textit{module\_name}
\end{bsyntax}

A parameter name is an arbitrary character string, and is used to
refer to the parameter module in the module body. The module name
after ``\verb|::|'' describes requirements that must be satisfied by
the actual parameters. The same module may act as distinct parameters,
and parameter names distinguish them.
For importation modes, which are optional, see
Section \ref{sec:p2-params-as-subs}.

\begin{warning}
  In ancient times, parameters were enclosed with square brackets ``\verb|[|'',
  ``\verb|]|''.
\end{warning}

\begin{warning}
  Do not forget to put blanks before and after ``\verb|::|''.
\end{warning}

For example, the following modules define indexed lists,
where both indices and data may come from arbitrary sets.
\label{exs:ilist}
\begin{vvtm}
\begin{ccode}
   module* ONE { [ Elt ] }

   module! ILIST ( IDX :: ONE, DAT :: ONE ) {
     [ Ilist ]
     [ Elt.DAT < ErrD ]
     op undef : -> ErrD
     op empty : -> Ilist
     op put : Elt.IDX Elt.DAT Ilist -> Ilist
     op _[_] : Ilist Elt.IDX -> ErrD
     -- -----------------------------
     vars I I' : Elt.IDX
     var D : Elt.DAT
     var L : Ilist
     eq put(I,D,L) [ I' ] = if I == I' then D else L [ I' ] fi .
     eq empty [ I ] = undef .
   }
\end{ccode}
\end{vvtm}
Observe how the same module \verb|ONE| is used as different parameters.
Inside \verb|ILIST|, sorts and operators of a parameter may be
referred to with qualified names, like ``\verb|Elt.DAT|''
(cf. Section \ref{sec:p2-naming-and-qualification}).

As an aside, the current version of \cafeobj~has a built-in module
called \verb|TRIV|, which is the same as \verb|ONE| above.\label{exs:triv}
Using this built-in, you may as well have written
\begin{vvtm}
\begin{ccode}
   module! ILIST ( IDX :: TRIV, DAT :: TRIV ) \{ ...
\end{ccode}
\end{vvtm}
Further, error sorts, such as \verb|ErrD|, are implicitly declared
(Section \ref{sec:p2-flexible-typing}), so you need not declare
\verb|ErrD| as above.

\subsection{Pre-view (Not Preview)}\label{sec:p2-pre-view}

This section contains a preliminary to the following sections,
and is rather technical. To bind actual parameter modules to formals,
we need ways to relate two modules. Since modules denote structures,
we rely on the idea of structure-preserving mappings. Such mappings
are usually called homomorphisms.\index{homomorphism}
Intuitively, in
\begin{vvtm}
\begin{ccode}
  module M { [ S ] }
  module M' { [ S' ] }
  module N { [ T U ] }
\end{ccode}
\end{vvtm}
the modules \verb|M| and \verb|M'| are essentially the same, since
the difference lies only in the naming; and \verb|M| (or \verb|M'|)
may be embedded in \verb|N|, since \verb|N| defines an enlarged
(two-sorted) structure. The following definitions are nothing more
than the statements of the obvious, like this tiny example. They
are complicated only because \cafeobj~is founded on a rich logical base.

\paragraph{Derived Operators}\index{derived operator}

A derived operator is just a term regarded as an operator.
For example, under the module \verb|MULT| (Section \ref{exs:mult})
and for variables \verb|X| and \verb|Y| of sort \verb|Nat|,
\verb|s(0)|, \verb|s(s(X))|, ``\verb|s(0) + X|'', ``\verb|s(X) * s(Y)|'', and
``\verb|X * X|'' are all
terms, hence derived operators. The important point here is that each
such term can be assigned a rank, inductively. We have
\begin{center}
\begin{tabular}{ll}
\multicolumn{1}{l}{term} & \multicolumn{1}{l}{rank} \\ \hline
\verb|s(0)| & \verb|-> NzNat| \\
\verb|s(s(X))| & \verb|Nat -> NzNat| \\
\verb|s(0) + X| & \verb|Nat -> NzNat| \\
\verb|s(X) * s(Y)| & \verb|Nat Nat -> Nat| \\
\verb|X * X| & \verb|Nat -> Nat| \\
\end{tabular}
\end{center}
It is easy\footnote{
Actually, not so easy. You have to calculate a least sort.
}
to calculate the rank of a derived operator: the sorts of
the variables constitute the arity, and the coarity of the dominant operator
is the coarity.

Further, given a signature, the derived signature\index{derived signature}
is the one containing every derived operator.
Thus, if we denote derived operators by terms,
the derived signature of \verb|MULT| looks like
\begin{vvtm}
\begin{ccode}
  [ Zero NzNat < Nat ]
  op 0 : -> Zero
  op s : Nat -> NzNat
  op _+_ : Nat Nat -> Nat
  op _*_ : Nat Nat -> Nat
  ...
  op s(0) : -> NzNat
  ...
  op s(s(X)) : Nat -> NzNat
  ...
  op s(0) + X : Nat -> Nat
  ...
\end{ccode}
\end{vvtm}
which, of course, we cannot write out fully, since this signature is
infinite.

\paragraph{Signature Morphisms}

A signature morphism\index{signature morphism} is a structure-preserving
mapping from a signature to another. For example,
\begin{vvtm}
\begin{ccode}
  signature {
    [ S < S' ]
    *[ H ]*
    bop f : H -> S 
  }
\end{ccode}
\end{vvtm}
may be mapped to
\begin{vvtm}
\begin{ccode}
  signature {
    [ T < T', U ]
    *[ K < K' ]*
    bop g : K -> T
  }
\end{ccode}
\end{vvtm}
via the mapping

%\begin{center}
\begin{tabular}{lll}
\verb|S| & $\to$ & \verb|T| \\
\verb|S'| & $\to$ & \verb|T'| \\
\verb|H| & $\to$ & \verb|K| \\
\verb|f| & $\to$ & \verb|g| \\
\end{tabular}
%\end{center}

which preserves sort ordering and visibility, as well as ranks of
operators.

To be definite, given signatures $\Sigma$ and $\Sigma^{\prime}$,
a signature morphism is a pair of
mappings $h_s$ (of sorts) and $h_o$ (of operators) such that
\begin{itemize}
\item $h_s$ preserves and reflects visibility, i.e. $S$ is visible
  (hidden) iff $h_s(S)$ is;
\item $h_s$ preserves sort ordering, i.e. you must have
  $h_s(S) \leq h_s(S')$ if $S \leq S'$;
\item $h_s$ reflects sort ordering on hidden sorts, i.e.
  you must have $S \leq S'$ if $h_s(S) \leq h_s(S')$;
\item $h_o$ preserves ranks, i.e. an operator $f$ with rank
  $S_1 \ldots S_n \to S$ must be mapped to an operator
  with rank $h_s(S_1) \ldots h_s(S_n) \to h_s(S)$;
\item $h_o$ maps behaviourals to behaviourals (\verb|bop| to \verb|bop|),
  and \verb|op| to \verb|op|; and
\item $h_o$ is surjective on behaviourals, i.e. for any behavioural
  operator $g$ in the target signature,
  there must be a (behavioural) operator $f$ such that $h_o(f) = g$.
\end{itemize}

\paragraph{Specification Morphism}\index{specification morphism}

Signature morphisms take care of signatures. Modules contain
axioms as well, and specification morphisms are defined to
``preserve'' axioms. As an example, consider \verb|MONOID|
(Section \ref{exs:monoid}) and \verb|SIMPLE-NAT|
(Section \ref{exs:simple-nat}). If \verb|SIMPLE-NAT| indeed specifies
natural number addition, it is associative and has identity \verb|0|,
hence constitutes a monoidal structure. This fact can be confirmed by
\begin{itemize}
\item[1.] Specifying a mapping of sorts and operators that is a
 signature morphism, and
\item[2.] Showing that, under that mapping, the (translated)
  axioms of \verb|MONOID| hold in \verb|SIMPLE-NAT|.
\end{itemize}
A specification morphism is a signature morphism that satisfies such
conditions as 2. above. A precise definition would require the
precise notion of satisfaction, which is beyond this exposition
(note that you have to consider transition relations
and behavioural equivalence, in addition to equality).
In its place and for intuitive illustration, we shall elaborate on the above
monoid example, after introducing concrete language constructs.

\subsection{View}\label{sec:p2-view}

A {\em view}\index{view} specifies ways to
bind actual parameters to formal parameters.
Given a parameter, i.e. a module $T$, and a module $M$,
a view $V$ from $T$ to $M$ is a specification morphism
from $T$ to $M'$, the derived specification of $M$, with one modification:
the operator mapping must be surjective only for
non-derived behavioural operators (i.e., those originally in $M$).
To spell out the definitions of the previous section, therefore,
a view is a pair of structure-preserving mappings of sorts
and operators, under which axioms of $T$ hold in $M'$
--- hence in $M$, since $M'$ does not contain extra axioms.

To instantiate a parameterised module, it is not enough to supply an
actual parameter, since there are in general several ways to
replace sorts with sorts and operators with operators. You need a view.
\label{sec:p2-view-decl}
A view declaration consists of a parameter module, an actual parameter module,
and a set of maps that constitute a specification morphism.

\begin{bsyntax} view \Hline
\index{\texttt{view}}\index{\texttt{from}}\index{\texttt{to}}
\texttt{view} \textit{view\_name} \texttt{from} \textit{module\_name} \texttt{to} \textit{module\_name} ``\texttt{\{}''
~~~\textit{view\_element} $*_,$
``\texttt{\}}''
\end{bsyntax}

\begin{tabular}{r c l}
  \textit{view\_element} &::=& \textit{map} \\
                &$|$& \textit{variable\_declaration}
\end{tabular}

A view name is a character string. The module names after \verb|from|
and \verb|to| are those of the parameter module and the actual parameter
respectively. Maps are as follows.

\begin{tabular}{r c l}\index{\texttt{sort}}\index{\texttt{op}}\index{\texttt{hsort}}
\index{\texttt{bop}}
  \textit{map} &::=& \verb|sort| \textit{sort\_name} ``\verb|->| \textit{sort\_name} \\
  &$|$& \verb|hsort| sort\_name ``\verb|->| sort\_name \\
  &$|$& \verb|op| \textit{operator\_reference} ``\verb|->|'' \textit{operator\_reference} \\
  &$|$& \verb|bop| \textit{operator\_reference} ``\verb|->|'' \textit{operator\_reference}
\end{tabular}

A sort name may be qualified by a module name or a parameter name
(Section \ref{sec:p2-naming-and-qualification}),
and has to be visible for \verb|sort|, and hidden for \verb|hsort|.
An operator reference is an operator name, or a term that denotes
a derived operator. An operator reference may also be qualified. And
needless to say, \verb|op| is for non-behavioural operators, and
\verb|bop| is for behaviourals.

For a source operator, only operator names, or terms that denotes
original operators, is allowed. Using the example of \verb|MULT|
with variables \verb|X| and \verb|Y|,
\begin{vvtm}
\begin{ccode}
  _*_
  X * Y
\end{ccode}
\end{vvtm}
are allowed, while
\begin{vvtm}
\begin{ccode}
  s(0)
  s(X) * Y
  X * X
\end{ccode}
\end{vvtm}
are not.

A variable declaration is as in Section \ref{sec:p2-variable-decl}, like
\begin{vvtm}
\begin{ccode}
  vars X Y : Nat
\end{ccode}
\end{vvtm}
where sort names are those in the {\em source} module.

\begin{warning}
  You may sometimes omit commas between view elements, but it is
  safer always to put them.
\end{warning}

For a view declaration to define a specification morphism, the maps
must satisfy the conditions for signature morphisms, and
the actual parameter must satisfy the translated axioms of the formal
(See \ref{sec:p2-pre-view}). And we remark that
\begin{itemize}
\item If operators are
  overloaded, a single map determines a correspondence between all the
  overloaded operators at once;
\item A view may be endomorphic, and not necessarily be the identity mapping
  at that; and
\item A view need not be onto, nor one-to-one.
\end{itemize}

\begin{warning}
  The system only checks syntactic conditions. To check theory inclusion,
  you need a powerful theorem prover, which is lacking in the current
  system.
\end{warning}

\begin{warning}
  Equational theory attributes (Section \ref{sec:p2-equational-theory})
  act like axioms when views are considered: associativity, for example,
  is an axiom that must hold in the actual parameter.
%  However,
%  for equational theory attributes, the system imposes a stronger requirement:
%  the same attributes must be specified for actual operators.
  In the spirit of checking only syntactic conditions, the system
  ignores these attributes.
\end{warning}

\begin{warning}
  The system does not check every syntactic conditions.
\end{warning}

\subsection{Views Galore}\label{sec:p2-views-exs}

We illustrate the definitions and remarks by several examples.
A first example maps \verb|MONOID| to \verb|SIMPLE-NAT|
(Sections \ref{exs:monoid} and \ref{exs:simple-nat}).
\begin{vvtm}
\begin{ccode}
  view NAT-AS-MONOID from MONOID to SIMPLE-NAT {
    sort M -> Nat,
    op e -> 0,
    op _*_ -> _+_
  }
\end{ccode}
\end{vvtm}
This mapping is certainly a signature morphism, since,
by replacing \verb|M| with \verb|Nat|, the ranks of
\verb|e| and ``\verb|_*_|'' match \verb|0| and ``\verb|_+_|'' respectively.
And we can show that, for variables \verb|X|, \verb|Y|, and \verb|Z|
of sort \verb|Nat|, the equations
\begin{vvtm}
\begin{ccode}
  eq (X + Y) + Z = X + (Y + Z) .
  eq 0 + X = X .
  eq X + 0 = X .
\end{ccode}
\end{vvtm}
hold under the theory of \verb|SIMPLE-NAT|
(but this requires a non-trivial proof; we shall come to this later).
Now consider another monoid, natural numbers under multiplication:
\begin{vvtm}
\begin{ccode}
  view NAT-AS-MONOID' from MONOID to MULT {
    sort M -> Nat,
    op e -> s(0),
    op _*_ -> _*_
  }
\end{ccode}
\end{vvtm}
\verb|MULT| was in Section \ref{exs:mult}. Here \verb|M| is mapped to
the same sort \verb|Nat| as before, but the operators are mapped
differently. Note first that ``\verb|_*_|'' refers to two distinct operators:
over \verb|M| and \verb|Nat|. Further note that the constant
\verb|e| is mapped to \verb|s(0)|, which is {\em not} a constant declared
in \verb|MULT|. It is a derived operator, and this view shows why
a view is defined to be a mapping to the derived specification.
To show that \verb|NAT-AS-MONOID'| defines a specification morphism, we
need to prove
\begin{vvtm}
\begin{ccode}
  eq (X * Y) * Z = X * (Y * Z) .
  eq s(0) * X = X .
  eq X * s(0) = X .
\end{ccode}
\end{vvtm}
Note, finally, that we may as well replace \verb|SIMPLE-NAT| by \verb|MULT|
as the target of \verb|NAT-AS-MONOID|, since \verb|MULT| imports every
declaration of \verb|SIMPLE-NAT|. This fact confirms the observation that
there can be more than one views between two modules.

We now turn to somewhat artificial examples. For the sake of brevity, let
us define a module without axioms:
\begin{vvtm}
\begin{ccode}
  module NAT-INT {
    [ Nat < Int ]
    op _+_ : Nat Nat -> Nat
    op _+_ : Int Int -> Int
  }
\end{ccode}
\end{vvtm}
Then we have a view
\begin{vvtm}
\begin{ccode}
  view ID from NAT-INT to NAT-INT {
    sort Nat -> Nat,
    sort Int -> Int,
    op _+_ -> _+_
  }
\end{ccode}
\end{vvtm}
which is just the pair of identity mappings. Note that the operator map
denotes two maps, for ``\verb|_+_|'' on \verb|Nat| and that on \verb|Int|.
This is an example of overloaded operators being bundled into one
(Section \ref{sec:p2-operator-reference}).

We have other endomorphisms.
\begin{vvtm}
\begin{ccode}
  view U from NAT-INT to NAT-INT {
    sort Nat -> Nat,
    sort Int -> Nat,
    op _+_ -> _+_
  }

  view L from NAT-INT to NAT-INT {
    sort Nat -> Int,
    sort Int -> Int,
    op _+_ -> _+_
  }
\end{ccode}
\end{vvtm}
\verb|U| collapses \verb|Nat| and \verb|Int| into \verb|Nat|. Recall that the
conditions on signature morphisms only require preservation of weak sort
ordering. \verb|Nat < Nat| holds\footnote{
Remember that \texttt{<} denotes less than \emph{or equal to}.
}, so \texttt{U} does define a signature morphism. The case of \texttt{L} is
similar, collapsing the two sorts into \texttt{Int}.
Even with relatively simple structures like this,
you have a couple of different views between modules.

\subsection{Not Quite a View}\label{sec:p2-non-view-exs}

We show why the conditions on views (see Section \ref{sec:p2-pre-view},
on specification morphisms) are reasonable.
It is easy to see why you have to preserve ranks and sort ordering.
For example, given a module
\begin{vvtm}
\begin{ccode}
  module FUNCTION {
    [ S T ]
    op f : S -> T
  } 
\end{ccode}
\end{vvtm}
and a self-mapping
\begin{vvtm}
\begin{ccode}
  sort S -> T
  sort T -> S
  op f -> f
\end{ccode}
\end{vvtm}
it is hard to know where to locate the image of \verb|f|.

The conditions on hidden sorts and behavioural operators ensure the
preservation of visibility --- mapping hiddens to hiddens, behaviourals
to behaviourals --- and observations. The following
counterexample illustrates the reason why views must reflect
hidden sort ordering and be surjective on behavioural operators.
Recall the module \verb|COUNTER| (Section \ref{exs:counter}), and
consider a module of bank accounts:\label{exs:account}
\begin{vvtm}
\begin{ccode}
  module SUBTRACT {
    protecting (SIMPLE-NAT)
    op _-_ : Nat Nat -> Nat
    vars N N' : Nat
    eq 0 - N = 0 .
    eq N - 0 = N .
    eq s(N) - s(N') = N - N' .
  }

  module* ACCOUNT {
    protecting (SUBTRACT)
    *[ Account ]*
    bops deposit withdraw : Account Nat -> Account
    bops balance point : Account -> Nat
    var N : Nat
    var A : Account
    eq balance(deposit(A, N)) = balance(A) + N .
    eq balance(withdraw(A, N)) = balance(A) - N .
    eq point(deposit(A, N)) = point(A) + s(0) .
  }
\end{ccode}
\end{vvtm}
``\verb|_-_|'' on \verb|Nat| is the usual pseudo-subtraction
(you have already seen this definition in Section \ref{exs:simple-nat+},
as a preparation to declare \verb|GCD|).
An account has a balance and a ``bonus point''. The bonus point
increases each time you make a deposit. If you identify a counter
reading with the amount of your fortune,
it seems plausible to define a view, by the following mapping.
\begin{vvtm}
\begin{ccode}
  sort Zero -> Zero
  sort NzNat -> NzNat
  sort Nat -> Nat
  op 0 -> 0
  op s -> s
  op _+_ -> _+_
  var N : Nat
  var C : Counter
  hsort Counter -> Account
  bop add(N, C) -> deposit(C, N)
  bop read -> balance
\end{ccode}
\end{vvtm}
Note first the appearance of \verb|Zero|, \verb|NzNat|, et al.
A view defines a mapping of all the sorts and operators, including those
declared in imported modules\footnote{
Even implicitly imported modules. We ignore them here, for your health.
}.
As a result, views easily become large.
And quite often, they contain a large uninformative set of maps --- the
identitiy maps, like here. There is a way to cut them out. See Section
\ref{sec:p2-succinct-view}.

Note also the usage of variables. In mapping
\begin{vvtm}
\begin{ccode}
  bop add : Nat Counter -> Counter
\end{ccode}
\end{vvtm}
to
\begin{vvtm}
\begin{ccode}
  bop deposit : Account Nat -> Account
\end{ccode}
\end{vvtm}
you need to change the order of arguments. Variables and derived opeartors
are used to state this permutation. In the term \verb|deposit(C,N)|, the
variable \verb|C| is interpreted as that of \verb|Account|, according to
the sort map from \verb|Counter| to \verb|Account|.

Let us return to conditions on views. This mapping does not
constitute a view, since
\verb|withdraw| and \verb|point| are not in the image of the
mapping. This oversight is harmful. It can be shown that in
\verb|COUNTER| the behavioural equation
\begin{vvtm}
\begin{ccode}
  beq add(m + n, c) = add(n, add(m, c)) .
\end{ccode}
\end{vvtm}
holds for any \verb|m|, \verb|n| of sort \verb|Nat| and for any
\verb|c| of sort \verb|Counter|, while its counterpart
\begin{vvtm}
\begin{ccode}
  beq deposit(a, m + n) = deposit(deposit(a, m), n) .
\end{ccode}
\end{vvtm}
in \verb|ACCOUNT| does not. The reason is that the observation
\verb|point(A:Account)| distinguishes the two terms:
thus behavioural equivalence is not preserved under this mapping ---
even though the (single) axiom of \verb|COUNTER| is preserved.

You should have ensured that no additional observation is imposed on
(the image of) \verb|Counter|. The conditions on views are sufficient
for this purpose. And note well that, if you pay respect to the
conditions, behavioural equivalence is preserved whenever
the {\em explicitly given}, {\em finite} axioms are preserved.

\subsection{Succinct Views}\label{sec:p2-succinct-view}

Fully to spell out the necessary maps may lead to unwieldy views.
In the previous section, you already get a hunch that imported sorts and
operators induce explosion. In fact,
it is possible to omit some obvious maps: the system guesses the
missing pieces by the following rules. Unless explicitly written
otherwise,
\begin{itemize}
\item[1.] If the source and target modules have common submodules,
  all the sorts and modules declared therein are assumed to
  be mapped to themselves;
\item[2.] If the source and target modules have sorts and/or operators
  with identical names, they are mapped to their respective namesakes; and
\item[3.] If the source module has a single sort and the target has
  a {\em principal} sort\index{principal sort}, the single sort is
  mapped to the principal.
\end{itemize}
The rules 1. and 2. are obviously helpful: they allow you to omit the obvious.

A principal sort is declared within the header part of
a module declaration, as follows.

\begin{bsyntax} module with principal sort \index{\texttt{principal-sort}} \Hline
\texttt{module} \textit{module\_name} $[$``\texttt{(}'' \textit{list\_of\_parameters} ``\texttt{)}''$]$ \texttt{principal-sort} \textit{sort\_name} ``\texttt{\{}''  
~~~~\textit{module\_element} $*$
``\texttt{\}}''
\end{bsyntax}

\verb|principal-sort| may be abbreviated to \verb|p-sort|.
\index{\texttt{p-sort}}
A sort name refers to a sort that is declared within the module, or in an
imported module.
Let us show some examples. If you have
\begin{vvtm}
\begin{ccode}
  module* ONE { [ Elt ] }
\end{ccode}
\end{vvtm}
and
\begin{vvtm}
\begin{ccode}
  module! SIMPLE-NAT' principal-sort Nat {
    ... the same as SIMPLE-NAT
  }
\end{ccode}
\end{vvtm}
it is possible to declare a view
\begin{vvtm}
\begin{ccode}
  view V from ONE to SIMPLE-NAT' { }
\end{ccode}
\end{vvtm}
which apparently is an empty mapping. This is equivalent to
\begin{vvtm}
\begin{ccode}
  view V from ONE to SIMPLE-NAT' { sort Elt -> Nat }
\end{ccode}
\end{vvtm}
Since great many views are from single-sort modules,
principal sorts are very useful for making views compact.

If so declared, a sort is principal in and only in that module, and
principality is {\em not} obtainable via importation\footnote{
You may buy out Monaco, but it is another matter.
}.

\begin{warning}
  The current version does not support all the mechanisms explained
  here. Identifying sorts or operators by name
  is sometimes tedious --- you may have to probe the depth of the module
  hierarchy. Or controvertial. Consider, e.g.,
  ``\verb|_+_|'' for natural number addition and for direct summation of sets.
\end{warning}

It is also possible to shorten views by importation.
\index{importation (of views)}

\begin{warning}
  At the time of writing, it is not possible. We have not even worked
  out a relevant syntax.
\end{warning}

\section{Binding Parameters}

\subsection{Instantiation of Parameterised Modules}
\label{sec:p2-module-instantiation}

An instance of a parameterised module is created by
binding actual parameters to formals. The process of binding is
called {\em instantiation}\index{instantiation}. 
The result of instantiation is a new module, obtained by
replacing occurrences of parameter sorts and operators by actuals.
If, as a result of instantiation, a module is imported twice,
it is assumed to be imported once, and shared throughout
(Section \ref{sec:p2-module-sharing}).

Syntactically, instantiation binds a view to a parameter.

\begin{bsyntax} instantiating parameterised module \Hline
\textit{module\_name} ``\texttt{(}'' \textit{binding} $+_,$ ``\texttt{)}''
\end{bsyntax}

There are two distinct kinds of binding constructs.

\paragraph{Instantiation by Declared Views}

You may bind an already declared view to a parameter.

\begin{tabular}{r c l}\index{\texttt{<=}}
  \textit{binding} &::=& \textit{parameter\_name} ``\verb|<=|'' \textit{view\_name}
\end{tabular}

If a module \verb|M| has a parameter ``\verb|X :: T|'' and a view
\verb|V| from \verb|T| to \verb|M'| is declared,
\verb|V| may be bound to \verb|X|, with the effect that
\begin{itemize}
\item[1.] The sort and operator names of \verb|T|
  that appear in the body of \verb|M| are replaced by
  those in \verb|M'|, in accordance with \verb|V|, and
\item[2.] The common submodules of \verb|M| and \verb|M'| are shared.
\end{itemize}

\paragraph{Instantiation by Ephemeral Views}

It is possible to declare and bind a view simultaneously.

\begin{tabular}{r c l}\index{\texttt{view}}\index{\texttt{to}}
  \textit{binding} &::=& \textit{parameter\_name} ``\verb|<=|'' \textit{view} \\
  \textit{view} &::=& \verb|view| \verb|to| \textit{module\_name}
     ``\verb|{|'' \textit{view\_element} $*$ ``\verb|}|''
\end{tabular}

where ``\verb|{|'', ``\verb|}|'' encloses the same constructs as in view
declarations. The view is valid only within the instantiation.
For example,\label{exs:nat-ilist}
\begin{vvtm}
\begin{ccode}
   module NAT-ILIST {
     protecting (ILIST(IDX <= view to SIMPLE-NAT { sort Elt -> Nat },
                       DAT <= view to SIMPLE-NAT { sort Elt -> Nat }))
   }
\end{ccode}
\end{vvtm}
binds a \verb|SIMPLE-NAT| to the parameter \verb|IDX| and \verb|DAT|,
via an identical view from \verb|ONE| (see Section \ref{exs:simple-nat} for
\verb|SIMPLE-NAT|, Section \ref{exs:ilist} for
\verb|ILIST| and \verb|ONE|). The code is equivalent to
\begin{vvtm}
\begin{ccode}
  view V from ONE to SIMPLE-NAT { sort Elt -> Nat }

  module NAT-ILIST {
    protecting (ILIST(IDX <= V, DAT <= V))
  }
\end{ccode}
\end{vvtm}
An ephemeral view may be as succinct as a everlasting counterpart, with
resort to principality and titular coincidence.

To make the code more concise, it is possible to identify parameters
by positions, not by names. \verb|NAT-ILIST| may then be defined by
\begin{vvtm}
\begin{ccode}
  module NAT-ILIST {
    protecting (ILIST(V,V))
  }
\end{ccode}
\end{vvtm}
or, more ephemerally,
\begin{vvtm}
\begin{ccode}
  module NAT-ILIST {
    protecting (ILIST(SIMPLE-NAT { sort Elt -> Nat },
                      SIMPLE-NAT { sort Elt -> Nat }))
  }
\end{ccode}
\end{vvtm}
Note that in the latter code ``\verb|view to|'' constructs are omitted.

\subsection{Parameters as Imports}\label{sec:p2-params-as-subs}

A parameter may be regarded as a submodule. If so regarded,
it poses a question of importation modes (Section \ref{sec:p2-import-decl})
and module contexts (Section \ref{sec:p2-current-module}).
Indeed, it is possible to specify an importation mode for a parameter, as in
\begin{vvtm}
\begin{ccode}
  module M (extending X :: T) \{ ...
\end{ccode}
\end{vvtm}
Available modes are the same as with plain importations: \verb|protecting|,
\verb|extending|, and \verb|using|. The default mode is \verb|protecting|.
You can check by feeding \verb|ILIST| (Section \ref{exs:ilist}) and
print parameters as follows.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select ILIST

  ILIST(IDX,DAT)> show params
  argument IDX : protecting ONE
  argument DAT : protecting ONE

  ILIST(IDX,DAT)> 
\end{ccode}
\end{vvtm}
Note in passing that the new prompt shows parameters as well as the module
name \verb|ILIST|.

%\begin{warning}
%  The current version is very verbose and print formal parameter modules
%  as well, as in
%  \begin{vvtm}
%\begin{ccode}
%    ILIST(IDX::ONE ,DAT::ONE)> 
%  \end{ccode}
%\end{vvtm}
%\end{warning}

\begin{warning}
  As stated in Section \ref{sec:p2-import-decl}, the system does not
  care if you have chosen an incorrect importation mode. Since
  various modules are to be bound to parameters, you should be especially
  cafeful.
\end{warning}

As to contexts, a parameter is included in the context graph of the module.
The difference from plainly imported modules is that the edge has
a name. For example, if \verb|M| imports \verb|M'|, the edge is anonymous
\begin{quotation}
  \verb|M| $\longrightarrow$ \verb|M'|
\end{quotation}
while if \verb|M| has a parameter ``\verb|X :: M'|'', the edge is
\begin{quotation}
  \texttt{M} $\buildrel \mbox{\texttt{X}} \over \longrightarrow$ \texttt{M'}
\end{quotation}
Moreover, since a module may have the same parameter with different names,
a context graph is in general a hypergraph.

Some aspects of instantiation is better explained in terms of such graphs.
Instantiation is then a process of subgraph replacement, and the
usual considerations --- indentifying which edges with which,
determining targets of edges, avoiding dangling edges, and so on --- are
relevant to the process of instantiation.

\subsection{Parameter Passing}

Since a parameterised module is a module, it may be imported.
You may enrich \verb|ILIST| (Section \ref{exs:ilist}), adding
an operator that counts entries.
\begin{vvtm}
\begin{ccode}
  module ILIST-EXT {
    protecting (ILIST)
    protecting (SIMPLE-NAT)
    op #_ : Ilist -> Nat
    var I : Elt.IDX
    var D : Elt.DAT
    var L : Ilist
    eq # put(I,D,L) = s(0) + (# L) .
    eq # empty = 0 .
  }
\end{ccode}
\end{vvtm}
The definition of ``\verb|#_|'' is obvious, but this module is
interesting in that it imports a parameterised module without
instantiation. Let us see how the system treats such a module.
After feeding \verb|ILIST-EXT|, you get
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select ILIST-EXT

  ILIST-EXT(IDX, DAT)> show params
  argument IDX.ILIST : protecting ONE
  argument DAT.ILIST : protecting ONE

  ILIST-EXT(IDX, DAT)> show param IDX
  module* IDX.ILIST :: ONE {
    imports {
      protecting (BOOL)
    }
    signature {
      [ Elt ]
    }
  }

  ILIST-EXT(IDX, DAT)> 
\end{ccode}
\end{vvtm}
Look first at the new prompt. In the previous section, after
the parameterised \verb|ILIST| was \verb|select|ed, the prompt
changed to
\begin{vvtm}
\begin{ccode}
  ILIST(IDX, DAT)> 
\end{ccode}
\end{vvtm}
to indicate that the current module had two parameters. The \verb|select|ion
here of \verb|ILIST-EXT| also led to the prompt suggesting parameters.
As the \verb|show| commands showed, this module indeed has parameters
\verb|IDX| and \verb|DAT|, which are both the module \verb|ONE|.
%The new prompt indicates that these parameters were derived from
%\verb|ILIST|.

%\begin{warning}
%  The current version is very verbose, and in the above case the prompt is
%  \begin{vvtm}
%\begin{ccode}
%    ILIST-EXT(IDX.ILIST::ONE, DAT.ILIST::ONE)> 
%  \end{ccode}
%\end{vvtm}
%\end{warning}

Since \verb|ILIST-EXT| is thus parameterised, you can instantiate it,
just as you instantiate \verb|ILIST|. For example,
\begin{vvtm}
\begin{ccode}
  module NAT-ILIST-EXT {
    protecting (ILIST-EXT(IDX <= view to SIMPLE-NAT { sort Elt -> Nat },
                          DAT <= view to SIMPLE-NAT { sort Elt -> Nat }))
  }
\end{ccode}
\end{vvtm}
defines a module of enriched indexed lists whose indices and data are
both natural numbers.

In importing parameterised modules, you can bind parameters to
parameters --- ``passing parameters'', as in the following
construction.
\begin{vvtm}
\begin{ccode}
  module ILIST' (X :: ONE) {
    protecting (ILIST(X, X))
  }
\end{ccode}
\end{vvtm}
Remember that this shorthand notation means that the default view ---
i.e., identity mapping ---, from
\verb|X| (i.e. \verb|ONE|) to \verb|IDX| and \verb|DAT| (both \verb|ONE|)
is bound to the parameters \verb|IDX| and \verb|DAT|. The result of the
instantiation is the sort of indexed lists whose indices and data
belong to the same (parametric) sort. Let us show a session that reveals
what is going on.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> module ILIST' (X :: ONE) {
    protecting (ILIST(X, X))
  }
  -- defining module ILIST'_.*.,,,,,,_,,*._* done.

  CafeOBJ> select ILIST'

  ILIST'(X)> show params
  argument X : protecting ONE

  ILIST'(X)> show subs
  protecting(ILIST(IDX <= X, DAT <= X))

  ILIST'(X)> 
\end{ccode}
\end{vvtm}
The module \verb|ILIST'| has a parameter \verb|X| and imports an
instance of \verb|ILIST| to whose parameters \verb|X| are bound.
We continue the session and create an instance of \verb|ILIST'|.
\begin{vvtm}
\begin{ccode}
  ILIST'(X)> module ILIST'-NAT {
    pr (ILIST'(X <= view to SIMPLE-NAT { sort Elt -> Nat }))
  }

  -- defining module ILIST'-NAT,,,,,,,*,,,,,,,*._* done.
  ILIST'(X)> 
\end{ccode}
\end{vvtm}
\verb|ILIST'-NAT| is a module of indexed lists whose indices and data
are both natural numbers --- which is the same module as
\verb|ILIST-NAT| in the previous section.

Finally, you may use this parameter passing mechanism to get
an alternative definition of enriched indexed lists, as follows.
\begin{vvtm}
\begin{ccode}
  module ILIST-EXT (IDX :: ONE, DAT :: ONE) {
    protecting (ILIST(IDX, DAT))
    protecting (SIMPLE-NAT)
    op #_ : Ilist -> Nat
    var I : Elt.IDX
    var D : Elt.DAT
    var L : Ilist
    eq # put(I,D,L) = s(0) + (# L) .
    eq # empty = 0 .
  }
\end{ccode}
\end{vvtm}

\subsection{Parameters with Parameters}

There are also cases when parameter modules themselves are parameterised.
Consider the following example.
\begin{vvtm}
\begin{ccode}
  module* ONE { [ Elt ] }
  module* STACK (X :: ONE) {
    [ Stack ]
    op push : Elt Stack -> Stack
  }

  module TRAY (Y :: STACK) {
    [ Tray ]
    op tray : Stack Stack -> Tray
    ops in-tray out-tray : Tray -> Stack
    op in : Elt Tray -> Tray 
    var E : Elt
    vars S S' : Stack
    eq in(E, tray(S,S')) = tray(push(E,S),S') .
    trans tray(push(E,S),S') => tray(S, push(E, S')) .
    eq in-tray(tray(S,S')) = S .
    eq out-tray(tray(S,S')) = S' .
  }
\end{ccode}
\end{vvtm}
The module \verb|TRAY| is intended to describe the desk of an
important executive. The parameter \verb|STACK| of this
module itself has a parameter \verb|ONE| (the same as the one
in Section \ref{exs:ilist}).

There are two ways to instantiate \verb|TRAY|:
\begin{itemize}
\item[a.] Instantiate \verb|Y|, or
\item[b.] Instantiate \verb|X| of \verb|Y|.
\end{itemize}
In case of a., \verb|Y| should be bound by a module which has
the same module \verb|ONE| as parameter. For example,
if you have defined
\begin{vvtm}
\begin{ccode}
  module LIST (X :: ONE) {
    [ NeList < List ]
    op nil : -> List
    op __ : Elt List -> NeList
    op __ : Elt NeList -> NeList
    op head_ : NeList -> Elt
    op tail_ : NeList -> List
    var E : Elt
    var L : List
    eq head (E L) = E .
    eq tail (E L) = L .
  }
\end{ccode}
\end{vvtm}
you may bound \verb|LIST|\footnote{
It has been a ritual to embed elements as one-length lists with
a subsort declaration. This practice is not recommended since you
may unable to get pushouts as desired. See the Haxhausen's paper
in AMAST'96 for detail.
} to the parameter \verb|Y|, as
\begin{vvtm}
\begin{ccode}
  view LIST-AS-STACK from STACK to LIST {
    sort Stack -> NeList,
    op push -> __
  }

  module LIST-TRAY {
    protecting (TRAY(Y <= LIST-AS-STACK))
  }
\end{ccode}
\end{vvtm}
The result is a module with parameter \verb|X| (originated from \verb|LIST|).
This module defines trays of lists of \verb|Elt|. Note that
\verb|LIST-AS-STACK| omits the map from \verb|Elt| of \verb|X| to itself.
This is an example of implicit submodule mapping
(cf. Section \ref{sec:p2-succinct-view}).
You may further instantiate \verb|LIST-TRAY|, by binding something to
\verb|X| --- which is \verb|ONE|, the module of an arbitrary set.

In case of b., you bind something to \verb|X| (of \verb|STACK|), which
is the module \verb|ONE|. For example,
\begin{vvtm}
\begin{ccode}
  module NAT-TRAY {
    protecting (TRAY(X.Y <= view to SIMPLE-NAT { sort Elt -> Nat }))
  }
\end{ccode}
\end{vvtm}
creates a module whose trays consist of
stacks of natural numbers ---
trays of mathematicians, perhaps. Note that \verb|X.Y| is a
qualification of a parameter name by another parameter name
(cf. Section \ref{sec:p2-naming-and-qualification}).
%You may further instantiate \verb|NAT-TRAY|, by binding something
%to \verb|Y| --- which is a module of natural number stacks.
\verb|NAT-TRAY| is not parametric; as a result of the instantiation,
\verb|STACK| becomes in effect a plain submodule of \verb|NAT-TRAY|.

%\begin{warning}
%  The current implementation does not work as explained. After creating
%  \verb|NAT-TRAY|, no parameter is left.
%\end{warning}

\subsection{Qualifying Parameter Names}

Parameter names may conflict, when a parameterised module imports
another parameterised module. To disambiguate parameter names, you may
qualify them by module names
(Section \ref{sec:p2-naming-and-qualification}). For example, in
\begin{vvtm}
\begin{ccode}
  module A ( X :: B ) { ... }
  module C ( X :: D ) {
    protecting (A)
    ...
  }
\end{ccode}
\end{vvtm}
\verb|X| is both the parameter name of \verb|A| and that of \verb|C|,
and is ambiguous in \verb|C|. You may refer to \verb|X| of \verb|A|
by ``\verb|X.A|''. The plain \verb|X|, in \verb|C|, refers to \verb|X|
of \verb|C|. This means that a sort or operator name may be
qualified by a parameter name which itself is qualified by a module
name. Since a term may be qualified by a sort name also
(see Section \ref{sec:p2-parsing-qualifier}), a chain of qualifications
such as
\begin{vvtm}
\begin{ccode}
  (f(a)):S.P.M
\end{ccode}
\end{vvtm}
is possible. If there is any ambiguity, qualifier ``\verb|.|'' is
considered right associative.

\section{Module Expression}\label{sec:p2-module-expression}

Syntactically, an instantiation of parameterised modules is an expression
involving module names. There are other kinds of such expressions.
Expressions over module names are called {\em module expression\/}s.
\index{module expression}
A module expression represents a module,
and may appear in import declarations or in several commands.
Here we summarise the syntax of module expressions.

\subsection{Module Name}

The simplest module expressions are module names.

\begin{bsyntax} module constant \Hline
\textit{module\_name}
\end{bsyntax}

A module represented by a module name is the module itself.

\subsection{Renaming}

{\em Renaming}\index{renaming} is to change sort or operator
names, creating a new module.

\begin{bsyntax} renaming \index{\texttt{*} (for remaning)} \Hline
\textit{module\_expression} ``\texttt{*}'' ``\texttt{\{}'' \textit{map} $*_,$ ``\texttt{\}}''
\end{bsyntax}

where a map is

\index{\texttt{sort}}\index{\texttt{op}}\index{\texttt{param}}
\index{\texttt{hsort}}\index{\texttt{bop}}
\begin{tabular}{r c l}
  \textit{map} &::=& \verb|sort| \textit{sort\_name} ``\verb|->|'' \textit{sort\_name} \\
      &$|$& \verb|hsort| \textit{sort\_name} ``\verb|->|'' \textit{sort\_name} \\
      &$|$& \verb|op| \textit{operator\_name} ``\verb|->|'' \textit{operator\_name} \\
      &$|$& \verb|bop| \textit{operator\_name} ``\verb|->|'' \textit{operator\_name} \\
\end{tabular}

Maps are as expected: \verb|sort| maps visible sorts, \verb|hsort| invisibles,
\verb|op| ordinary operators, \verb|bop| behaviourals, and \verb|param|
parameters. Sort and operator names should
be familiar now. Source names may be qualified; target names may not
(they are supposed to be brand-new names).

\begin{warning}
  Commas may be omitted.
\end{warning}

Note that renaming creates a new, different module, even if it has
isomorphic models. A consequence is that a renamed module is not
shared (cf. Section \ref{sec:p2-module-sharing}).

\begin{warning}
  Renaming is meant to describe a bijective signature
  morphism (Section \ref{sec:p2-pre-view}). The current implementation allows
  more flexible renaming, however, and you may collapse
  two distinct sort/operators into one. If you do give such a renaming,
  care should be taken.
\end{warning}

Renaming is quite often used in combination with instantiations.
Since instantiation is a (module-level) operation that generates
specific data types from generic ones, it is natural for you to
confer names that describe specialised sorts and operators more
effectively. For example, in specialising generic indexed lists to those of
natural numbers (Section \ref{exs:nat-ilist}), you may write
\begin{vvtm}
\begin{ccode}
  module NAT-ILIST {
    protecting (ILIST(IDX <= view to SIMPLE-NAT { sort Elt -> Nat },
                      DAT <= view to SIMPLE-NAT { sort Elt -> Nat })
                  * { sort IList -> IList-of-Nat })
  }
\end{ccode}
\end{vvtm}
In the parameterised \verb|ILIST|, a simple \verb|IList| is okay to
denote lists of something. After instantiation, a list is a list
of natural numbers, so why not call it as it is.

\subsection{Module Sum}

Combining several modules together is another common module-level
operation. The combined whole is called {\em module sum}\index{module sum}.

\begin{bsyntax} module sum \index{\texttt{+} (module sum)} \Hline
\textit{module\_expression} ``\texttt{+}'' \textit{module\_expression} $\{$ ``\texttt{+}'' \textit{module\_expression} $\}$ $*$
\end{bsyntax}

A module represented by a module sum consists of all the module elements in
the summands. If submodules are imported more than once, it is assumed to
be imported once, and is shared throughout
(Section \ref{sec:p2-module-sharing}).
This construction is sometimes called {\em amalgamated sum} or
{\em shared sum}.\index{amalgamated sum}\index{shared sum}
From this definition, it follows that
\begin{vvtm}
\begin{ccode}
  module A { protecting (B + C) ... }
\end{ccode}
\end{vvtm}
is equivalent to
\begin{vvtm}
\begin{ccode}
  module A { protecting (B) protecting (C) ... }
\end{ccode}
\end{vvtm}

\subsection{Making Modules}\label{sec:p2-make-command}

Module expressions are often used in isolation. To create a module, it is
often the case that you simply import a module represented by an expression,
as
\begin{vvtm}
\begin{ccode}
  module LOVE {
    protecting (...)
 }
\end{ccode}
\end{vvtm}
where ``\verb|...|'' is a module expression. The purpose of this
declaration is to give a name to a module defined by the expression.
C'est tout. In such a case, an abbreviation is handy.

\begin{bsyntax} \texttt{make} command \index{\texttt{make}} \Hline
\texttt{make} \textit{module\_name} ``\texttt{(}'' \textit{module\_expression} ``\texttt{)}''
\end{bsyntax}

\verb|make| evaluates the module expression and confer the resulting
module with the given name.
In fact, this is a shorthand of the protecting importation as above.
You may want to try this:
\begin{vvtm}
\begin{ccode}
  CafeOBJ> make LOVE (SIMPLE-NAT)

  -- defining module LOVE._* done.
  CafeOBJ> show LOVE
  module LOVE {
    imports {
      protecting (SIMPLE-NAT)
    }
  }

  CafeOBJ> 
\end{ccode}
\end{vvtm}


%\subsection{Rules with Hidden Sorts}
%
%% but should this be mentioned in the manual?
%
%In \verb|NAT-COUNTER|, \verb|Counter| acquires a
%non-trivial reachability relation. For example,
%\begin{vvtm}
%\begin{ccode}
%  add(s(0), init)
%\end{ccode}
%\end{vvtm}
%may be reached from
%\begin{vvtm}
%\begin{ccode}
%  add(s(0) | s(s(0)), init)
%\end{ccode}
%\end{vvtm}
%The reasoning is as follows.
%\begin{itemize}
%\item[] \verb?add(s(0) | s(s(0)), init)? reads as \verb?s(0) | s(s(0)) + 0?,
%  from two equations in \verb|COUNTER|.
%\item[] \verb?s(0) | s(s(0)) + 0? equals \verb?s(0) | s(s(0))?
%  since \verb|0| is the identity.
%\item[] Similarly, \verb?add(s(0), init)? reads as \verb|s(0)|.
%\item[] More generally, every context reads
% \verb?n + s(0) | s(s(0))? and \verb|n + s(0)| respectively,
% for the same \verb|n|.
%\item[] For any \verb|n|, \verb|n + s(0)| is
% reachable from \verb?n + s(0) | s(s(0))?, by a rule in \verb|HUMANE-NAT|
% and because reachability is congruent.
%\item[] Therefore, in every context, the read of
% \verb?add(s(0), init)? is reachable from
% \verb?add(s(0) | s(s(0)), init)?.
%\item[] Therefore, behaviourally, the result holds.
%\end{itemize}
%
%By the technique explained in \ref{sec:p2-open-close} as adapted to
%coinduction scheme, it is possible to realise the above reasoning
%as a proof score in \cafeobj.
%
%Beware, however, that
%na{\" \i}ve combination of a set of equations and that of
%rules may result in an undesirable proof. For example,
%an indiscriminate use of rules and equations results in the
%following rewrite sequence.
%\begin{vvtm}
%\begin{ccode}
%  read(add(s(0) | s(s(0)), init)) -->
%  read(add(s(0), init)) -->
%  s(0) + read(init) -->
%  s(0)
%\end{ccode}
%\end{vvtm}
%where the first rewrite uses a rule in \verb|HUMANE-NAT|. This
%reduction cannot be used to reason about \verb|Counter|'s behaviour,
%since the context was changed before observation.
%In general, in reasoning about behavioural equivalence or
%reachability, you should use \verb|reduce|, which exludes rules,
%instead of \verb|exec|, which does not.

\chapter{Theorem-Proving Tools}\label{sec:p2-theorem-proving}

The TRS engine (Chapter \ref{sec:p2-term-evaluation}) may be used as a
lightweight theorem prover. In addition, the current version of the
system supports a couple of commands that act as theorem-proving
tools.

\section{Open/Closing Modules}\label{sec:p2-open-close}

There are commands to modify module declarations. To start modifying a
module, use the command

\begin{bsyntax} \texttt{open} command \index{\texttt{open}} \Hline
\texttt{open} \textit{module\_name}
\end{bsyntax}

This command enables you to declare new sorts, operators, equations,
and so on. Just type declarations after this command.
You cannot, however, change or delete the existing declarations.

To finish the modification, use the command

\begin{bsyntax} \texttt{close} command \index{\texttt{close}} \Hline
\texttt{close}
\end{bsyntax}

\subsection{Why Opening Modules?}\label{sec:p2-usage-of-open}

The effects of declarations supplied in between \verb|open| and
\verb|close| commands are temporary.
\begin{itemize}
\item An \verb|open| command creates a new module. This module contains
  a copy of declarations in the given module.
\item Until the module is \verb|close|d, all the declared sorts,
  equations, etc. are added to the new module.
\item \verb|close| expunges the new module.
\end{itemize}
So \verb|close| makes all your efforts banish. What is the sense of it all?
Well, this open/closing mechanism is an ecological tool to (1) make
hypotheses,
(2) prove, by evaluation, your favourite theorems upon the hypotheses,
(3) finish the proof, and delete the hypotheses, (1') start again with
new hypotheses, \ldots

For example, consider the familiar module \verb|SIMPLE-NAT|, reprinted here.
\begin{vvtm}
\begin{ccode}
  module SIMPLE-NAT {
    [ Zero NzNat < Nat ]
    op 0  : -> Zero
    op s : Nat -> NzNat 
    op _+_ : Nat Nat -> Nat
    vars N N' : Nat
    eq 0 + N = N .
    eq s(N) + N' = s(N + N') .
  }
\end{ccode}
\end{vvtm}
Suppose you want to show that \verb|0| is a right identity of ``\verb|_+_|''
also. Using the standard structural induction\index{structural induction},
you can prove it easily, by
showing (1) ``\verb|0 + 0|'' equals \verb|0|, and (2) for any \verb|M|,
if ``\verb|M + 0|'' equals \verb|M|, \newline
``\verb|s(M) + 0|'' equals \verb|s(M)|.
A score of this proof may be written, using \verb|open| command, as
\begin{vvtm}
\begin{ccode}
  open SIMPLE-NAT
  op a : -> Nat .
  eq a + 0 = a .
  reduce 0 + 0 .
  reduce s(a) + 0 .
  close
\end{ccode}
\end{vvtm}
When a module is \verb|open|ed, the system changes the prompt beginning
with \verb|%|, as
\begin{vvtm}
\begin{ccode}
  CafeOBJ> open SIMPLE-NAT

  -- opening module SIMPLE-NAT.. done.

  %SIMPLE-NAT> 
\end{ccode}
\end{vvtm}
After \verb|open|ing, module elements and various commands can be input.
The above score adds a new constant \verb|a| (to represent ``any''
natural number) and an equation (for induction hypothesis), and invlokes
reduction commands (base case and induction step). The system evaluates
``\verb|0 + 0|'' and ``\verb|s(a) + 0|'' as usual, and returns the results
\verb|0| and \verb|s(a)|.
\begin{vvtm}
\begin{ccode}
  %SIMPLE-NAT> op a : -> Nat .

  %SIMPLE-NAT> eq a + 0 = a .

  %SIMPLE-NAT> reduce 0 + 0 .
  *
  -- reduce in % : 0 + 0
  0 : Zero
  (0.000 sec for parse, 1 rewrites(0.000 sec), 2 matches)
  %SIMPLE-NAT> reduce s(a) + 0 .

  -- reduce in % : s(a) + 0
  s(a) : NzNat
  (0.000 sec for parse, 2 rewrites(0.000 sec), 4 matches)
  %SIMPLE-NAT> close

  CafeOBJ> 
\end{ccode}
\end{vvtm}
You may have noticed quizzical ``\verb|*|'' in the above
session. They are not print smudges.
When a module is opened, the system processes the subsequent
declarations and commands as if they were entered during a normal
module declaration, and tries to tell you that it is working
furiously (cf. an aside in Section \ref{sec:p2-comment-syntax}).

\begin{warning}
  As you may have noticed in the above example,
  the current implementation requires a blank-period terminator
  for each declaration (note ``\verb| .|'' after the operator
  declaration above).
\end{warning}

The opened module and the current module need not be the same. For
example, if the current module is \verb|NERD|, you can have a session
like
\begin{vvtm}
\begin{ccode}
   NERD> open SIMPLE-NAT

  -- opening module SIMPLE-NAT_.* done.

   %SIMPLE-NAT> select BOOL
   ...
   BOOL> close

   NERD> 
\end{ccode}
\end{vvtm}
By opening \verb|SIMPLE-NAT|, the temporary new module is set to be current,
as indicated by the prompt. \verb|select| command switches the current
module to \verb|BOOL|. \verb|close| restores the previous
current module (remember that the effects of declarations and commands
during opening are temporary).
A convenient way to set the current module while it is
opened is selecting the module ``\verb|%|''.
\begin{vvtm}
\begin{ccode}
  %SIMPLE-NAT> select %

  %SIMPLE-NAT> 
\end{ccode}
\end{vvtm}

\begin{warning}
  As you have guessed, the module name ``\verb|%|'' refers to the 
  temporary module. You should not use ``\verb|%|'' as a module name.
\end{warning}

\subsection{Constant On the Fly}\label{sec:p2-temporary-constant}

Let us think awhile of the example of the previous section. In
the proof score, a constant \verb|a| was declared by
\begin{vvtm}
\begin{ccode}
  op a : -> Nat .
\end{ccode}
\end{vvtm}
to represent {\em any} element of sort \verb|Nat|. Such declarations
appear quite often when you are using the evaluation mechanism to
prove theorems. To prove that \verb|0| is a right identity, \verb|a|
appeared to calculate the induction step
\begin{vvtm}
\begin{ccode}
  reduce s(a) + 0 .
\end{ccode}
\end{vvtm}
To make proofs more concise, you may use on-the-fly declarations
of constants, similar to variable declarations on the fly
(Section \ref{sec:p2-variable-decl}).

\begin{bsyntax} constant declaration on the fly \Hline
\textit{constant\_name}``\texttt{:}''\textit{sort\_name}
\end{bsyntax}

where a constant name is a character string that starts with
the backquote ``\verb|`|''.
The effects of declarations are temporary, like the case of variables.
Using this construct, it is possible to invoke reduction commands,
without \verb|open|ing modules, as
\begin{vvtm}
\begin{ccode}

  CafeOBJ> select SIMPLE-NAT

  SIMPLE-NAT> reduce 0 + 0 .

  -- reduce in SIMPLE-NAT : 0 + 0
  0 : Zero
  (0.000 sec for parse, 1 rewrites(0.000 sec), 1 matches)
  SIMPLE-NAT> reduce s(`a:Nat) + 0 .

  -- reduce in SIMPLE-NAT : s(`a:Nat) + 0
  s(`a:Nat + 0) : NzNat
  (0.000 sec for parse, 1 rewrites(0.000 sec), 6 matches)
  SIMPLE-NAT> 
\end{ccode}
\end{vvtm}
This time, the hypothesis is implicit: instead of stating and using
it explicitly, you take note of it in analysing the result of the
second evaluation.

\begin{warning}
  In fact, you get quite similar effects by using variables on the
  fly, instead of constants. Although evaluation is a procedure
  for ground terms, the system allows variables within terms to
  be reduced. Here is an example corresponding to the second reduction
  above.
  \begin{vvtm}
\begin{ccode}
    SIMPLE-NAT> reduce s(X:Nat) + 0 .

    -- reduce in SIMPLE-NAT : s(X:Nat) + 0
    s(X:Nat + 0) : NzNat
    (0.000 sec for parse, 1 rewrites(0.000 sec), 6 matches)
    SIMPLE-NAT> 
  \end{ccode}
\end{vvtm}
  But note that the system does not treat non-ground terms as such.
  It treats variables as if they were constants, and would not attempt
  unification.
\end{warning}

\section{Applying Rewrite Rules}\label{sec:p2-applying-rules}

In Section \ref{sec:p2-open-close}, it was shown that reductions can be
used to prove some theorems. For more demanding theorems, they are
inadequate. Consider the additive group theory written in \cafeobj.
\label{exs:group}
\begin{vvtm}
\begin{ccode}
  module* GROUP {
    [ G ]
    op 0 : -> G
    op _+_ : G G -> G { assoc }
    op -_ : G -> G
    var X : G
    eq 0 + X = X .
    eq (- X) + X = 0 .
  }
\end{ccode}
\end{vvtm}
Suppose you want to show that ``\verb|- X|'' is also a right inverse
(so {\em the} inverse). Using \verb|open|, you may write a score as
\begin{vvtm}
\begin{ccode}
  open GROUP
  op a : -> G .
  reduce a + (- a) .
\end{ccode}
\end{vvtm}
or, using a constant on the fly, just
\begin{vvtm}
\begin{ccode}
  reduce in GROUP : `a:G + (- `a) .
\end{ccode}
\end{vvtm}
But the result of reduction is simply
\begin{vvtm}
\begin{ccode}
  CafeOBJ> reduce in GROUP : `a:G + (- `a) .

  -- reduce in GROUP : `a:G + - `a:G
  `a:G + - `a:G : G
  (0.000 sec for parse, 0 rewrites(0.000 sec), 8 matches)
  CafeOBJ> 
\end{ccode}
\end{vvtm}
which is no wonder, since no equation has a matching lefthand side.
In fact, a standard proof goes as follows.
\begin{vvtm}
\begin{ccode}
  a + (- a) =
  0 + a + (- a) =
  (- (- a)) + (- a) + a + (- a) =
  (- (- a)) + 0 + (- a) =
  (- (- a)) + (- a) =
  0
\end{ccode}
\end{vvtm}
where we omitted parentheses since ``\verb|_+_|'' was declared associative.
This proof requires two ``reverse'' applications of rewrite rules.

\subsection{Start, Then Apply}\label{sec:p2-apply-command}

To accommodate such proofs as above, \cafeobj~supports the
following set of commands.

\begin{bsyntax} \texttt{start} command \index{\texttt{start}} \Hline
\texttt{start} \textit{term} ``\texttt{.}''
\end{bsyntax}

where a term is a term of the opened module
(Section \ref{sec:p2-open-close}), or in the current context
(Section \ref{sec:p2-current-module}).
This command sets the focus on the given term, which may be printed and
referred to in the subsequent commands. \verb|show| command
(Section \ref{sec:p2-show-command}) with \verb|term| as argument prints
the term just selected.\index{\texttt{show}}\index{\texttt{term}}

\begin{bsyntax} \texttt{apply} command \index{\texttt{apply}} \Hline
\texttt{apply} \textit{action} $[$\textit{substitution}$]$ \textit{range selection}
\end{bsyntax}

where the action, substitution, range and selection are as follows.

\index{\texttt{reduce}}\index{\texttt{exec}}\index{\texttt{print}}
\begin{tabular}{r c l}
  \textit{action} &::=& \verb|reduce| \\
     &$|$& \verb|exec| \\
     &$|$& \verb|print| \\
     &$|$& \textit{rewrite\_rule} \\
\end{tabular}

where a rewrite rule is

\begin{bsyntax} rule specification in \texttt{}apply\textit{} command \Hline
$[$``\texttt{+}''$|$``\texttt{-}''$]$$[$\textit{module\_name}$]$``\texttt{.}''$\{$ \textit{number}$|$\textit{label} $\}$
\end{bsyntax}

If the action is \texttt{reduce} or \texttt{exec},
the (sub)term specified by the range and
selection is reduced. If it is \texttt{print}, the (sub)term is printed.
If it is a rewrite rule, the chosen rule is applied, once, to the
subterm. In the last case, the numbered or labelled rule of the
module (if omitted, of the opened module) is used from left to right
(if the sign is ``\verb|+|'' or none), or right to left (if ``\verb|-|'').
We will first show a couple of examples in 
Section \ref{sec:p2-usage-of-apply} and
say more on this construct later (Section \ref{sec:p2-apply-rule-id}).

Substitutions are of the form

\begin{bsyntax} substitution specification in \texttt{}apply\textit{} command \Hline
~~~~\texttt{}with\textit{} $\{$ variable ``\/\texttt{}=\textit{}'' term $\}$ $+_,$ 
\end{bsyntax}

This option is necessary only when the action is a rewrite rule,
and binds variables that appear in the rule (see the next section
for why this option exists).

Ranges and selections are as follows.

\begin{tabular}{r c l}\index{\texttt{within}}\index{\texttt{at}}
  \textit{range} &::=& \verb|within| $|$ \verb|at|
\end{tabular}

\verb|within| means at or inside the (sub)term specified by the
selection, while \verb|at| means exactly at the (sub)term.

\begin{tabular}{r c l}\index{\texttt{of}}
  \textit{selection} &::=& \textit{selector} $\{$ \texttt{of} \textit{selector} $\}$ $*$\\
  \index{\texttt{top}}\index{\texttt{term}}\index{\texttt{subterm}}
  \textit{selector} &::=& \verb|top| \\
   &$|$& \verb|term| \\
   &$|$& \verb|subterm| \\
   &$|$& ``\verb|(|'' \textit{number\_list} ``\verb|)|'' \\
   &$|$& ``\verb|[|'' \textit{sublist} ``\verb|]|'' \\
   &$|$& ``\verb|{|'' \textit{subset} ``\verb|}|'' \\
\end{tabular}

\verb|top| and \verb|term| mean the entire term.
\verb|subterm| means the pre-chosen subterm (see the next section).
For the other alternatives,
\begin{itemize}
\item
 The list of numbers, separated by blanks, within ``\verb|(|'', ``\verb|)|''
 indicates a subterm by tree search. For example, ``\verb|(2 1)|'' means
 the first argument of the second argument; if ``\verb|a + (b * c)|'' is
 the term of concern, it means \verb|b|.
\item The
 \verb|[|, \verb|]| selector makes sense only with associative operators, and
 indicates a subterm in a flattened structure. For
 example, if ``\verb|_*_|'' was declared associative and given a term \newline
 ``\verb|a * b * c * d * e|'', ``\verb|[2 .. 4]|'' means ``\verb|b * c * d|'',
 while ``\verb|[2 .. 2]|'' means \verb|b|. The latter case can be
 abbreviated to \verb|[2]|.
\item The
 \verb|{|, \verb|}| selector makes sense only with associative and commutative
 operators, and indicates a subterm in a multiset structure.
 For example, if ``\verb|_*_|'' was declared associative and commutative,
 and given a term ``\verb|b * c * d * e * f|'', both ``\verb|{2, 4}|'' and
 ``\verb|{4, 2}|'' means a subterm \newline
 ``\verb|c * e|'', while \verb|{4}| means
 \verb|e|.
\end{itemize}
Note that the above selections are indeed subterms.
If ``\verb|_*_|'' is associative, the connectivity is immaterial, in
whatever way the term was originally given. If it is commutative in
addition, even the order is immaterial.

\begin{warning}
  \verb|top| is obsolete, and is here only for historical curiosity.
\end{warning}

\subsection{Applying Apply Command}\label{sec:p2-usage-of-apply}

\verb|apply| command has a very complicated syntax. It is better to
explain its behaviours by examples.
We use the group theory presented at the start of this section.

To show ``\verb|- X|'' is a right inverse, you may use the
following sequence of commands.
\begin{vvtm}
\begin{ccode}
  open GROUP
  op a : -> G .
  start a + (- a) .
  apply -.1 at (1) .
  apply -.2 with X = - a at [1] .
  apply reduce at term .
\end{ccode}
\end{vvtm}
(The numbers of rewrite rules are printed by \verb|show| command. See
Section \ref{sec:p2-apply-rule-id}.)
After two applications of reversed rules, reduction yields the desired
result, as follows.
\begin{vvtm}
\begin{ccode}
  NAT> open GROUP

  -- opening module GROUP... done.

  %GROUP> op a : -> G

  %GROUP> start a + (- a) .

  %GROUP> apply -.1 at (1) .
  *result 0 + a + - a : G

  %GROUP> apply -.2 with X = - a at [1] .
  result - (- a) + - a + a + - a : G

  %GROUP> apply reduce at term .
  result 0 : G

  %GROUP> 
\end{ccode}
\end{vvtm}
Look in more detail what happened at the second \verb|apply|
command. This command applied
\begin{vvtm}
\begin{ccode}
  eq (- X) + X = 0 .
\end{ccode}
\end{vvtm}
to the subterm \verb|0|. Without saying anything, a variable \verb|X|
would be introduced. This situation often occurs when a rule is
reversely applied. The substitution ``\verb|X = - a|'' avoids that.

You can continue, and prove another theorem that \verb|0| is a right identity
(so {\em the} identity).
Since we already showed ``\verb|a + (- a)|'' equals \verb|0|, it is
sound to add the equation. That leads to the command sequence
\begin{vvtm}
\begin{ccode}
  eq a + (- a) = 0 .
  start a + 0 .
  apply -.2 with X = a at (2) .
  apply reduce at term .
\end{ccode}
\end{vvtm}
which mirrors the reasoning
\begin{vvtm}
\begin{ccode}
  a + 0 = a + (- a) + a = 0 + a = a
\end{ccode}
\end{vvtm}

\subsection{Choosing Subterms}\label{sec:p2-choose-command}

If a term has a complicated structure, it is error-prone to
select a subterm at once. To make safer selections, a command
is supported.

\begin{bsyntax} \texttt{choose} command \index{\texttt{choose}}\Hline
\texttt{choose} \textit{selection}
\end{bsyntax}

where a selection is as in \verb|apply|
(Section \ref{sec:p2-apply-command}). This command
sets the focus to the chosen subterm, and its successive application
narrows the focus gradually.
\verb|show| command with \verb|subterm| argument may be used to print
the current subterm in focus.\index{\texttt{show}}\index{\texttt{subterm}}

For example, if you define a module of rings as\label{exs:ring}
\begin{vvtm}
\begin{ccode}
  module* RING {
    [ R ]
    op 0 : -> R
    op _+_ : R R -> R { assoc comm prec: 35 }
    op -_ : R -> R
    op _*_ : R R -> R { assoc prec: 31 }
    vars X Y Z : R
    eq 0 + X = X .
    eq (- X) + X = 0 .
    eq X * (Y + Z) = X * Y + X * Z .
    eq (Y + Z) * X = Y * X + Z * X .
  }
\end{ccode}
\end{vvtm}
and after \verb|open|ing \verb|RING|, you get
\begin{vvtm}
\begin{ccode}
  %RING> op f_ : R -> R .

  %RING> start ((f f 0) * ((f f f 0) + (- (f f f f 0)))) *
      ((- (f f f f 0)) + ((f f f 0) * ((f f f f 0) *
                                   ((f f 0) + ((f f f f f 0) * (f 0)))))) .

  %RING> choose (2) .

  %RING> show subterm
  ((- (f (f (f (f 0))))) + ((f (f (f 0))) * ((f (f (f (f 0)))) * ((f (f 0)) + 
      ((f (f (f (f (f 0))))) * (f 0)))))) : R

  %RING> choose (2) .

  %RING> show subterm
  ((f (f (f 0))) * ((f (f (f (f 0)))) * ((f (f 0)) + ((f (f (f (f (f
      0))))) * (f 0))))) : R

  %RING> choose [1 .. 2] .

  %RING> show subterm
  ((f (f (f 0))) * (f (f (f (f 0))))) : R

  %RING> show term
  (((f (f 0)) * ((f (f (f 0))) + (- (f (f (f (f 0))))))) * ((- (f (f 
      (f (f 0))))) + (((f (f (f 0))) * (f (f (f (f 0))))) * ((f (f 
      0)) + ((f (f (f (f (f 0))))) * (f 0)))))) : R

  %RING> 
\end{ccode}
\end{vvtm}
The last command was used to print the entire term that had been
\verb|start|ed. This command was
also useful in the stepper (cf. Section \ref{sec:p2-eval-step-mode}).
You may also print the subterm in a tree form, as
\begin{vvtm}
\begin{ccode}
  %RING> show subterm tree
  ((f (f (f 0))) * (f (f (f (f 0))))) : R
        _*_ 
       /   \ 
      f_  f_
       |   | 
      f_  f_
       |   | 
      f_  f_
       |   | 
       0  f_
           | 
           0
           
    

  %RING> 
\end{ccode}
\end{vvtm}
The current term, subterm etc. can also be printed by \verb|show|
command, as\index{\texttt{show}}\index{\texttt{context}}
(cf. Sections \ref{sec:p2-current-module}, \ref{sec:p2-apply-to-cond})
\begin{vvtm}
\begin{ccode}
  %RING> show context
  -- current context :
  [module] %
  [special bindings]
    $$term    = (((f (f 0)) * ((f (f (f 0))) + (- (f (f (f (f 0))))))) 
        * ((- (f (f (f (f 0))))) + (((f (f (f 0))) * (f (f (f (f 0))))) 
        * ((f (f 0)) + ((f (f (f (f (f 0))))) * (f 0)))))) : R
    $$subterm = ((f (f (f 0))) * (f (f (f (f 0))))) : R
  [bindings] empty.
  [selections] 
    1| [ 1 .. 2 ] .
        2| ( 2 ) .
            3| ( 2 ) .
  [pending actions]  none.
  [stop pattern] not specified.

  %RING> 
\end{ccode}
\end{vvtm}

\subsection{Identifying Rewrite Rules}\label{sec:p2-apply-rule-id}

We have not shown how to obtain the number that designates a specific
rewrite rule. Returning to \verb|GROUP|,
you may print rewrite rules --- or axioms so regarded
--- as follows.\index{\texttt{show}}\index{\texttt{rules}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> open GROUP

  -- opening module GROUP_.* done.

  %GROUP> show rules
   -- rewrite rules in module : %GROUP
    1 : eq 0 + X = X
    2 : eq - X + X = 0

  %GROUP> 
\end{ccode}
\end{vvtm}
Rules of any module may be printed, by supplying an extra argument.
\begin{vvtm}
\begin{ccode}
  %GROUP> show rules RING
   -- rewrite rules in module : RING
    1 : eq 0 + X = X
    2 : eq - X + X = 0
    3 : eq X * (Y + Z) = X * Y + X * Z
    4 : eq (Y + Z) * X = Y * X + Z * X

  %GROUP> 
\end{ccode}
\end{vvtm}
It is also possible to print all the rules, including those declared
in imported modules, by specifying \verb|all|, as in\index{\texttt{all}}
\begin{vvtm}
\begin{ccode}
  %GROUP> show all rules
\end{ccode}
\end{vvtm}

The numbering of the above is used to specify rewrite rules.
For example, you encountered in Section \ref{sec:p2-usage-of-apply} a
command
\begin{vvtm}
\begin{ccode}
  %GROUP> apply -.1 at (1) .
\end{ccode}
\end{vvtm}
The specified rule, according to the output above, was
\begin{vvtm}
\begin{ccode}
    1 : eq 0 + X = X
\end{ccode}
\end{vvtm}
and the minus sign was added to apply this rule in reverse.
You may decorate a rule number with a module name, like
\begin{vvtm}
\begin{ccode}
  %GROUP> apply -GROUP.1 at (1) .
\end{ccode}
\end{vvtm}
which will apply the same rule as before.
Axiom labels may also be used to designate rules. For example, if
the above equation were labelled as
\begin{vvtm}
\begin{ccode}
  eq [l-id] : 0 + X = X .
\end{ccode}
\end{vvtm}
the \verb|apply| command might as well be
\begin{vvtm}
\begin{ccode}
  %GROUP> apply -.l-id at (1) .
\end{ccode}
\end{vvtm}

\begin{warning}
  Do not put blanks anywhere in between the sign, module name, period,
  number or label. Memorise ``a rule spec hates vacuum''.
\end{warning}

Finally, \verb|show| command with \verb|rule| (not \verb|rules|) may be
used to print a single rule. This command is useful when the number of
rewrite rules is large. An example:\index{\texttt{show}}\index{\texttt{rule}}
\begin{vvtm}
\begin{ccode}
  %GROUP> show rule .2
  rule 2 of the last module
    - X + X = 0
  (This rule rewrites up.)
\end{ccode}
\end{vvtm}
Do not forget the period before \verb|2|. Arguments to this command are
rule specifications, and ``\verb|.2|'' is of rule specification form,
according to the definition in Section \ref{sec:p2-apply-command}.

``\verb|show rule|'' and ``\verb|show rules|'' may be invoked when no module
is opened. In such a case, the rule(s) of the current module are printed.
\subsection{Appyling Conditionals}\label{sec:p2-apply-to-cond}

When the action is a rewrite rule, \verb|apply| command tries to
apply just one rule and immediately returns the control to you.
What if the rule is conditional? Recall \verb|GCD| (Section
\ref{exs:gcd}):
\begin{vvtm}
\begin{ccode}
  CafeOBJ> open GCD

  -- opening module GCD.. done.

  %GCD> start gcd(s(0),s(s(0))) .

  %GCD> show rules
   -- rewrite rules in module : %GCD
    1 : ceq gcd(N,M) = gcd(M,N) if N < M
    2 : eq gcd(N,0) = N
    3 : ceq gcd(s(N),s(M)) = gcd(s(N) - s(M),s(M)) if not N < M

  %GCD> apply +.1 at term .
  shifting focus to condition
  -- condition(1) s(0) < s(s(0)) : Bool

  %GCD> show context
  -- current context :
  [module] %
  [special bindings]
    $$term    = (s(0) < s(s(0))) : Bool
    $$subterm =  $$term
  [bindings] empty.
  [selections]  empty.
  [pending actions] 
    1| in gcd(s(0),s(s(0)))  at top
     | rule ceq gcd(N,M) = gcd(M,N) if N < M
     | condition s(0) < s(s(0))  replacement gcd(s(s(0)),s(0))
  [stop pattern] not specified.

  %GCD> 
\end{ccode}
\end{vvtm}
It looked certain that the rule \verb|1| would apply, so you tried it.
The system then told that, since that rule was conditional, it had to
resolve the condition first.

\verb|show| command with \index{\texttt{context}} argument were
partly explained in Sections \ref{sec:p2-current-module} and
\ref{sec:p2-choose-command}. What was remained was the misterious
heading ``[pending actions]''. This part is used exactly in
a situation like now, and contains terms to be further
reduced after a condition --- the current focus --- has been evaluated.

The instance of the condition requires
rules in \verb|SIMPLE-NAT+| (Section \ref{exs:simple-nat+}),
so you have to continue as follows.
\begin{vvtm}
\begin{ccode}
  %GCD> show rules SIMPLE-NAT+
   -- rewrite rules in module : SIMPLE-NAT+
    1 : eq 0 - M = 0
    2 : eq N - 0 = N
    3 : eq s(N) - s(M) = N - M
    4 : eq 0 < s(N) = true
    5 : eq N < 0 = false
    6 : eq s(N) < s(M) = N < M

  %GCD> apply +SIMPLE-NAT+.6 at term .
  -- condition(1) 0 < s(0) : Bool

  %GCD> apply +SIMPLE-NAT+.4 at term .
  -- condition(1) true : Bool
  -- condition is satisfied, applying rule
  -- shifiting focus back to previous context
  result gcd(s(s(0)),s(0)) : Nat

  %GCD>
\end{ccode}
\end{vvtm}
At last the condition was satisfied, and the system rewrote the
original term. You may continue, this time applying the rule \verb|3|.
\begin{vvtm}
\begin{ccode}
  %GCD> apply +.3 at term .
  shifting focus to condition
  -- condition(1) not s(0) < 0 : Bool

  %GCD>
\end{ccode}
\end{vvtm}
But reduction of ``\verb|_<_|'' is obvious so you apply \verb|reduce|
at once.
\begin{vvtm}
\begin{ccode}
  %GCD> apply reduce at term .
  -- condition(1) true : Bool
  -- condition is satisfied, applying rule
  -- shifiting focus back to previous context
  result gcd(s(s(0)) - s(0),s(0)) : Nat

  %GCD>
\end{ccode}
\end{vvtm}
The original term was further rewritten, and you can continue as before.

As shown by this frustrating example, what \verb|apply| basically
offers is a painful step-by-step reasoing. There are ways to skip
certain parts at one go. One way is to invoke the action \verb|reduce|,
as above. In the case of conditional rewrite rules, there is another,
systematic way to do it. Let us redo the above session using this
mechanism.\index{\texttt{reduce}}\index{\texttt{conditions}}
\begin{vvtm}
\begin{ccode}
  %GCD> start gcd(s(0), s(s(0))) .

  %GCD> set reduce conditions on

  %GCD> apply +.1 at term .
  result gcd(s(s(0)),s(0)) : Nat

  %GCD> apply +.3 at term .
  result gcd(s(s(0)) - s(0),s(0)) : Nat

  %GCD> apply +.1 at term .

  [Warning]: rule not applied
  result gcd(s(s(0)) - s(0),s(0)) : Nat

  %GCD>  
\end{ccode}
\end{vvtm}
The switch ``\verb|reduce conditions|'', when \verb|on|, makes the
system to evaluate conditions automatically.

\section{Matching Terms}\label{sec:p2-matching-terms}

Matching is a basic procedure in evaluation (Section \ref{sec:p2-trs-basic}).
It may be useful by itself as a theorem-proving helper, since
\begin{itemize}
\item When you use \verb|reduce| command, it is a good practice to write
  down the expected result beforehand. If the actual result differs, you
  immediately notice something is going wrong. A standard way to realise
  this practice is to use a printable comment ``\verb|-->|'' or ``\verb|**>|''
  (Section \ref{sec:p2-comment-syntax}), as
  \begin{vvtm}
\begin{ccode}
    reduce s(s(0)) + s(0) .
    **> should be: s(s(s(0)))
  \end{ccode}
\end{vvtm}
  The system then prints
  \begin{vvtm}
\begin{ccode}
    -- reduce in SIMPLE-NAT : s(s(0)) + s(0)
    s(s(s(0))) : NzNat
    (0.000 sec for parse, 3 rewrites(0.000 sec), 5 matches)
    **> should be: s(s(s(0)))  
  \end{ccode}
\end{vvtm}
  so that you can compare the actual and expected results easily.
  A more sophisticated mechanism is to invoke a matching
  procedure. And
\item In using \verb|reduction| and \verb|apply| commands for
  theorem proving, it is necessary to know what rewrite rules are
  applicable to what terms. You can inspect the rules by \verb|show|
  command, but if the set of rules is large, it is tedious.
  A tool to list applicable rules is helpful. ``Applicable'' here
  means ``having matchable lefthand side''.
\end{itemize}

\subsection{Match Command}\label{sec:p2-match-command}

\begin{bsyntax} \texttt{match} command \index{\texttt{match}}\Hline
\texttt{match} \textit{term\_specifier} \texttt{to} \textit{pattern} ``\texttt{.}''
\end{bsyntax}

The last period (preceded by a blank) is necessary. Term specifiers and
patterns are as follows.

\begin{tabular}{r c l}\index{\texttt{top}}\index{\texttt{term}}\index{\texttt{it}}
\index{\texttt{subterm}}
  \textit{term\_specifier} &::=& \verb|top| \\
   &$|$& \verb|term| \\
   &$|$& \verb|it| \\
   &$|$& \verb|subterm| \\
   &$|$& \textit{term} \\
\end{tabular}

where a term is a usual term. \verb|top| or the literal \verb|term|
means the term set by
\verb|start| command; \verb|subterm| means the term selected by \verb|choose|
commands; \verb|it| is the same as \verb|subterm| if \verb|choose| was
used, and is the same as \verb|top| otherwise.

\begin{warning}
  Unlike former versions, the current version do not require enclosing
  parentheses for a term. If you are cautious, put them anyway. They
  are harmless.
\end{warning}

\begin{tabular}{r c l}\index{\texttt{all}}\index{\texttt{rules}}\index{\texttt{+rules}}
\index{\texttt{-rules}}
  \textit{pattern} &::=& $[$ \verb|all| $]$
   $\{$ \verb|rules| $|$ \verb|+rules| $|$ \verb|-rules| $\}$ \\
   &$|$& \textit{term}
\end{tabular}

where a term is a usual term. \verb|rules|, ``\verb|+rules|'' or
``\verb|-rules|''
lists rewrite rules applicable to the specified term. ``\verb|+rules|'' means
the rules with matching lefthand sides, ``\verb|-rules|'' means
those with
matching righthand sides, and \verb|rules| means both.
If optional \verb|all| is given, all the rules in the current context,
including those declared in built-in modules, are inspected.

If a pattern is a term, matching is attempted, and if successful,
the matching subsitution is printed. Is a pattern is \verb|rules|,
``\verb|+rules|'' or ``\verb|-rules|'',
the list of applicable rules, together with
corresponding matching substutitions, are printed.

\subsection{Matching Terms to Terms}\label{sec:p2-match-to-term}

We use \verb|GROUP| (Section \ref{exs:group}) for examples.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select GROUP

  GROUP> match 0 + 0 to X:G + 0 .
  -- match success.
   substitution : { X |-> 0 }
  -- No more match

  GROUP> match 0 + 0 to X:G + Y:G .
  -- match success.
   substitution : { X |-> 0, Y:G |-> 0 }
  -- No more match

  GROUP> match 0 to 0 + 0 .
  -- no match

  GROUP> 
\end{ccode}
\end{vvtm} 
As shown above, the system prints the substitution when
matching succeeds.

The system recognises equational theory
attributes, such as associativity (Section \ref{sec:p2-equational-theory}),
and tries all the possibilities, as
\begin{vvtm}
\begin{ccode}
  GROUP> match 0 + 0 + 0 to X:G + Y:G .
  -- match success.
   substitution : { X |-> 0, Y:G |-> 0 + 0 }
  >> More? [y/n] : y
  -- match success : 
   * substitution : { X |-> 0 + 0, Y:G |-> 0 }

  -- No more match

  GROUP> 
\end{ccode}
\end{vvtm}
Remember that ``\verb|_+_|'' was declared associative. Modulo associativity,
there are two ways of matching the above two terms.

\begin{warning}
  It is possible for a term to contain variables, both as a term specifier
  and as a pattern. For example, it is legal to try
  \begin{vvtm}
\begin{ccode}
    match X:G + 0 to 0 + X':G .
  \end{ccode}
\end{vvtm}
  But this does not acts as expected:
  \begin{vvtm}
\begin{ccode}
    GROUP> match X:G + 0 to 0 + X':G .
    -- no match

    GROUP> 
  \end{ccode}
\end{vvtm}
  \verb|match| is a matching procedure,
  not a unification. If a term (to the left of ``\verb|to|'') contains
  a variable, it is treated as a pseudo-constant. In the above example,
  \verb|X| acts as a constant, and cannot be substituted by \verb|0|.
\end{warning}

\subsection{Matching Terms to Pattern}\label{sec:p2-match-to-pattern}

We next deal with the cases when the pattern designates a set of rules.
For illustration, we add several equations before invoking matching.
\begin{vvtm}
\begin{ccode}
  GROUP> open GROUP

  -- opening module GROUP_.* done.

  %GROUP> ops a b : -> G .

  %GROUP> eq X:G + Y:G = Y + X .

  %GROUP> eq a + X:G = a + X + a .

  %GROUP> start 0 + a + a .

  %GROUP> match term to +rules .
  == matching rules to term : (0 + (a + a))
  +%.1 is eq 0 + X = X
   substitution : { X |-> a + a }
  +%.3 is eq X + Y:G = Y:G + X
   substitution : { Y:G |-> a + a, X |-> 0 }
  +%.4 is eq a + X = a + X + a
   substitution : { X |-> a }

  %GROUP> 
\end{ccode}
\end{vvtm}
The system lists applicable rules to the term ``\verb|0 + a + a|''.
In this output, a rule is numbered, adorned with the module name
``\verb|%|'' (the opened module: cf. Section \ref{sec:p2-usage-of-open}),
and a sign. Remember that this form appears in arguments to \verb|apply|
command (Section \ref{sec:p2-apply-rule-id}). You may have noticed
two differences from the cases of matching terms to terms.
\begin{itemize}
\item Not all possibilities are considered. In the above output,
  only one matching possibility is shown for the rule \verb|3|, even though
  there are two possibilities (see the previous section).
\item All the subterms of the given term is under consideration.
  The rule \verb|4| does not match the whole term, but does match
  a subterm.
\end{itemize}
The case where ``\verb|-rules|'' is specified is similar.
\begin{vvtm}
\begin{ccode}
  %GROUP> match term to -rules .
  == matching rules to term : (0 + (a + a))
  -%.1 is eq 0 + X = X
   substitution : { X |-> 0 + a + a }
  -%.3 is eq X + Y:G = Y:G + X
   substitution : { Y:G |-> 0, X |-> a + a }
  -%.20 is eq if true then CXU else CYU fi = CXU
   substitution : { CXU |-> 0 + a + a }
  -%.21 is eq if false then CXU else CYU fi = CYU
   substitution : { CYU |-> 0 + a + a }

  %GROUP> 
\end{ccode}
\end{vvtm}

\begin{warning}
  The last two printed rules are of \verb|BOOL|
  (actually, a submodule thereof). This rule is always applicable in
  reverse, since the righthand side is a single variable.
\end{warning}

\chapter{Proving Module Properties}\label{sec:p2-semantic-prop}

\section{Check Command}\label{sec:p2-check-command}

Some of the module properties are checkable syntactically, within
reasonable computation cost.

\begin{bsyntax} \texttt{check} command \index{\texttt{check}}\Hline
\index{\texttt{regularity}}\index{\texttt{compatibility}}\index{\texttt{laziness}}
\texttt{check} $\{$ \texttt{regularity} $|$ \texttt{compatibility} $\}$ $[$\textit{module\_expression}$]$
\texttt{check} $\{$ \texttt{laziness} $\}$ $[$\textit{operator\_name}$]$
\end{bsyntax}

A module expression may be omitted if the current module
(Section \ref{sec:p2-current-module}) is set.
\verb|regularity| may be abbreviated to \verb|reg| or \verb|regular|,
\verb|compatibility| to \verb|compat|, and \verb|laziness| to \verb|lazy|.

\paragraph{Regularity}

If the first argument is \verb|regularity|, the system checks
if the module is regular\index{regular}.
Using \verb|INTB'| in Section \ref{exs:intb'}, you can
obtain the following message.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> check regularity INTB'

  >> start regularity check ...
  >> The following sorts may be required for regularity:
    [ Nat^NonPos < NonPos Nat ]
  >> The following operators may be required for regularity:
    _+_ : Nat^NonPos Nat^NonPos -> Nat^NonPos
  CafeOBJ> 
\end{ccode}
\end{vvtm}
while with \verb|SIMPLE-NAT|, the system reports nothing, as
\begin{vvtm}
\begin{ccode}
  CafeOBJ> check regularity SIMPLE-NAT

  >> start regularity check ...
  -- signature of module SIMPLE-NAT is regular.
  CafeOBJ> 
\end{ccode}
\end{vvtm}
Unlike \verb|regularize| command (Section \ref{sec:p2-wff-terms}),
this command does not modify the signature.

\paragraph{Compatibility}

If the first argument is \verb|compatibility|, the system checks
if the TRS defined by the module is compatible\index{compatible}, i.e.,
every application of every rewrite rule to every well-formed term
results in a well-formed term. Note that, in order-sorted
rewriting, an application of a rewrite rule may introduce
an ill-formed term. For (a contrived) example,
\begin{vvtm}
\begin{ccode}
  module NONCOMPAT {
    [ S < S' ]
    op a : -> S
    op b : -> S'
    op f : S -> S
    eq a = b .
  }
\end{ccode}
\end{vvtm}
is not compatible, since \verb|f(a)|, which is well-formed, rewrites to
\verb|f(b)|, which is ill-formed. As this example shows, non-compatibility
is caused by a rewrite rule that ``raise''s the sort of a term. This is
not a necessary condition of compatibility, however. In the absence of
the operator \verb|f|, the above module {\em is} compatible.
The system checks a necessary and sufficient condition of compatibility,
as
\begin{vvtm}
\begin{ccode}
  CafeOBJ> check compatibility NONCOMPAT

  >> started compatibility check:

  >> module (corresponding TRS) is NOT compatible:
  - rewrite rule
      a = b
    violates the compatibility,
    and following operator(s) can possibly be affected:
      f : S -> S
  CafeOBJ> module COMPAT {
      [ S < S' ]
      op a : -> S
      op b : -> S'
      eq a = b .
  }

  -- defining module COMPAT..._.* done.
  CafeOBJ> check compatibility COMPAT

  >> started compatibility check:

  >> module is compatible.
  CafeOBJ>
\end{ccode}
\end{vvtm}

\begin{warning}
  As shown in Section \ref{sec:p2-flexible-typing}, the current
  implementation regards
  a term like \verb|f(b)| above as {\em well-formed}, although of
  a questionable sort. The above definition should be rephrased, in this
  setting, in terms of error sorts.
\end{warning}

\paragraph{Laziness}

If the first argument is \verb|laziness|,
the system checks if the given operator can be evaluated lazily.
The operator must be in the current module (which must be set
beforehand). If an operator name is omitted, all the operators
directly declared in the current module is checked.

Laziness\index{laziness} is related to evaluation strategies.
The system checks a sufficient
condition under which an operator may be evaluated lazily,
as explained Section \ref{sec:p2-rew-strategy}. Here is an example.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> module LAZY {
    [ S ]
    op f : S -> S
    op g : S -> S
    eq f(f(X:S)) = g(X) .
    eq g(X:S) = X .
  }

  -- defining module LAZY..._..* done.
  CafeOBJ> select LAZY

  LAZY> check laziness

  ------------------------------------------------------------
                 * laziness of operator: (f) *
  ------------------------------------------------------------
  f : S -> S
    * strict on the arguments :  1
    - rewrite strategy: 1 0
    - axioms:
      eq f(f(X:S)) = g(X:S)

  ------------------------------------------------------------
                 * laziness of operator: (g) *
  ------------------------------------------------------------
  g : S -> S
    * may delay the evaluation on the arguments :  1
    - rewrite strategy: 0 1 0
    - axioms:
      eq g(X:S) = X:S

  LAZY> 
\end{ccode}
\end{vvtm}

\begin{warning}
  The system only checks an apparent sufficient condition, and
  do not use a detailed strictness analysis as used in
  functional language compilers. The word ``laziness'' was chosen
  humbly and carefully.
\end{warning}

\section{Theorem Proving Techniques}\label{sec:p2-theorem-proving-exs}

We have already shown a couple of proofs based on the TRS engine of
\cafeobj(Sections \ref{sec:p2-usage-of-open}, \ref{sec:p2-usage-of-apply}).
There a proof score was a sequence of commands, including
\verb|open|, \verb|reduce| and \verb|apply|. The system reads the commands,
rewrites terms as commanded, and prints the result. Behind such
rewrite sequences is equational reasoning: schematically, the reasoning
is of the form
\begin{center}
  $t_0$ $=$ $t_1$ $=$ $\ldots$ $=$ $t_n$
\end{center}
and the theorem to prove is the equation $t_0$ $=$ $t_n$.

Another way to prove theorems by evaluation is to state the theorems
as terms of sort \verb|Bool|, and to evaluate them. If the terms are
reduced to \verb|true|, the theorems are proved. For example, to
show
\begin{vvtm}
\begin{ccode}
  eq a + (- a) = 0 .
\end{ccode}
\end{vvtm}
we may try to reduce the term
\begin{vvtm}
\begin{ccode}
  a + (- a) == 0
\end{ccode}
\end{vvtm}
to \verb|true|. This approach does not confer
you with much extra power. As explained in Section
\ref{sec:p2-equality-pred}, in evaluating ``\verb|_==_|'',
\cafeobj~simply reduces both arguments, and check if they are equal.
Apart from the equality checking part, which involves
equational theory (Section \ref{sec:p2-equational-theory}),
what can be done with ``\verb|_==_|'' can be done without.
In terms of presentation, however, this approach produces
something like
\begin{vvtm}
\begin{ccode}
  ...
  %GROUP> start a + (- a) == 0 .
  ...
  %GROUP> apply reduce at term .
  result true : Bool
\end{ccode}
\end{vvtm}
which is more appealing to intuition than
\begin{vvtm}
\begin{ccode}
  ...
  %GROUP> start a + (- a) .
  ...
  %GROUP> apply reduce at term .
  result 0 : G
\end{ccode}
\end{vvtm}
where you must mentally compare the actual result with the expected.
Especially, when both sides of the equation need evaluation, this
approach provides you with a much more compact proof.

\subsection{Structural Induction}\label{sec:p2-proof-by-induction}

In Section \ref{sec:p2-usage-of-open}, we have presented a
proof score to show that \verb|0| is a right identity of ``\verb|_+_|''
under the definition of \verb|SIMPLE-NAT|. The score relies on
structural induction\index{structural induction}.

Strictly speaking, proofs by structural induction only demonstrate
that certain properties (called
{\em inductive properties}\index{inductive property}) hold for
the term-generated models of a module, including its initial model.
Recall that ``\verb|module!|'' denotes such a
model, while \verb|module| has both tight and loose denotations.
Since \verb|SIMPLE-NAT| was declared with \verb|module|, what was proven
in Section \ref{sec:p2-usage-of-open} is a property that does not
necessarily hold when \verb|SIMPLE-NAT| denotes loose models.
With this proviso, structural induction is certainly a useful
technique, and you are often powerless without it.

Let us show a couple of examples. For the sake of variety, we use
the predicate ``\verb|_==_|'' here. The following sequence proves
associativity of ``\verb|_+_|''.
\begin{vvtm}
\begin{ccode}
  ** proving associativity of _+_
  open SIMPLE-NAT
  ops a b c : -> Nat .
  reduce 0 + (a + b) == (0 + a) + b .
  eq (a + b) + c = a + (b + c) . ** hypothesis
  reduce s(a) + (b + c) = (s(a) + b) + c .
  close
\end{ccode}
\end{vvtm}
The session goes as follows.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> open SIMPLE-NAT

  -- opening module SIMPLE-NAT_.* done.

  %SIMPLE-NAT> ops a b c : -> Nat .

  %SIMPLE-NAT> reduce 0 + (a + b) == (0 + a) + b .
  _*
  -- reduce in % : 0 + (a + b) == (0 + a) + b
  true : Bool
  (0.000 sec for parse, 3 rewrites(0.000 sec), 11 matches)
  %SIMPLE-NAT> eq (a + b) + c = a + (b + c) .

  %SIMPLE-NAT> reduce s(a) + (b + c) == (s(a) + b) + c .
  *
  -- reduce in % : s(a) + (b + c) == (s(a) + b) + c
  true : Bool
  (0.010 sec for parse, 5 rewrites(0.000 sec), 26 matches)

  %SIMPLE-NAT> close

  CafeOBJ> 
\end{ccode}
\end{vvtm}
Recall that when we gave a view for \verb|MONOID|
(Section \ref{sec:p2-views-exs}), the associativity axiom
remained to be proven. This obligation was discharged just now.
Similarly, commutativity is proven by
\begin{vvtm}
\begin{ccode}
  ** proving commutativity of _+_
  open SIMPLE-NAT
  ops a b : -> Nat .
  reduce 0 + 0 == 0 + 0 .
  eq b + 0 = 0 + b . ** (inner) hypothesis
  reduce s(b) + 0 == 0 + s(b) .
  eq a + X:Nat = X + a . ** (outer) hypothesis -- *
  reduce 0 + s(a) == s(a) + 0 .
  eq b + s(a) = s(a) + b . ** (inner) hypothesis
  reduce s(b) + s(a) == s(a) + s(b) .
  close
\end{ccode}
\end{vvtm}
The proof relies on double induction. And in this proof,
the ``direction'' of equations is crucial: in giving the equation
marked ``\verb|*|'', if you exchanged the sides, the subsequent evaluations
would produce \verb|false|. To get \verb|true|, you need
reverse applications (by using \verb|apply|).

\subsection{Nondeterministic Transitions}\label{sec:p2-proving-trans}

Since the current implementation of evaluation mechanism is deterministic,
it is impossible to prove transition relations by
\verb|execute| command alone. In such a case, the transition predicate
``\verb|_==>_|'' is often useful.
As explained in Section \ref{sec:p2-transition-pred},
``\verb|_==>_|'' is supported by ``\verb|_=(*)=>_|'', which systematically
checks transitions step by step.

Recall \verb|CHOICE-NAT| (Section \ref{exs:choice-nat}),
and let us prove a simple fact that
\begin{quotation}
  If $t$ transits to $u$, $t|t'$ also transits to
  $u$, for any $t'$.
\end{quotation}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> open CHOICE-NAT

  -- opening module CHOICE-NAT.. done.

  %CHOICE-NAT> ops a b c : -> Nat .

  %CHOICE-NAT> trans a => c .
  _
  %CHOICE-NAT> reduce a | b ==> c .

  -- reduce in % : a | b ==> c
  true : Bool
  (0.000 sec for parse, 6 rewrites(0.000 sec), 13 matches)
  %CHOICE-NAT> close

  CafeOBJ>
\end{ccode}
\end{vvtm}
For another simple example, suppose you want to prove another simple
fact that
\begin{quotation}
  If $t$ transits to $u$, $t + t'$ transits to $u + t'$, for any $t'$.
\end{quotation}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> open CHOICE-NAT

  -- opening module CHOICE-NAT.. done.

  %CHOICE-NAT> ops a b c : -> Nat .

  %CHOICE-NAT> trans a => c .
  _
  %CHOICE-NAT> reduce a + b ==> c + b .
  *
  -- reduce in % : a + b ==> c + b
  true : Bool
  (0.000 sec for parse, 4 rewrites(0.000 sec), 15 matches)
  %CHOICE-NAT> close

  CafeOBJ> 
\end{ccode}
\end{vvtm}
Note that, when using ``\verb|_==>_|'',
evaluation should be by \verb|reduce| command, {\em not} by
\verb|execute| cpmmand. Although ``\verb|_==>_|''
represents transition relations, the reasoning is within pure 
equational logic.

There are a couple of switches that control the reduction procedure
for ``\verb|_==>_|''. One is to get a trace. For illustration, you may
rerun the first above session.\index{\texttt{exec}}\index{\texttt{trace}}
\begin{vvtm}
\begin{ccode}
  ... declaring a, b, c, and assert a => c as before

  %CHOICE-NAT> set exec trace on

  %CHOICE-NAT> reduce a | b ==> c .

  -- reduce in % : a | b ==> c
  ** transition step 1-1 *******
  (): (a | b)
      =(1)=> a
  (): (a | b)
      =(1)=> b
  (1): (a | b)
      =(1)=> (c | b)

  ** transition step 2-1 *******
  (): a
      =(2)=> c
  ** term : c
   matched to the pattern : c
   with the substitution : {}
  true : Bool
  (0.000 sec for parse, 6 rewrites(0.000 sec), 13 matches)
  %CHOICE-NAT>
\end{ccode}
\end{vvtm}
There are three transitions from ``\verb+a | b+'', that is
\begin{vvtm}
\begin{ccode}
  trans N | N' => N .
  trans N | N' => N' .
  trans a => c .
\end{ccode}
\end{vvtm}
respectively yielding \verb|a|, \verb|b|, and ``\verb+c | b+''.
The first branch further transits to \verb|c|, which matches
the given destination.

%!!!!!!!!!!!!!!!!!
% What is exec condition?
%A second switch controls conditional transitions. For example,
%\begin{vvtm}
%\begin{ccode}
%  %CHOICE-NAT> 
%\end{ccode}
%\end{vvtm}

\subsection{Systematic Search for Transition Relations}
\label{sec:p2-proving-trans-2}

``\verb|_=(*)=>_|'' can often be used directly.
Continuing the example of \verb|CHOICE-NAT|,
\begin{vvtm}
\begin{ccode}
  CafeOBJ> select CHOICE-NAT

  CHOICE-NAT> reduce (0 | s(0)) | (s(s(0)) | (s(s(s(0))) | s(s(s(s(0)))))) 
    =(*)=> s(s(s(0))).
  -- reduce in CHOICE-NAT : (0 | s(0)) | (s(s(0)) | (s(s(s(0))) | s(
     s(s(s(0)))))) = ( * ) => s(s(s(0)))
  true : Bool
  (0.010 sec for parse, 51 rewrites(0.020 sec), 51 matches)
  CHOICE-NAT>
\end{ccode}
\end{vvtm}
This was a very easy case, since all the arguments to ``\verb+_|_+'' are
are irreducible and only pure transition steps are involved.
A more demanding case is
\begin{vvtm}
\begin{ccode}
  CHOICE-NAT> reduce (0 | s(0)) + ((s(s(0)) | (s(s(s(0))) + 0)) 
    + s(s(s(s(0))))) =(*)=> s(s(0)) + (s(s(s(0))) + s(0)).

  -- reduce in CHOICE-NAT : (0 | s(0)) + ((s(s(0)) | (s(s(s(0))) + 
      0)) + s(s(s(s(0))))) = ( * ) => s(s(0)) + (s(s(s(0))) + s(0))
    
  true : Bool
  (0.000 sec for parse, 35 rewrites(0.000 sec), 78 matches)
  CHOICE-NAT> 
\end{ccode}
\end{vvtm}
where the the system need to compute ``\verb|_+_|'' along the way.

If the search space can be large, ``\verb|=(*)=>|'' is a dangerous weapon.
In such cases, you may limit the search up to a realistic step, with
the set of predicates ``\verb|=(n)=>|'' where \verb|n| is a natural
number (in the usual decimal notation) and indicates how many transit
steps to take. For example,
\begin{vvtm}
\begin{ccode}
  CHOICE-NAT> reduce (0 | s(0)) | (s(s(0)) | ((s(s(s(0))) + 0) |
    s(s(s(s(0)))))) =(1)=> s(s(s(0))).
  -- reduce in CHOICE-NAT : (0 | s(0)) | (s(s(0)) | ((s(s(s(0))) + 
       0) | s(s(s(s(0)))))) = ( 1 ) => s(s(s(0)))
  [Warning]: =(N)=> terminates, reaching preset maximum count of transitions.
  false : Bool
  (0.010 sec for parse, 13 rewrites(0.000 sec), 16 matches)
  CHOICE-NAT>
\end{ccode}
\end{vvtm}
which is a correct result, since the first argument cannot transit to
the second in one step.

Another way to limit the search is by a switch.\index{\texttt{exec}}
\index{\texttt{limit}}
\begin{vvtm}
\begin{ccode}
  CafeOBJ> set exec limit 40
\end{ccode}
\end{vvtm}
limits the maximal transition step to 40. The default limit is quite
large.

As the above sessions show, ``\verb|_=(*)=>_|'' and
``\verb|_==>_|'' take into account equations as well as
transitions. In most cases and with appropriate evaluation strategies,
``\verb|_==>_|'' does give correct answers on transition relations.
However, it is in general impossible always to obtain correct answers
on transition relations between {\em equivalence classes} of terms.
For example, consider a module
\begin{vvtm}
\begin{ccode}
  module M {
    [ S ]
    ops a b c d : -> S
    eq a = b .
    trans a => c .
    eq c = d .
  }
\end{ccode}
\end{vvtm}
and a theorem
\begin{vvtm}
\begin{ccode}
  trans a => d .
\end{ccode}
\end{vvtm}
The system does not evaluate the corresponding term to \verb|true|, as
\begin{vvtm}
\begin{ccode}
  M> reduce a ==> d .

  -- reduce in M : a ==> d
  > pre normalization : a
      == b
  -- no more possible transition for : a
  b ==> d : Bool
  (0.000 sec for parse, 4 rewrites(0.000 sec), 12 matches)
  M>
\end{ccode}
\end{vvtm}
This is because the system reduces \verb|a| to an irreducible form
(\verb|b|) before trying a systematic search. If it had tried
a search before normalising, it would have proved the theorem.
There is a switch that tells the system to forget about normalisation.
\begin{vvtm}
\begin{ccode}
  M> set exec normalize on

  M>> reduce a ==> d .

  -- reduce in M : a ==> d

  ** transition step 1-1 *******
  (): a
      =(1)=> c
  < post nomalization : c
      == d
  ** term : d
   matched to the pattern : d
   with the substitution : {}
  true : Bool
  (0.000 sec for parse, 4 rewrites(0.010 sec), 6 matches)

  M>
\end{ccode}
\end{vvtm}
The result was satisfactory. This switch is hopeless if interleaving
applications of equations and transitions are necessary. In
\begin{vvtm}
\begin{ccode}
  module M' {
    [ S ]
    ops a b c d e : -> S
    eq [e1] a = b .
    eq [e2] b = c .
    trans [t] b => d .
    eq [e3] d = e .
  }
\end{ccode}
\end{vvtm}
to prove
\begin{vvtm}
\begin{ccode}
  trans a => e .
\end{ccode}
\end{vvtm}
you have to use \verb|e1|, and only that.

\subsection{Behavioural Equivalence}\label{sec:p2-proving-beh-eq}

Recall \verb|COUNTER| (Section \ref{exs:counter}) and let us prove
a behavioural equation
\begin{vvtm}
\begin{ccode}
  beq add(N:Nat, add(N':Nat, C:Counter)) = add(N', add(N, C)) .
\end{ccode}
\end{vvtm}
As explained, this equation holds iff two terms act
identically on every observation. This theorem may be proved
by induction on the length of observations
(called {\em context induction}\index{context indution}).
Since \verb|add|, \verb|read| are the only ``method'' and ``attribute''
respectively, every observation is an application of \verb|read|
after a finite number of applications of \verb|add|.

A necessary command sequence is as follows. Since the proof
uses associativity and commutativity of ``\verb|_+_|'' on \verb|Nat|,
which were proven
in Section \ref{sec:p2-proof-by-induction}, they are stated as equations.
\begin{vvtm}
\begin{ccode}
  open COUNTER
  ops m n p : -> Nat .
  op c : -> Counter .
  op addn : Counter -> Counter .
  eq m + n = n + m .
  eq N:Nat + (M:Nat + P:Nat) = (N + M) + P .
  reduce read(add(m, add(n, c))) == read(add(n, add(m, c))) .
  eq read(addn(add(m, add(n, c)))) = read(addn(add(n, add(m, c)))) .
  reduce read(add(p, addn(add(m, add(n, c))))) ==
         read(add(p, addn(add(n, add(m, c))))) .
  close
\end{ccode}
\end{vvtm}
Alternatively, you may use ``\verb|_=*=_|''
(Section \ref{sec:p2-beh-equiv-pred})
and get a proof by {\em coinduction}\index{coinduction}.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> open COUNTER

  -- opening module COUNTER_.*done.

  %COUNTER> ops m n : -> Nat .

  %COUNTER> op c : -> Counter .

  %COUNTER> eq m + n = n + m .
  _

  %COUNTER> eq N:Nat + (M:Nat + P:Nat) = (N + M) + P .

  %COUNTER> reduce add(m, add(n, c)) =*= add(n, add(m, c)) .
  *
  -- reduce in % : add(m,add(n,c)) =*= add(n,add(m,c))
  true : Bool
  (0.000 sec for parse, 9 rewrites(0.000 sec), 37 matches)
  %COUNTER> close

  CafeOBJ> 
\end{ccode}
\end{vvtm}
The reduction went as desired, since the system automatically
added an equation
\begin{vvtm}
\begin{ccode}
  eq hs1:Counter =*= hs2:Counter = read(hs1:Counter) == read(hs2:Counter) .
\end{ccode}
\end{vvtm}
once ``\verb|_=*=_|'' was shown to be a congruence
(Section \ref{sec:p2-hsort-beget-axs}).

As an aside, you may wonder why two axioms are given in these forms:
commutativity is stated with constants, while associativity is with
variables. The reason is that a straightforward statement of commutativity
\begin{vvtm}
\begin{ccode}
  eq M:Nat + N:Nat = N + M .
\end{ccode}
\end{vvtm}
engenders infinite rewrite sequences. The trick here is to give an
axiom that restricts the matching power of the system so that,
only in the special instances when you need for this special proof,
the axiom is usable as a rewrite rule.

\subsection{Behavioural Transition}\label{sec:p2-proving-beh-trans}

To illustrate proofs on behavioural transitions, we define
counters of wobbly numbers.\label{exs:w-counter}
\begin{vvtm}
\begin{ccode}
  module W-COUNTER {
    protecting (CHOICE-NAT)
    *[ Counter ]*
    bop read : Counter -> Nat
    bop add : Nat Counter -> Counter
    eq read(add(N:Nat, C:Counter)) = N + read(C) .
}
\end{ccode}
\end{vvtm}
The structure is the same as \verb|COUNTER|, and the difference is
in the imported \verb|CHOICE-NAT|. We would like to
prove a behavioural transition relation
\begin{vvtm}
\begin{ccode}
  btrans add(M:Nat | N:Nat, C:Counter) => add(N, C) .
\end{ccode}
\end{vvtm}
An element of hidden sort behaviourally transits to another
iff every observation of the former transits to the same
observation of the latter. This definition leads to
a proof by context induction, as in the previous section. The session goes
as follows.
\begin{vvtm}
\begin{ccode}
  CafeOBJ> open W-COUNTER

  -- opening module W-COUNTER_.*done.

  %W-COUNTER> ops m n p : -> Nat .

  %W-COUNTER> op c : -> Counter .

  %W-COUNTER> op addn : Counter -> Counter .

  %W-COUNTER> reduce read(add(m | n, c)) ==> read(add(m, c)) .
  _*
  -- reduce in % : read(add(m | n,c)) ==> read(add(m,c))
  true : Bool
  (0.010 sec for parse, 6 rewrites(0.010 sec), 32 matches)
  %W-COUNTER> trans read(addn(add(m | n, c))) => read(addn(add(m, c))) .

  %W-COUNTER> reduce read(add(p, addn(add(m | n, c)))) 
      ==> read(add(p, addn(add(m, c)))) .
  *
  -- reduce in % : read(add(p,addn(add(m | n,c)))) ==> read(add(p,addn(
      add(m,c))))
  true : Bool
  (0.000 sec for parse, 4 rewrites(0.000 sec), 11 matches)
  %W-COUNTER> close

  CafeOBJ> 
\end{ccode}
\end{vvtm}
The command sequence is quite similar to the one in the previous section.
Or, relying on ``\verb|=*=|'', you may be rest assured by just one
reduction
\begin{vvtm}
\begin{ccode}
  %W-COUNTER> reduce read(add(m | n, c)) ==> read(add(m, c)) .
\end{ccode}
\end{vvtm}
which, by itself, is a proof by coinduction. A difference from the case of
behavioural equivalence is that the system does not suppy an
axiom like
\begin{vvtm}
\begin{ccode}
  eq hs1:Counter =*= hs2:Counter = read(hs1:Counter) == read(hs2:Counter) .
\end{ccode}
\end{vvtm}
so you have to be satisfied by handfeed reduction commands for each
``attribute''.

%\subsection{Congruences for Coinduction}\label{sec:p2-congruence-def}
%
%Since the predicate ``\verb|=*=|'' is not omnipotent, you may want to
%define your own congruences on hidden sorts. Consider a parametric module
%\verb|STREAM|.
%\begin{vvtm}
%\begin{ccode}
%  module* STREAM (X :: ONE) {
%    *[ Stream ]*
%    bop head : Stream -> Elt
%    bop tail : Stream -> Stream
%    op merge : Stream Stream -> Stream
%    vars S S' : Stream
%    eq head(merge(S,S')) = head(S) .
%    beq tail(merge(S,S')) = merge(S',tail(S)) .
%  }
%\end{ccode}
%\end{vvtm}

\chapter{Built-in Modules}\label{sec:p2-builtin-module}

You may define any data types in \cafeobj, so in principle the need for
built-in data types does not arise. So is the principle, but
considerations about
convenience and tolerable performance dictate otherwise. Some
frequently used data types are defined in {\em built-in module}s.
\index{built-in module} In addition,
the system relies on a couple of {\em kernel module}s,\index{kernel module}
which are located near its jugular.
A few commands, such \verb|reset| (Section \ref{sec:p2-startup}) are
closely related to these modules.

Listed below are the kernels and built-ins.
(As explained in Section \ref{sec:p2-init-opt}, you may supply your
own built-ins, or even override the standard built-ins.)
\begin{itemize}
\item[] \textbf{ Systems}. Some modules are vital to the behaviour of
  the system. Unless you are ready to help us tune the system, they
  need not concern you.
\item[] \textbf{ Booleans}. The module \verb|BOOL| and the sort \verb|Bool|
  have appeared frequently. Actually, \verb|Bool| is declared in a
  submodule imported by \verb|BOOL|. And \verb|RWL| is a module that
  declares transition predicate ``\verb|_==>_|''.
\item[] \textbf{ Numbers}. The system supports usual arithmetics within
  a usual number system. The modules involved are
  \verb|NAT|, \verb|INT|, \verb|RAT| and \verb|FLOAT|.
\item[] \textbf{ Strings}. \verb|QID| (quoted identifier),
  \verb|CHARACTER|, \verb|STRING| define operations on characters
  and strings.
\item[] \textbf{ Pairs}. A simple pair, triple, and quadruple are defined
  in \verb|2TUPLE|, \verb|3TUPLE|, and \verb|4TUPLE|.
\item[] \textbf{ Miscellaneous}. For historical reasons, \verb|PROPC|
  (Section \ref{exs:propc}), \verb|TRIV| (Section \ref{exs:triv})
   are built-in modules.
\end{itemize}
There are also a set of library modules and examples in the
distribution package.

\begin{warning}
  Elements in built-in sorts are defined as corresponding Lisp objects,
  and the system may compute them by stealth. For example,
  an expression \verb|2.1e1| is an element of \verb|Float|, and
  is {\em identified} with \verb|21.0|; \verb|2/1| is an element of
  \verb|Rat|, and is identified with \verb|2|.
\end{warning}

\begin{warning}
  The built-ins and their definitions may change.
\end{warning}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\appendix
\chapter{Summary of \cafeobj~~syntax}

Here is a brief summary of lexical conventions and syntactic definitions
used in \cafeobj~codes and commands.

\section{Lexical Analysis} \label{sec:lex}

On the lexical surface a \cafeobj~code is a sequence of tokens and
separators.
A {\em token} is a sequence of printable ASCII characters (octal
40 through 176)\footnote{The current system accepts Unicode 
characters also, but this is beyond the definition of
the language.}, and is classified as either a self-terminating
character, an identifier, or an operator symbol. Each class
is explained below.

A {\em separator} is a blank character --- space, vertical tab,
horizontal tab, carriage return, newline, or from feed.

On the one hand, any mumber of separators may appear between tokens. 
On the other hand, one or more separators must appear between any two
adjacent non-self-terminating tokens\footnote{The same rule
applies to terms.
Further, if an operator symbol contains blanks or
self-terminating characters, it is sometimes neccessary to enclose a
term with such operator as top by parentheses for disambiguation.}.

\subsection{Reserved Words} \label{sec:keywords}

There is {\em no} reserved word.
One can use such keywords such as \sym{module}, \sym{op}, \sym{var},
or \sym{signature}, etc. for identifiers or operator symbols.

\subsection{Self-Terminating Characters} \label{sec:lex-selfterminating}

A self-terminating character is a printable ASCII character
which by itself constitutes a token. There are seven such characters.
\begin{center}
\begin{minipage}{0.5\textwidth}
\begin{snugshade}
\begin{tabular}{lllllll}
  \verb|(| & \verb|)| & \verb|,| & \verb|[| & \verb|]| & \verb|{| & \verb|}|
\end{tabular}
\end{snugshade}
\end{minipage}
\end{center}
%%
\subsection{Identifiers} \label{sec:lex-identifier}

An \textit{ident} (identifier)
is a sequence of any printable ASCII characters other than
\begin{center}
\begin{minipage}{0.5\textwidth}
\begin{snugshade}
  \begin{tabular}{l}
    self-terminating characters \\
    \verb|.| (period) \\
    \verb|"| (double quote) \\
  \end{tabular}
\end{snugshade}
\end{minipage}
\end{center}

The \cafeobj~reader is case-sensitive, and \verb|Nat| and \verb|nat| are
different identifiers.
\textit{ident}s appear as module names, view names,
parameter names, sort names, variables names,
slot names, and labels.

\subsection{Operator Symbols} \label{sec:opsymbol}

An \nonterm{operator\_symbol} is a sequence of any ASCII characters,
including non-printables, except EOT (control-D).

An underbar has a special meaning in an operator symbol.
It reserves the place where an argument is inserted.
A single underbar \verb|_| cannot be an operator symbol.

\subsection{Comments} \label{sec:lex-comments}

A \nonterm{comment} is a sequence of characters which begins with one
of the following four character sequences
\begin{center}
\begin{minipage}{0.5\textwidth}
\begin{snugshade}
  \begin{tabular}{ll}
    "\verb|--|" & 
    "\verb|-->|" \\
    "\verb|**|" &
    "\verb|**>|"
  \end{tabular}
\end{snugshade}
\end{minipage}
\end{center}
and that ends with a newline character. In between, a comment may
contain only printable ASCII characters and horizontal tabs.

Comments may act as separators, but their appearance is restricted
(See the next section).

\newpage
\section{\cafeobj~ Syntax} \label{sec:cafeobj-syntax}
We use an extended BNF grammar to define the syntax. The general form
of a production is
\begin{vvtm}
\begin{syntax}
\synindent\synindent  nonterminal &::=& alternative \alt alternative \alt \cdots \alt alternative
\end{syntax}
\end{vvtm}
The following extensions are used:
\begin{center}
\begin{fminipage}{0.7\textwidth}
  \begin{tabular}{ll}
    $\alpha$ $\cdots$ & a list of one or more $\alpha$s. \\
    $\alpha$, $\cdots$ & a list of one or more $\alpha$s separated by commas: \\
    & ``$\alpha$'' or ``$\alpha$, $\alpha$'' or ``$\alpha$, $\alpha$, $\alpha$'', etc. \\
    $\seqof{\alpha}$ & \textbf{\{} and \textbf{\}} are meta-syntactical
    brackets \\ 
    & treating $\alpha$ as one syntactic category. \\
    $\optn{\alpha}$ & an optional $\alpha$: `` '' or ``$\alpha$''.
  \end{tabular}
\end{fminipage}
\end{center}
Nonterminal symbols appear in \textit{italic face}. Terminal symbols
appear in the face like this: ``\sym{terminal}'', and may be
surrounded by `` and '' for emphasis or to avoid confusion
with meta characters used in the extended BNF. We will refer terminal
symbols other than self-terminating characters (see section
~\ref{sec:lex-selfterminating}) as \textit{keyword}s in this document.

\subsection{\cafeobj~Codes}
A \cafeobj~code is a sequence of modules, views, and evaluation commands.
\begin{vvtm}
\begin{syntax}
  \synindent\synindent spec &::=& \seqof{module \alt view \alt eval} \cdots
\end{syntax}
\end{vvtm}
%%%
\newpage
\subsection{Modules} \label{sec:syntax-module}
where a \nonterm{module} is
\begin{vvtm}
\begin{syntax}
  module &::=& module\_type\; module\_name \;
  \optn{parameters} \;
  \optn{principal\_sort} \\
  && \sym{``\{''}\; module\_elt\cdots \; \sym{``\}''} \\
  \synindent module\_type &::=& \sym{module} \alt \sym{module!} \alt
  \sym{module*}\\ 
  \synindent module\_name &::=& ident  
  % &\footnote{The nonterminal \textit{ident} is for identifiers and 
  %   will be defined in the section ~\ref{sec:identifier}.} 
  \\
  parameters &::=& \sym{``(''}\; parameter, \cdots \sym{``)''}\\
  \synindent parameter &::=&
  \optn{\sym{protecting}\alt\sym{extending}\alt\sym{including}}\; 
  paramter\_name \; 
  \sym{::}\; module\_expr 
  %& \footnote{\textit{module\_expr} is defined in 
  %   the section ~\ref{sec:modexpr}.}\footnote{If optional
  %   $\optn{\sym{protecting}\alt\sym{extending}\alt\sym{including}}$ is omitted, it is
  %   defaulted to \sym{protecting}.}
  \\
  \synindent parameter\_name &::=& ident \\
  principal\_sort &::=& \sym{principal-sort}\; sort\_name \\
  % module\_elt &::=& import \alt sort \alt record \alt operator \alt 
  module\_elt &::=& import \alt sort \alt operator \alt 
  % module\_elt &::=& import \alt sort  \alt operator \alt
  variable \alt axiom \alt comment
  % &\footnote{\nonterm{comment} is
  %   descussed in section ~\ref{sec:comments}.}
  \\  
  import &::=& \seqof{\sym{protecting}\alt\sym{extending}\alt\sym{including}\alt\sym{using}}
  \sym{``(''}\;module\_expr\;\sym{``)''}\\
  sort & ::= & visible\_sort \alt hidden\_sort \\
  \synindent visible\_sort & ::=& \sym{``[''}\; sort\_decl, \cdots \; \sym{``]''} \\
  \synindent hidden\_sort & ::=& \sym{``*[''}\; sort\_decl, \cdots \; \sym{``]*''} \\
  \synindent sort\_decl &::=& sort\_name\; \cdots\; \optn{supersorts\; \cdots} \\
  \synindent supersorts &::=& <\; sort\_name\; \cdots \\
  \synindent sort\_name &::=& sort\_symbol\optn{qualifier} 
  % & \footnote{There must not be any separators (see section
  %   ~\ref{sec:lex}) between \nonterm{ident} and \nonterm{qualifier}.}
  \\ 
  \synindent sort\_symbol &::=& ident \\
  \synindent qualifier &::=& \sym{``.''}module\_expr\optn{qualifier}\\
  %% record &::=& \sym{record}\; sort\_name\; \optn{super\;\cdots}\;
  %% \sym{``\{''}\; \seqof{slot \alt comment}\cdots \; \sym{``\}''} \\
  %% \synindent super &::=&
  %% \sym{``[''}\;sort\_name\;\optn{\sym{``(''}\; slot\_rename,\cdots
  %%   \sym{``)''}}\;\sym{``]''} \\
  %% \synindent slot &::=& slot\_name : sort\_name \alt
  %% slot\_name\;\sym{=}\;\sym{``(''}term\sym{``)''}\;:\; sort\_name \\
  %% \synindent slot\_name &::=& ident \\
  %% \synindent slot\_rename &::=& slot\_name\; \verb|->|\; slot\_name\\
  operator &::=& \seqof{\sym{op}\alt\sym{bop}}
               \; operator\_symbol\; : \; \optn{arity}\; \verb|->|\;
  coarity \; \optn{op\_attrs} 
  % &\footnote{\nonterm{operator\_symbol} is defined in section
  %   ~\ref{sec:opsymbol}.}
  \\ 
  \synindent arity &::=& sort\_name \cdots \\
  \synindent coarity &::=& sort\_name \\
  \synindent op\_attrs &::=& \sym{``\{''}\;op\_attr\cdots\;\sym{``\}''} \\
  \synindent op\_attr &::=& \sym{constr} \alt 
  \sym{associative} \alt \sym{commutative}
  \alt\sym{idempotent}
  \alt \seqof{\sym{id:} \alt \sym{idr:}} \sym{``(''} \; term\; \sym{``)''}
  %&\footnote{The general syntax of \nonterm{term} is defined in section
  %  ~\ref{sec:term}.}
  \\
  &\alt & \sym{strat: ``(''}\; natural \cdots\; \sym''{)''}
  \alt\sym{prec:}\; natural 
  \alt \sym{l-assoc} \alt \sym{r-assoc} \alt \sym{coherent} 
  % &\footnote{\nonterm{natural} is a natural number written in ordinal
  %   arabic notation.} 
  \\
  variable &::=& \sym{var}\; var\_name\; :\; sort\_name \alt
  \sym{vars} \; var\_name\cdots\; :\; sort\_name \\
  \synindent var\_name &::=& ident \\
  axiom &::=& equation \alt cequation\alt transition \alt ctransition \\
  \synindent equation &::=& \seqof{\sym{eq} \alt \sym{beq}}\;
  \optn{label}\; term \; \sym{=} \; term\; \sym{``.''}\\
  \synindent cequation &::=& \seqof{\sym{ceq} \alt \sym{bceq}}\;
  \optn{label}\; term \; \sym{=} 
  \; term\; \sym{if}\; term\;\sym{``.''} \\
  \synindent transition &::=& \seqof{\sym{trans} \alt \sym{btrans}}\;
  \optn{label}\; term \; \verb|=>| \; term \;\sym{``.''}\\
  \synindent ctransition &::=& \seqof{\sym{ctrans} \alt \sym{bctrans}}\;
  \optn{label}\; term \; \verb|=>| \; term\; \sym{if}\; term\;\sym{``.''}\\
  \synindent label &::=& \sym{``[''}\; ident\; \sym{``]:''}
\end{syntax}
\end{vvtm}
%%
\newpage
\subsection{Module Expression}
\label{sec:modexpr}
A \nonterm{module\_expr} is
\begin{vvtm}
\begin{syntax}
  module\_expr &::=& module\_name \alt sum \alt rename \alt instantiation 
  \alt \sym{``(''} module\_expr \sym{``)''} \\
  sum &::=& module\_expr\; \seqof{+\;\; module\_expr} \cdots \\
  rename &::=& module\_expr\;\sym{*}\;\sym{``\{''} rename\_map,\cdots
               \sym{``\}''} \\ 
%  instantiation &::=&  module\_expr\;\sym{``(''}
%  \seqof{ident \optn{qualifier}\;\verb|<=|\;aview},\cdots
%  \sym{``)''}
  instantiation &::=& module\_expr\;\sym{``(''}\textbf{\{}\;ident 
  [ qualifier ]\; \verb|<=|\; aview\textbf{\}},\;\cdots\;\sym{``)''}
  \\ 
  rename\_map &::=& sort\_map \alt op\_map \\
  sort\_map &::=& \seqof{\sym{sort} \alt \sym{hsort}}\; 
  sort\_name \; \verb|->|\; ident \\
  op\_map &::=& \seqof{\sym{op} \alt \sym{bop}}\;
                op\_name\;\verb|->|\;operaotr\_symbol \\
  op\_name &::=& operator\_symbol\alt 
  \sym{``(''}operator\_symbol\sym{``)''}qualifier\\
  aview &::=& view\_name\alt module\_expr\\
  & \alt & 
  \sym{view to}\; module\_expr\;\sym{``\{''} view\_elt,\cdots \sym{``\}''} \\
  view\_name &::=& ident \\
  view\_elt &::=& sort\_map \alt op\_view \alt variable \\
  op\_view &::=& op\_map \alt term\; \verb|->|\; term
\end{syntax}
\end{vvtm}
When a module expression is not fully parenthesized, the proper
nesting of subexpressions may be ambiguous. The following precedence rule
is used to resolve such ambiguity:
\[ \nonterm{sum} < \nonterm{rename} < \nonterm{instantiation} \]

\subsection{Views} \label{sec:syntax-view}
and a \nonterm{view} is
\begin{vvtm}
\begin{syntax}
  view &::=& \sym{view}\; view\_name\; \sym{from}\; module\_expr\; \sym{to}
  \; module\_expr \\
  && \sym{``\{''}\; view\_elt, \cdots \; \sym{``\}''} \\
\end{syntax}
\end{vvtm}

\subsection{Evaluation Commands} \label{sec:syntax-eval}

and an \nonterm{eval} is
\begin{vvtm}
\begin{syntax}
  eval & ::= & \seqof{\sym{reduce}\alt\sym{behavioural-reduce}
    \alt\sym{execute}}\; context\;
  term\; \sym{``.''} \\
  context & ::=& \sym{in}\; module\_expr\;\sym{:} 
\end{syntax}
\end{vvtm}
The interpreter has a notion of \textit{current module} which
is specified by a \nonterm{module\_expr} and establishes a context.
If it is set, \nonterm{context} can be omitted.

\subsection{Terms} \label{sec:syntax-term}

A \nonterm{term} is a sequence of any ASCII characters except EOT.

\subsection{Sugars and Abbreviations} \label{sec:syntax-abbrev}

\paragraph{Module type}
There are following abbreviations for \nonterm{module\_type}.
\begin{center}
  \begin{minipage}{0.3\textwidth}
%    \begin{vvtm}
      \begin{tabular}{ll}\hline
        Keyword & Abbriviation \\\hline
        \sym{module} & \sym{mod}\\
        \sym{module!} & \sym{mod!} \\
        \sym{module*} & \sym{mod*}\\\hline
      \end{tabular}
%    \end{vvtm}
  \end{minipage}
\end{center}

%%%

\paragraph{Module Declaration}
\nonterm{make} is a short hand for declaring module of
name \nonterm{module\_name} which imports \nonterm{module\_expr} with 
protecting mode. 
\begin{vvtm}
\begin{syntax}
  make &::=& \sym{make}\;module\_name\;\sym{``(''}\; module\_expr\;\sym{``)''}
\end{syntax}
\end{vvtm}

\begin{ccode}
  make FOO (BAR * {sort Bar -> Foo})
\end{ccode}

is equivalent to

\begin{ccode}
  module FOO { protecting (BAR * {sort Bar -> Foo}) }
\end{ccode}


\paragraph{Principal Sort}
\sym{principal-sort} can be abbriviated to \sym{psort}.

\paragraph{Import Mode}
For import modes, the following abbriviations can be used:
\begin{center}
  \begin{minipage}{0.31\textwidth}
%    \begin{vvtm}
      \begin{tabular}{ll}\hline
        Keyword & Abbriviation \\\hline
        \sym{protecting} & \sym{pr} \\
        \sym{extending} & \sym{ex} \\
        \sym{including} & \sym{inc} \\
        \sym{using} & \sym{us} \\\hline
      \end{tabular}
%    \end{vvtm}
  \end{minipage}
\end{center}

\paragraph{Simultaneous Operator Declaration}
Several operators with the same arity, coarity and operator attributes 
can be declared at once by \sym{ops}.
The form
\begin{vvtm}
\begin{syntax}
  \sym{ops}\; operator\_symbol_1 \cdots operator\_symbol_n\;
  :\; arity\; \verb|->|\; coarity\; op\_attrs
\end{syntax}
\end{vvtm}
is just equivalent to the following multiple operator declarations:
\begin{vvtm}
\begin{syntax}
\sym{op}\; & operator\_symbol_1\;:\;arity\;\verb|->|\;coarity\;op\_attrs 
\\
&\vdots\\
\sym{op}\; & operator\_symbol_n\;:\;arity\;\verb|->|\;coarity\;op\_attrs 
\end{syntax}
\end{vvtm}
\sym{bops} is the counterpart of \sym{ops} for behavioural operators.
\begin{vvtm}
\begin{syntax}
  \sym{bops}\; operator\_symbol\;\cdots\; : \; arity\;\verb|->|\;
  coarity \; op\_attrs
\end{syntax}
\end{vvtm}
and the effect is the same as many \nonterm{operator\/}s as there are
\nonterm{operator\_symbols\/}s.

In simultaneous declarations, parentheses are sometimes necessary
to separate operator symbols. This is always required if an operator
symbol contains dots, blank characters or underscores.
  
\paragraph{Predicate}
A \nonterm{predicate} is a syntactic sugar for operator declarations with
arity \verb|Bool|, and is defined as
\begin{vvtm}
\begin{syntax}
  predicate &::=&
  \sym{pred}\;operator\_symbol\;:\;arity\;\optn{op\_attrs} 
  % &\footnote{You cannot use \nonterm{sort\_name} of the same
  %   character sequence as that of any keywords, i.e., \sym{module}, 
  %   \sym{op}, \sym{vars}, etc. in \nonterm{arity}.}
\end{syntax}
\end{vvtm}
The form
\begin{vvtm}
\begin{syntax}
 \sym{pred}\;operator\_symbol\;:\;arity\;op\_attrs 
\end{syntax}
\end{vvtm}
is equivalent to:
\begin{vvtm}
\begin{syntax}
\sym{op}\;operator\_symbol\;:\;arity\;\verb|->|\; \sym{Bool} \;op\_attrs
\end{syntax}
\end{vvtm}

\paragraph{Operator Attributes}
The following abbriviations are available:
\begin{center}
  \begin{tabular}{ll}\hline
    Keyword & Abbriviation \\\hline
    \sym{associative} & \sym{assoc} \\
    \sym{commutative} & \sym{comm} \\
    \sym{idempotent} & \sym{idem} \\\hline
  \end{tabular}
\end{center}

\paragraph{Axioms}
For the keywords introducing axioms, the following
abbriviations can be used:
\begin{center}
  \begin{tabular}{ll|ll}\hline
    Keyword & Abbriviation & Keyword & Abbriviation \\\hline
    \sym{ceq} & \sym{cq} & 
    \sym{bceq} & \sym{bcq} \\
    \sym{trans} & \sym{trns} &
    \sym{ctrans} & \sym{ctrns} \\
    \sym{btrans} & \sym{btrns} &
    \sym{bctrans} & \sym{bctrns} \\\hline
  \end{tabular}
\end{center}

\paragraph{Blocks of Declarations}
Importationss, signature definitions and
axioms can be clusterd in blocks
\nonterm{imports}, \nonterm{signature}, and \nonterm{axioms} respectively.
\begin{vvtm}
\begin{syntax}
  imports &::=&
  \sym{imports}\;\sym{``\{''}\\
  &&\synindent\seqof{import \alt comment}\cdots\\
  &&\sym{``\}''}\\
  signature &::=& \sym{signature}\;\sym{``\{''}\\
%  &&\synindent\seqof{sort \alt record \alt operator \alt
  &&\synindent\seqof{sort \alt operator \alt
    comment}\cdots\\
  &&\sym{``\}''}\\
  axioms &::=&  \sym{axioms}\;\sym{``\{''}\\
  &&\synindent\seqof{variable \alt axiom\alt comment}\cdots\\
  &&\sym{``\}''}
\end{syntax}
\end{vvtm}
\paragraph{Views}
It is possible to identify parameters by positions, not by names. 
For example, if a parametric module is declared as
\begin{ccode}
  module! FOO (A1 :: TH1, A2 :: TH2) { ... }
\end{ccode}
the form
\begin{ccode}
  FOO(V1, V2)
\end{ccode}
is equivalent to 
\begin{ccode}
  FOO(A1 <= V1, A2 <= V2)
\end{ccode}

Moreover, \sym{view to} construct in arguments of module
instantiations can always be omitted. So,
\begin{example}
   \kbd{FOO(A1} \verb|<=| \sym{view to} \nonterm{module\_expr}\{...\}\kbd{)}
\end{example}
can be written as
\begin{example}
   \kbd{FOO(A1} \verb|<=| \nonterm{module\_expr}\{...\}\kbd{)}
\end{example}

\paragraph{Evaluation}
For \nonterm{eval}, the following abbriviations are available:
\begin{center}
\begin{tabular}{ll}\hline
Keyword & Abbriviation \\\hline
\sym{reduce} & \sym{red} \\
\sym{bereduce} & \sym{bred} \\
\sym{execute} & \sym{exec} \\\hline
\end{tabular}
\end{center}

%%%%%%%%%%%%%%%%%%%%%%%%
\clearpage

\chapter{Command Summary}\label{sec:ref-cafeobj-cmds}

Following is the top level commands that do not constitute \cafeobj~codes.

\textit{}
\begin{tabular}{r c l}
  command &::=& show $|$ describe $|$ set $|$ input $|$ check $|$
    regularise $|$ save $|$ restore $|$ save\_system \\
  &$|$& protect $|$ unprotect $|$ clean\_memo $|$ reset $|$ full\_reset $|$
    parse $|$ lisp\_call $|$ select $|$ open \\
  &$|$& close $|$ start $|$ apply $|$ match $|$
    choose $|$ find $|$ provide $|$ require $|$ autoload \\
  &$|$& eof $|$ prompt $|$ quit $|$ cd $|$ ls $|$ pwd $|$ help $|$
    shell\_call $|$ dribble $|$ period $|$ compile \\
  \\
  show &::=& \verb|show| $\{$ help $|$ module\_contents $|$
    switches $\}$ \\
  describe &::=& \verb|describe| $\{$ help $\}$ $|$ module\_contents $\}$ \\
  set &::=& \verb|set| $\{$ set\_help $|$ set\_switch $|$ set\_other $\}$ \\
  input &::=& \verb|input| file\_name \\
  protect &::=& \verb|protect| module\_name \\
  unprotect &::=& \verb|unprotect| module\_name \\
  full\_reset &::=& \verb|full-reset| $|$ $\{$ \verb|full| \verb|reset| $\}$ \\
  open &::=& \verb|open| module\_expression \\
  close &::=& \verb|close| \\
  start &::=& \verb|start| term ``\verb|.|'' \\
  parse &::=& \verb|parse| $[$ context $]$ term ``\verb|.|'' \\
  cd &::=& \verb|cd| file\_name \\
  quit &::=& \verb|quit| \\
  period &::=& ``\verb|.|'' \\
  shell\_call &::=& ``\verb|!|'' shell\_command \\
  provide &::=& \verb|provide| feature \\
  require &::=& \verb|require| feature $[$ file\_name $]$ \\
  ls &::=& \verb|ls| file\_name \\
  compile &::=& \verb|tram| \verb|compile| $[$ compile\_option $]$
    module\_expression \\
  compile\_option &::=& \verb|-exec| \\
  eof &::=& \verb|eof| \\
  save &::=& \verb|save| file\_name \\
  restore &::=& \verb|restore| file\_name \\
  clean\_memo &::=& \verb|clean| \verb|memo| \\
  dribble &::=& \verb|dribble| file\_name \\
  select &::=& \verb|select| module\_expresion \\
  lisp\_call &::=& $\{$ \verb|lisp| $|$ \verb|lispq| $\}$ S\_expression \\
  help &::=& ``\verb|?|'' \\
  autoload &::=& \verb|autoload| proc\_name \\
  find &::=& \verb|find| $\{$ \verb|rule| $|$ \verb|+rule| $|$ \verb|-rule|
    $\}$ \\
  match &::=& \verb|match| term\_specifier \verb|to| match\_pattern
    ``\verb|.|'' \\
  term\_specifier &::=& \verb|top| $|$ \verb|term| $|$ \verb|it| $|$ subterm
    $|$ ``\verb|(|'' term ``\verb|)|'' \\
  match\_pattern &::=& $\{$ $[$ \verb|all| $]$
    $\{$ \verb|rules| $|$ \verb|+rules| $|$ \verb|-rules| $\}$ $\}$ \\
    &$|$& term \\
  apply &::=& \verb|apply| action $[$ substitution $]$ range selection \\
  select &::=& \\
  check &::=& \\
  regularise &::=& \verb|regularize| module\_name \\
\end{tabular}
\textrm{}

%\appendix
%\chapter{A Brief Guide to Basic Notions and Terminology}

%\section{Algebra}\label{sec:app-algebra}
%
%An algebra is a system of sets and operators thereon, usually written as a
%list $(S_1, \ldots, S_n, f_1, \ldots, f_m)$. Typical examples are
%a monoid $(M,e,*)$ and a vector space $(V,\cdot)$ over a field $F$.
%
%When there is only one underlying set,
%the rank of an operator is just a natural number that indicates the number
%of arguments.
%For example, in the above monoid, $e$ has rank zero and $*$ has rank $2$.
%If more than one sets are involved, the rank has to be described more
%carefully. In general the rank of an operator is written as
%$f_1 : S_1 \times \ldots \times S_l \to S$ where $S_i$ is the $i$-th
%projection of the domain, and $S$ is the codomain.
%
%The operators of an algebra are often characterised by
%a equational theory. In the case of the above monoid, $e$ and $*$ are
%characterised by three ``law''s
%\begin{quotation}
%$\forall x,y,z[x * (y * z) = (x * y) * z]$ \\
%$\forall x[x * e = x]$ \\
%$\forall x[e * x = x]$
%\end{quotation}
%where the variables are understood to range over $M$. In case of
%the above vector space, $\cdot : F \times V \to V$ is characterised
%by
%\begin{quotation}
%$\forall x \in F,v,w \in V[x \cdot (v + w) = x \cdot v + x \cdot w]$ \\
%$\forall x,y \in F,v \in V[(x + y) \cdot v = x \cdot v + y \cdot v]$ \\
%$\forall x,y \in F,v \in V[(xy)\cdot v = x \cdot (y \cdot v)]$ \\
%$\forall v \in V[1 \cdot v = 1]$ \\
%\end{quotation}
%where $+$ etc. are operators of the underyling field $F$ or group $V$.
%
%Some operator is not total. For example, the inverse $\_^{-1}$ of
%a field is undefined on the additive neutral $0$. Hence
%the characterisation of an operator requires a statement on which elements
%of the domain it is defined on.
%
%A graph is an algebra $(V,E,s,t)$, where
%$s$, $t$ have the same rank $E \to V$ with no characteristic equations.
%You may enrich the algebra with the set of paths $P$ and the composition
%$\circ : P P -> P$ and the extensions to $s$, $t$ to $P$, characterised
%by
%\begin{quotation}
%$\forall e \in E[e \in P]$ \\
%For all $p,q \in P$, $p \circ q$ is defined iff $sp = tq$ \\
%$\forall p,q \in P[s(p \circ q) = sq]$ (if defined) \\
%$\forall p,q \in P[t(p \circ q) = tp]$ (if defined)
%\end{quotation}
%
%\section{Category}\label{sec:app-category}
%
%A category is an algebra $(Obj,Arr,dom,cod,id,\circ)$ where
%$(Obj,Arr,dom,cod)$ is a graph.
%
%A functor from a category $(Obj,Arr,dom,cod,id,\circ)$ to another
%$(Obj',Arr',dom',cod',id',\circ')$ is a pair of functions.
%
%A natural transformation from a functor to another is
%a function.
%
%\section{Institution}\label{sec:app-institution}
%
%An institution is a triple $(S,M,\models)$.
%
%\section{Coinduction}\label{sec:app-coinduction}
%
%A coinduction is a proof technique that uses bisimulation.

\begin{thebibliography}{?-}

\bibitem{trs-handbook} Dershowitz,~N. and Jouannaud,~J.-P.,
  ``Rewrite Systems'',
  \textit{Handbook of Theoretical Computer Science, Vol.B: Formal Models
  and Semantics}, The MIT Press/Elsevier Science Publishers,
  1990, pp.245--320

\bibitem{razvan96-1} Diaconescu,~R. and Futatsugi,~K.,
  \textit{Logical Semantics of CafeOBJ}, Technical Report
  IS-RR-96-0024S, Japan Advanced Institute for Science and
  Teleology, 1996

\bibitem{cafeobj-rep} Diaconescu,~R. and Futatsugi,~K.,
  \textit{CafeOBJ Report}, World Scientific, 1998

\bibitem{e-m85} Ehrig,~H. and Mahr,~B.,
  \textit{Fundamentals of Algebraic Specifications 1:
       Equations and Initial Semantics},
  Springer-Verlag, 1985

\bibitem{institution} Goguen,~J. and Burstall,~R.,
  ``Institutions: Abstract Model Theory for Specification and Programming'',
  \textit{Journal of the Association for Computing Machinery},
  Vol.39, 1992, pp.95--146

\bibitem{osa-survey} Goguen,~J. and Diaconescu,~R.,
  ``An Oxford Survey of Order Sorted Algebra'',
  Mathematical Structures in Computer Science, Vol.4, 1994,
  pp.363--392

\bibitem{hsa} Goguen,~J. and Malcom,~G.,
  \textit{A Hidden Agenda}, technical report, UCSD, 1998

\bibitem{osa} Goguen,~J.A. and Meseguer,~J.,
 \textit{Order-Sorted Algebra 1:
  Equational Deduction for Multiple Inheritance, Polymorphism,
  Overloading and Partial Operations},
  Technical Report SRI-CSL-89-10, SRI International, 1989

\bibitem{OBJ} Goguen,~J., Winkler,~T., Meseguer,~J., Futatsugi,~K.,
  and Jouannaud,~J.-P.,
 \textit{Introducing OBJ}, Technichal Report
  SRI-CSL-92-03, SRI International, 1992

\bibitem{eatcs-coalg} Jacobs,~B. and Rutten,~J.,
  ``A Tutorial on (Co)Algebras and (Co)Induction'',
  \textit{EATCS Bulletin}, No.62, EATCS, 1997, pp.222--259

\bibitem{trs-eatcs} Klop,~J.W.,
  ``Term Rewriting Systems: A Tutorial'',
  \textit{EATCS Bulletin}, No.32, EATCS, 1987, pp.143--182

\bibitem{rew-logic} Meseguer,~J.,
  ``Conditional Rewriting Logic: Deduction, Models and Concurrency'',
  \textit{Proc. 2nd International CTRS Workshop}, Lecture Notes in
  Computer Science 516, 1991, pp.64--91

\bibitem{m-g82} Meseguer,J. and Goguen,J.A.,
  ``Initiality, induction and computability'',
  \textit{Algebraic Methods in Semantics},
  Cambridge University Press, 1984, pp.459--541

\end{thebibliography}
\clearpage
\twocolindex
\pagestyle{index}
%\renewcommand{\chaptermark}[1]{}
\renewcommand{\preindexhook}{%
The first page number is usually, but not always, the primary reference to
the indexed topic.\vskip\onelineskip}
\indexintoc

%%%\raggedright  does nasty things to index entries
\printindex

\onecolindex
\renewcommand*{\preindexhook}{}
\renewcommand*{\indexname}{Index of first lines}
%%%\indexintoc
\printindex[lines]

\cleardoublepage

\end{document}
