%> do tex %F -l -l -d"-t a4"

\documentstyle[12pt,times]{article}
\input{psfig}

\textwidth=16cm
\oddsidemargin=1cm
\evensidemargin=1cm
\textheight=22cm
\topmargin=0cm
\parindent=0mm
\parskip=4mm

\title{TOPO: Quick Reference	\\
	C Code Generator --- version 3R6}

\author{Jos{\'e} A. Ma{\~n}as	 		\\
        Tom{\'a}s de Miguel	 		\\
        Tom{\'a}s Robles	 		\\
        Joaqu{\'\i}n Salvachua	 	\\
        Gabriel Huecas	 		\\
        Marcelino Veiga	 		\\
					\\
        Dpt. Ingenier{\'\i}a Telem{\'a}tica	\\
        E.T.S.I. de Telecomunicaci{\'o}n	\\
        Univ. Polit{\'e}cnica de Madrid	\\
        E-28040 Madrid, SPAIN	 	\\
					\\
        {\tt <topo@dit.upm.es>}
        }

\date{20 January, 1995}

\pagestyle{myheadings}
\markright{Quick Reference -- C Code Generation}

\begin{document}

\maketitle

\begin{abstract}
TOPO is a set of interoperating LOTOS tools grouped in several packages.
This one contains the C code generator.
It produces a rewrite system for the ADT part,
and a transition system for the behaviour part.
The package includes separate compilers for the behaviour and data
parts, as well as the needed run time libraries, and kernel.
Compiler instantiation is presented below,
altogether with the files involved.
Compiler execution may be affected by means of annotations
that permit the mapping of the abstract LOTOS entities
to real objects.

This paper is a quick reference guide for users.
\end{abstract}

\newpage
\tableofcontents

\newpage

\section{Getting Started \ldots}
TOPO is a set of interoperating LOTOS tools grouped in several packages.
This one contains the C code generator, and must be together with TOPO
Front-End package for proper interworking.
It takes a LOTOS specification
and generates two target modules:
one implementing the abstract data types as a rewrite system,
and another implementing the behaviour as a transition system.
Typically,
one module more is needed to provide a \verb/main/ function as an
interface between the run--time environment and the generated
modules.
More modules may need to be loaded together to build a complete
product.

\begin{center}
\begin{tabular}{| r @{$\;\rightarrow\;$} l |}
  \hline
  spec\verb/.lot/       & The LOTOS specification                  \\
  spec\verb/.c/         & UNIX interface, i.e. \verb/main/ program \\
  \hline
  \verb/ldc.c/          & The implementation of the ADTs	\\
  \verb/ldc.hh/         & Interface to use \verb/ldc.c/		\\
  \verb/lbc.c/          & The implementation of the behaviour	\\
  \verb/lbc.hh/         & Interface to use \verb/lbc.c/		\\
  \hline
\end{tabular}
\end{center}
The LOTOS source specification may be {\bf annotated}
by means of a special class of comments that are transparent to the
``pure LOTOS'' tools,
but may direct the data and behaviour compilers.

TOPO aims to produce working code that may be integrated as a module
of a bigger communications system.

\newpage
\section{Calling the Compilers}
For calling the compilers (C code generators) of TOPO, it is used the
same interface as TOPO Front-End package. Only some actions are added.
\begin{center}
\begin{tabular}{| r | l |}
  \hline
  \multicolumn{2}{| c |}{
    \rule[-3mm]{0mm}{6mm}
    \verb/topo/ spec[\verb/.lot/] action [options]
    } \\
  \hline
  \hline
  -behaviour    &
  \begin{minipage}[t]{10cm}
    Runs the behaviour compiler.
  \end{minipage}                                        \\
  &
  \begin{minipage}[t]{10cm}
    \begin{description}
      \item[-g]
      Adds symbolic information for debugging.
    \end{description}
  \end{minipage}                                        \\
  \hline
  -data    &
  \begin{minipage}[t]{10cm}
    Runs the ADT compiler.
  \end{minipage}                                        \\
  \hline
  -p &
  \begin{minipage}[t]{10cm}
    Generate a prototype of the specification. It calls the behaviour
    and data compiler, and provides a main function.
  \end{minipage}                                        \\
  \hline
  -main    &
  \begin{minipage}[t]{10cm}
    Generate a main function (if none).
  \end{minipage}                                        \\
  \hline
\end{tabular}
\end{center}

Some options are stored in the context, SPEC.ctx,
and \verb/toposet/ allows to deal with them.

Firstly, TOPO should be instructed to generate C language:
\begin{center}
\begin{tabular}{| r | l |}
  \hline
  \multicolumn{2}{| c |}{
    \rule[-3mm]{0mm}{6mm}
    \verb/toposet/ spec[\verb/.lot/] -language C
    } \\
  \hline
\end{tabular}
\end{center}

But, it is not needed, because it is the default.

And then, some extra options can be specified.
\begin{center}
\begin{tabular}{| r | l |}
  \hline
  \multicolumn{2}{| c |}{
    \rule[-3mm]{0mm}{6mm}
    \verb/toposet/ spec[\verb/.lot/] [options]
    } \\
  \hline
  \hline
  -list		& Print current context		\\
  \hline
  -tname NAME	& Root name for C files (behaviour)	\\
  -tpieces \#	& Number of pieces to break C files down	\\
  \hline
  -dname NAME	& Root name for C files (data)	\\
  -dpieces \#	& Number of pieces to break C files down	\\
  \hline
\end{tabular}
\end{center}

You may further influence the behaviour of concrete tools by setting
environment variables:

\begin{center}
\begin{tabular}{| l | l | l |}
  \hline
  variable	& tool		& help		\\
  \hline
  TOPOF\_OM	& om		& om -h		\\
  TOPOF\_IDLE	& idle		& idle -h	\\
  TOPOF\_OMLBC	& omlbC		& omlbC -h	\\
  TOPOF\_D2H	& d2h		& d2h -h	\\
  TOPOF\_D2C	& d2c		& d2c -h	\\
  \hline
\end{tabular}
\end{center}

\newpage
\section{Makefile}
In general, it is not possible to have a \verb/make(1)/ specification
that is universally valid.
Nevertheless,
let's show an example of a typical makefile.
It is ready to work when both behaviour and data are compiled into 1
piece.
You will have to adapt it to different situations

\rule{\textwidth}{.3mm}
\begin{verbatim}
#---> you may wish to change these
SPEC=   spec
DNAME=  ldc
TNAME=  lbc

CFLAGS=-g -I$(TOPOINC)
LDFLAGS=-L$(TOPOLIB) -lotos -lkaos

TRGT=   $(SPEC)
OBJS=   $(DNAME).o $(TNAME).o $(SPEC).o

$(TRGT):        $(OBJS)
        $(CC) $(CFLAGS) -o $@ $(OBJS) $(LDFLAGS)

$(DNAME).o:     $(DNAME).hh
$(TNAME).o:     $(DNAME).hh $(TNAME).hh

$(DNAME).c $(DNAME).hh: $(SPEC).lot $(SPEC).ctx
        $(TOPOBIN)/topo $(SPEC) -verbose -data
$(TNAME).c $(TNAME).hh: $(SPEC).lot $(SPEC).ctx
        $(TOPOBIN)/topo $(SPEC) -verbose -behaviour

$(SPEC).ctx:
        $(TOPOBIN)/toposet $(SPEC) -dname $(DNAME) -tname $(TNAME)

clean tidy::
        rm -f *~ core topocore
        rm -f $(OBJS)
        rm -f $(SPEC).com

clean::
        $(TOPOBIN)/topo $(SPEC) -clean

tidy::
        rm -f $(TRGT)
        $(TOPOBIN)/topo $(SPEC) -tidy
        rm -f $(SPEC).ctx
\end{verbatim}

\newpage
\section{Code Interface}
TOPO provides an implementation of the input specification.
It is a transition system that ``moves'' according to the
specification.
Still to make this system useful,
it must cooperate with the real environment.
Thus,
further C code will be loaded with the automatically derived modules
in order to get a complete program.

In this section the available data structures,
functions and procedures
are described.

\subsection{Data Rewrite System}
Every data is represented at run-time by means of both C structures
called \verb/kdatum/ and \verb/udatum/. The first one is for
automatically generated sorts, and the other one for hand coded sorts.

The ADT compiler CAOS generates one C function for each LOTOS
operation (if not hand coded, of course).

Let's show an example.
From the LOTOS specification spec\verb/.lot/
\begin{verbatim}
  sorts
    nat
  opns
    0     (*| name zero |*) :          -> nat
    _ + _ (*| name plus |*) : nat, nat -> nat
\end{verbatim}

it will generate in \verb/ldc.hh/
\begin{verbatim}
/* 0: -> nat */
kdatum zero(/* void */);

/* _+_: nat, nat -> nat */
kdatum plus(/* kdatum p1, kdatum p2 */);
\end{verbatim}

and in \verb/ldc.c/
\begin{verbatim}
/* 0: -> nat */
kdatum zero() { ... }

/* _+_: nat, nat -> nat */
kdatum plus(p1, p2) kdatum p1; kdatum p2; { ... }
\end{verbatim}

At run time a key value is assigned to each sort in the specification.
It may be obtained by means of calling the library functions
\verb/kd_sort()/, for automatically generated sorts, and
\verb/ud_sort()/, for hand coded ones.
For instance, \verb/kd_sort ("nat")/
returns the unique identifier assigned to sort \verb/nat/.
It is an integer value, that may be used in other functions.

\newpage
In every implementation of LOTOS ADTs,
there are a number of interface functions, all of them included in
KAOS and some ones instantiated by the generated ADT code.
These are publicly available and encapsulate decisions taken by the
compiler at compilation time. There are two groups, one for
automatically generated sorts, prefixed by \verb/kd_/, and another one
for hand coded sorts, prefixed by \verb/ud_/. They have analogue
functions, and the main difference is that \verb/ud_/ group always need
the \verb/sort/ parameter, because the compiler does not know what the
user put inside an \verb/udatum/.
Besides, there is a common initializacion function.

\verb/void ldcinit ()/        \\
It initializes some internal KAOS structures and invokes the code in the
\verb/ldcinit/ annotation. It must be called before using any data type,
both automatically generated ones and hand coded ones.

\verb/int kd_equal (v1, v2) kdatum v1, v2;/        \\
\verb/int ud_equal (sort, v1, v2) int sort; udatum v1, v2;/        \\
\verb/int kd_gequal (v1, v2, mask) kdatum v1, v2; int mask;/        \\
\verb/int ud_gequal (sort, v1, v2, mask) int sort; udatum v1, v2; int mask;/        \\
These functions decide whether two values are equal or not,
according to the data equations.
Technically,
they implement the initial model of the data algebra.
The difference among them is that the first pair does not free its
arguments, and the second pair yes depending on the value of the binary
\verb/mask/, i.e., if first bit is $ 1 $, the first argument must be
freed, if the second one is $ 1 $ the second argument is freed, an if
both ones are $ 1 $ both arguments are freed.

\verb/char* kd_draw (v) kdatum v;/    \\
\verb/char* ud_draw (sort, v) int sort; udatum v;/    \\
\verb/char* kd_gdraw (v, mask) kdatum v; int mask;/    \\
\verb/char* ud_gdraw (sort, v, mask) int sort; udatum v; int mask;/    \\
Pretty print \verb/v/ onto a string (or NULL if cannot),
using always LOTOS prefix notation.
The value returned by the functions
is a pointer into a static buffer,
the contents of which are overwritten by each call.
The difference among them is the same as for equal functions.

\verb/int kd_parse (sort, p, r) int sort; char** p; kdatum* r;/	\\
\verb/int ud_parse (sort, p, r) int sort; char** p; udatum* r;/	\\
\verb/int kd_eval (sort, s, r) int sort; char* s; kdatum* r;/	\\
\verb/int ud_eval (sort, s, r) int sort; char* s; udatum* r;/	\\
Parse a string until it matches a value, then store it in \verb/r/
and return true (i.e. $\not= 0$).
The pointer is updated to the remainder substring.
If no correct value was matched
(because of wrong syntax, ambiguity, ...),
return false (i.e. $0$),
and the pointer is updated to the end of the substring recognized.
Similarly to drawing functions
they only understand LOTOS prefix notation.
The differences among these functions is that
the second pair ones must match the whole string.

\verb/int kd_sort (sortname) char* sortname;/ \\
\verb/int ud_sort (sortname) char* sortname;/ \\
They take a sort name and return its unique identifier (or a negative
number if not found or ambiguous).

As already mentioned, every data of hand coded sorts is encapsulated
(or coded) at run-time into a structure named \verb/udatum/.
So users need to allocate new \verb/udatum/:   \\
\verb/udatum ud_alloc ()/

For properly handling data values, both \verb/kdatum/ and \verb/udatum/,
functions are needed for copying values:		\\
\verb/kdatum kd_copy (n) kdatum n;/			\\
\verb/udatum ud_copy (sort, n) int sort; udatum n;/

And for freeing them:					\\
\verb/void kd_free (n) kdatum n;/			\\
\verb/void ud_free (sort, n) int sort; udatum n;/

Indeed, both \verb/kdatum/ and \verb/udatum/ are shared structures, so
there is no real copy, and memory is only deallocated when it become
unused, i.e., there is no reference to it.

This mechanism saves space and time, and also allows to mark a datum as
permanent, i.e., it will never be deallocated:		\\
\verb/kdatum kd_const (n) kdatum n;/			\\
\verb/udatum ud_const (sort, n) int sort; udatum n;/

Finally, there is one symbolic name, \verb/$#/, that allows access to
arguments of an operation (\# represents its position).
It must be procesed, so it must be used inside of data annotations.
A single \verb/$/ must be escaped as \verb/$$/.

Automatically generated code for LOTOS ADTs may cause serious
performance losses.
Users may replace critical data by manually coded implementations.
A separate document describes in detail the C interface of LOTOS ADTs,
and how replace some parts by hand coded implementations.

\newpage
\subsection{Transition System}
LBC is the compiler for the behaviour.
It implements a transition system.
There are four interface functions:
\verb/lbcinit()/ initializes the transition system;
then there are two alternatives to run it,
either control is given for one step
(\verb/step()/),
or to the built-in scheduler
(\verb/sch()/).
\verb/lbcend()/ finish the transition system; free the resources used
by it. After this  \verb/lbcinit()/ can be called again.

\verb/void lbcinit (argc, argv) int argc; void* argv[];/ \\
External arguments may be provided via a vector of \verb/void*/
(because types of data values can be any {\em x\verb/datum/}).
The first parameter is the number of arguments,
and the second one is a vector of so many arguments.
These are used as value parameters of the specification.

\verb/int step ()/      \\
The automaton is allowed to advance one step.
It returns a status code:
\begin{enumerate}
\item[0]
  The automaton terminates, executing \verb/stop/.
\item[1]
  The automaton terminates with some error condition.
\item[2]
  One step has been successfully performed.
\item[3]
  All potential synchronizations are waiting for some \verb/delay/,
  \verb/wait/ or \verb/eval/ annotation.
\item[4]
  Some  \verb/delay/ or  \verb/wait/ annotation has succeeded, so more
  actions may be performed.
\end{enumerate}

\verb/int sch ()/       \\
The built-in scheduler gets control.
It will run the system for as long as possible,
and return an exit code:
\begin{enumerate}
\item[0]
  The automaton terminates, executing \verb/stop/.
\item[1]
  The automaton terminates with some error condition.
\end{enumerate}

\verb/void lbcend ()/ \\
Just finish everything and free resources.

\verb/void cmd2lbc (argc, argv, nvals, vals)/ \\
\verb/int argc; char *argv[]; int *nvals; value_list *vals;/ \\
This function gets parameters from command line (i.e. strings), and
translate them to be applied to lbcinit() (i.e. {\em x}datum).

\verb/$!#/        \\
This symbolic name allows access to those data values that
have been used in the very last successful rendez--vous.
The \verb/#/ varies from 1 to the total number of experiment offers.
Because of this is a symbolic representation, it needs to be processed,
so it only can be included in behaviour annotations.
% It is publicly accessible,
% and is properly loaded upon \verb/step()/ return.

\verb/$#/ \\
This symbolic name allows access to the value arguments
of the innermost process instantiation.
The \verb/#/ varies from 1 to the total number of formal parameters.
Because of this is a symbolic representation, it needs to be processed,
so it only can be included in behaviour annotations.
% It is a very local piece of information,
% and can only be used in behaviour annotations.
% Its value is undefined upon \verb/step()/ return.

\verb/$$/	\\
It is a escape sequence for \verb/$/.

\verb/int min_delay();/ \\
This function return the minimum amount of time needed for a delay to
succeed. 
This may be used by the user to build his own scheduler, son active
waits can be avoid.

\newpage
\subsection{Debugging Facilities}
A limited amount of debugging may be controlled by the user at run
time.

\subsubsection{Data Checking}
When your specification contains LOTOS data types implemented by hand,
or when you use LOTOS data types from C code, you can have problems
if you don't follow the established procedures.
In those conditions,
sometimes it is difficult to find the bug, and for this reason the
variable \verb/kaos.debug/ is provided. By default its value is
false (i.e. $0$), but if you set it to true (i.e. $\not= 0$), all KAOS
functions check their parameters looking for corrupted data,
badly built, ..., raising an exception when found.

This feature slows down the execution of the specification, but you can
enable/disable it dynamically, so you only need to activate it
in the part where you suspect there is (or is near to) a problem.

\subsubsection{Random Behaviour}
It may be specified that the system runs randomly,
that is,
when there are non-deterministic choices,
one is selected using a random number generator.

By default,
randomness is disabled.
The user can provide it's own random number generator.

For example using the function \verb/random(3)/.
In order to enable it, include the following statement
before calling \verb/sch()/ or \verb/step()/.	\\
\centerline{
  \verb|konfig.random = random;  /* default: NULL */|
}

This option may be enabled/disabled dynamically,
for instance via annotations.

Still \verb/random(3)/ provides a deterministic sequence of random
numbers.
You may consider to set the random number generator to an initial
value that is out of control. For instance	\\
\centerline{
  \verb|srandom (getpid ());|
}

Each system has its own random number generator.
Consult your local system manager for advice.

\subsubsection{Event Tracing}
It is possible to get a print out of the events that occur,
and even a list of the participating partners in it.
This implies keeping a large amount of symbolic information at run
time,
and is not provided as default.
You have to ask for it explicitly when instantiating the behaviour
compiler	\\
\centerline{
  \verb/topo SPEC -behaviour -g .../
}	\\
At run time,
a trace level may be selected:
\begin{center}
\begin{tabular}{| l | l |}
  \hline
  \verb/konfig.trace= 0;/	& default: no trace	\\
  \verb/konfig.trace= 1;/	& trace events		\\
  \verb/konfig.trace= 2;/	& trace events \& partners	\\
  \hline
\end{tabular}
\end{center}
This parameter may be changed dynamically during execution
(e.g. via annotations).

\subsubsection{Synchronization value missing}
If you want to trace synchronization failures due to the lack of values at
negotiation time there is an option for trace this ill behaviour.
\begin{center}
\begin{tabular}{| l | l |}
  \hline
  \verb/konfig.negotiation= 0;/	& default: no trace	\\
  \verb/konfig.negotiation= 1;/	& trace events		\\
  \hline
\end{tabular}
\end{center}
This parameter may be changed dynamically during execution
(e.g. via annotations).

\newpage
\section{Annotations}
TOPO compilers may be directed via annotations.
These are a special class of LOTOS comments that are transparent to
any other tool.
In general an annotation is a pair of a keyword and a value:	\\
\centerline{
  \verb/(*| keyword value |*)/
}

\subsection{Data Annotations}
\begin{itemize}
\item
  \verb/(*| ldc C_code |*)/      \\
  \verb/C_code/ is reproduced verbatim onto file
  \verb/ldc.hh/.
  It is typically used to reference other files that are used to
  implement parts of the data part.
\item
  \verb/(*| ldc C_code |*)/ \\
  This annotation may be used too at the end of the specification
  (i.e. after keyword \verb/endspec/).	\\
  The \verb/C_code/ is reproduced verbatim in file
  \verb/lbc.c/.

  It is typically used to provide in the same file spec\verb/.lot/
  some functions to be used from data annotations.
\item
  \verb/(*| ldcinit C_statements |*)/ \\
  This annotation is specially designed to initialize some constants or
  data structures needed for using hand coded sorts. \verb/C_statements/
  are executed when function \verb/ldcinit()/ is invoked, i.e., at the
  very beginning, when no data type was used. A typical case is to
  initialize a constant containing the unique identifier of a sort, for
  using in \verb/ud_/ functions.
  \begin{verbatim}
    (*| ldcinit
    nat= ud_sort("nat");
    |*)
  \end{verbatim}
\item
  \verb/(*| using C_identifier |*)/	\\
  This applies to operation identifiers.	\\
  The \verb/C_identifier/ will be used as a prefix to generate the full
  operation name.	\\
  It is very useful when there is a lot of overloading,
  either explicit or implied by renaming and/or actualizing.
\item
  \verb/(*| usingsort |*)/	\\
  This applies to operation identifiers.	\\
  It is Similar to \verb/using/ annotation, but the prefix is the name
  generated for the sort of the operation.
\item
  \verb/(*| name C_identifier |*)/      \\
  This applies to sort and operation identifiers.	\\
  It forces CAOS to use the \verb/C_identifier/ when generating C
  code.
\item
  \verb/(*| lexical |*)/	\\
  This applies to sort and operation identifiers.	\\
  It is similar to \verb/name/ annotation, but the name is the lexical
  value of the sort or operation.	\\
  It is the default for sorts.
\item
  \verb/(*| lexicalifpossible |*)/	\\
  This applies operation identifiers.	\\
  It is similar to \verb/name/ annotation, but the name is the lexical
  value of the operation if it is a C identifier,
  otherwise an internal name will be generated.
\item
  \verb/(*| internal |*)/	\\
  This applies operation identifiers.	\\
  It is similar to \verb/name/ annotation, but an internal name will be
  generated.	\\
  It is the default for operations.
\item
  \verb/(*| extern |*)/ \\
  This applies to sort and operation identifiers.

  When applied to sort identifiers,
  CAOS assumes that the corresponding sort is implemented by the user
  using ad-hoc coding,
  always within the frame imposed by \verb/udatum/.
  When a sort is marked as \verb/extern/,
  every {\em constructor} operation of that sort
  must be \verb/extern/ too,
  otherwise there will be a compile-time error.
  By the other hand, equations which outermost operation of left member
  does not belong to a \verb/extern/ sort,
  cannot contain non-constant \verb/extern/ expressions
  in such left member.

  When a sort is marked as \verb/extern/,
  the user must provide an external implementation of equality on that
  sort,
  and functions to pretty-print and parse values of that sort.
  A procedure to remove data of that sort is expected too.

  When applied to operation identifiers,
  CAOS will not generate code for the corresponding operation.
  The equations provided in spec\verb/.lot/ are still analyzed
  semantically, but are not used for code generation.
  The only restriction is that the operation cannot be a
  {\em constructor}.
\item
  \verb/(*| free C_identifier |*)/      \\
  This applies to sort identifiers.     \\
  It identifies a C function that is expected from the user,
  and that is able to free memory allocated to a value of that sort.  \\
  It is called from system freeing functions.	\\
  \centerline{
    \verb/void C\_identifier (n) udatum n; { ... }/
  }
\item
  \verb/(*| nofree |*)/	\\
  This applies to sort identifiers.     \\
  No function is provided to deallocate memory,
  so data of such a sort do not need to deallocate memory.	\\
  It is the default for external sorts, but it avoids a warning.
\item
  \verb/(*| equal C_identifier |*)/     \\
  This applies to sort identifiers.     \\
  It identifies a C function that is expected from the user,
  and that is able to decide whether two values of a sort are to be regarded
  as equal or not.
  It is a manual implementation of the equality induced by equations.  \\
  It is called from system equality functions.	\\
  \centerline{
    \verb/int C\_identifier (v1, v2) udatum v1, v2; { ... }/
  }
\item
  \verb/(*| draw C_identifier |*)/      \\
  This applies to sort identifiers.     \\
  It identifies a C function that is expected from the user,
  and that is able to pretty-print a value of that sort
  (or return NULL if cannot). \\
  It is called from system drawing functions.	\\
  \centerline{
    \verb/char* C\_identifier (v) udatum v; { ... }/
  }
\item
  \verb/(*| nodraw |*)/	\\
  This applies to sort identifiers.     \\
  No function is provided to draw values,
  so data of such a sort are not printable.	\\
  It is the default for external sorts, but it avoids a warning.
\item
  \verb/(*| parse C_identifier |*)/      \\
  This applies to sort identifiers.     \\
  It identifies a C function that is expected from the user,
  and that is able to parse a string against the format of the sort
  values: it traverses the string from the pointer until it doesn't
  match; if a substring was matched, it stores its value in \verb/r/
  and returns \verb/true/ (i.e. $\not= 0$),
  or else returns \verb/false/ (i.e. $0$);
  then, the pointer is updated to the remainder substring.
  It is called from system parsing functions.	\\
  \centerline{
    \verb/int C\_identifier (p, r) char** p; udatum* r; { ... }/
  }
\item
  \verb/(*| noparse |*)/	\\
  This applies to sort identifiers.     \\
  No parsing function is provided,
  so this sort is not parseable.	\\
  It is the default for external sorts, but it avoids a warning.
\item
  \verb/(*| call C_expression |*)/	\\
  This applies to operation identifiers.        \\
  the \verb/C_expression/ is like a macro to be called instead of
  generating code for the operation,
  so the result must be a {\em x\verb/datum/},
  and the operation external.
  \begin{verbatim}
    opns
      not (*| lexical |*): nat -> nat
      eq (*| lexical |*): nat, nat -> nat
      ne (*| extern |*) (*| call not(eq($1, $2)) |*): nat, nat -> nat
  \end{verbatim}
\item
  \verb/(*| partial C_expression |*)/   \\
  This applies to operation identifiers.        \\
  The \verb/C_expression/ is evaluated whenever the operation is
  called.
  It must evaluate to true (i.e. $\not= 0$) for the system to
  continue.
  If it evaluates to $0$,
  a run time exception will be raised.
  \begin{verbatim}
    opns
      empty (*| lexical |*): -> stack
      top (*| partial !kd_gequal($1, empty(), 0x2) |*): stack -> nat
  \end{verbatim}
\item
  \verb/(*| constructor |*)/	\\
  This applies to operation identifiers.        \\
  This operation {\em may} be a constructor,
  i.e., if every pattern for rewriting fails,
  it is legal to build a term using this operation.	\\
  It is the default.
\item
  \verb/(*| nonconstructor |*)/	\\
  This applies to operation identifiers.        \\
  This operation {\em cannot} be a constructor,
  i.e., the patterns for rewriting should consider every case,
  and provide adequate rewriting.
  If all those fail, a run-time exception will be raised.
\end{itemize}

\newpage
\subsection{Behaviour Annotations}
\begin{itemize}
\item
  \verb/(*| lbc C_code |*)/      \\
  \verb/C_code/ is reproduced verbatim onto file
  \verb/lbc.hh/.		\\
  It is typically used to
  reference other files that provide functions and/or variables that
  are used in annotations.
\item
  \verb/(*| lbc C_code |*)/ \\
  This annotation may be used too at the end of the specification
  (i.e. after keyword \verb/endspec/).	\\
  The \verb/C_code/ is reproduced verbatim in file
  \verb/lbc.c/.

  It is typically used to provide in the same file spec\verb/.lot/
  some functions to be used from behaviour annotations.
  If it is cumbersome to have a separate spec\verb/.c/ file for holding the
  \verb/main()/ function,
  it may be placed in this annotation,
  making spec\verb/.lot/ self--contained.
\item
  \verb/(*| C C_statements |*)/ \\
  The annotation keyword \verb/C/ means {\em code}
  and applies to action denotations.   \\
  The C statements are executed just after the action denotation is
  involved in a successful rendez-vous.

  When there are several action denotations involved in a multiway
  rendez-vous,
  there may be different \verb/C/ annotations to perform.
  These are executed in any arbitrary order.
  \begin{verbatim}
    g?b: bool ?n: nat
      (*| C
          printf ("g ");
          printf ("!%s ",   kd_draw ($!1));
          printf ("!%s;\n", kd_draw ($!2));
      |*) ;
  \end{verbatim}
\item
  \verb/(*| delay C_expression |*)/      \\
  This applies to action denotations.   \\
  The value is any C expression that evaluates to an integer value.  \\
  The effect of this annotation is that the corresponding action
  denotation will not be offered before \verb/int/ seconds.	\\
  \centerline{
    \verb/(*| delay 10 |*) timeout !transmitter ;/
  }
\item
  \verb/(*| wait C_expression |*)/      \\
  This applies to action denotations.   \\
  This annotation implements busy wait:
  the \verb/C_expression/ is repeatedly evaluated until it returns
  true (i.e. $\not=0$),
  then the corresponding action denotation may be offered.
  Busy wait on a \verb/wait/ doesn't preclude other offers,
  that may occur or not.	\\
  \centerline{
    \verb/(*| wait DataReceived (stdin) |*) gate ?d: data ;/
  }
\item
  \verb/(*| default C_expression |*)/ \\
  This applies to experiment offers of type query (i.e. ?).     \\
  \verb/C_expression/ must evaluate to a {\em x\verb/datum/} value.

  When in a rendez-vous negotiation there is no ! offer available,
  a default may be provided.
  ! offers always take precedence.
  When there are several \verb/default/s,
  they are considered in an arbitrary order.

  \verb/default/, \verb/use/, and \verb/eval/ annotations
  may NOT apply simultaneously.
  For a default to be accepted, it must fulfill all the requirements,
  that is, all the predicates involved.	\\
  \centerline{
    \verb/gate ?d (*| default getdata() |*) : data [predicate]/
  }
\item
  \verb/(*| use C_expression |*)/ \\
  Identical to the \verb/default/ annotation above,
  but the {\em x\verb/datum/} value is imposed on the rendez-vous
  negotiation.
  It has the ``power'' of a !-experiment.

  \verb/default/, \verb/use/, and \verb/eval/ annotations
  may NOT apply simultaneously.
  For a default to be accepted, it must fulfill all the requirements,
  that is, all the predicates involved.	\\
  \centerline{
    \verb/keyboard ?d (*| use scandata(...) |*) : data [predicate]/
  }
\item
  \verb/(*| eval C_identifier |*)/ \\
  This applies to experiment offers of type query (i.e. ?).     \\
  \verb/C_identifier/ is a C function that stores a {\em x\verb/datum/}
  in \verb/r/ and returns true (i.e. $\not= 0$). \\
  \centerline{
    \verb/int C\_identifier (r) kdatum* r; { ... }/
  }
  \centerline{
    \verb/int C\_identifier (r) udatum* r; { ... }/
  }
  When in a rendez-vous negotiation there is no ! offer available,
  an \verb/eval()/ function may be provided.
  This function is repeatedly
 called , once each tree evaluation, until a valid value for
  negotiation is provided. If a false (i.e. $0$) is returned the
  negotiation is over.
  ! offers always take precedence.

  \verb/default/, \verb/use/, and \verb/eval/ annotations
  may NOT apply simultaneously.
  For a default to be accepted, it must fulfill all the requirements,
  that is, all the predicates involved.	\\
  \centerline{
    \verb/gate ?d (*| eval getdata |*) : data [predicate]/
  }
\item
  \verb/(*| priority C_expression |*)/ \\
  This  \verb/C_expression/ is a number for priority to synchronize
  the action that comes after it. The default priority is 0. The
  priority can be greater or lower than zero.

  If nothing else makes a difference,
  that is if the behaviour of the specification is not further
  imposed,
  priorities affect fair behaviour,
  forcing a selection.
  The action with the higher priority is selected.
  Thus, a possitive priority value implies a preferrence,
  while a negative value labels an undesired event.

  When several components are composed into a rendezvous (n-way),
  each syntactical offer may have a different priority,
  so we need an algebra to compose priority values.
  TOPO takes as the composition of two values the one which absolute
  value is furthest from zero.
  So possitive values pull harder and harder for an event to occur,
  while negative values pull harder and harder to avoid it.

  Some examples (where . stands for priority composition:	\\
  0 . 9 = 9	\\
  0 . 9 . 2 = 9	\\
  0 . -4 = -4	\\
  0 . -1 . -2 = -2	\\
  0 . 9 . -4 = 9	\\
  0 . -9 . 4 = -9


\item
  \verb/(*| if C_expression |*)/ \\
  This  \verb/C_expression/ acts as a guard.
  If it returns a false (i.e. $0$),
  the subsequent behaviour is replaced by STOP.
\end{itemize}

\newpage
\section{Limitations}
TOPO is able to generate executable code for a large part of LOTOS.
Nevertheless, there are a few limitations:
\begin{enumerate}
\item
  The functionality of the specification as a whole
  (as specified in the \verb/specification/ statement)
  must be \verb/noexit/.
\item
  Unguarded recursion in process instantiation may drive into a
  run-time overflow.
\item
  Rendez-vous may fail when no partner involved is providing any
  !-offer, or any acceptable \verb/default/ or \verb/eval/.
  That is, data for value negotiations must be explicit somehow.
\item
  The data types must be interpretable as a rewrite system.
  That is, equations may be used as patterns (LHS)
  that may be replaced by the right hand side (RHS).
  For this method to provide correct results,
  the system must be terminating
  (no infinite sequence of rewrites),
  and confluent
  (if two LHS apply simultaneously,
  the election of one or the other must terminate in the same normal
  form).
  These rewrite systems are said to be convergent.
\end{enumerate}

\newpage
\appendix
\section{Example}
This appendix shows a simple example.
In general,
implementing a LOTOS specification is far from a trivial task;
but simple animations may be run quite fast.

This examples covers several topics described in this document:
\begin{itemize}
\item
  Uses the following annotations:
    \verb/lexical/, \verb/name/, \verb/constructor/,
    \verb/nonconstructor/, \verb/lbc/, \verb/delay/, and \verb/C/.
\item
  Uses KAOS public function \verb/kd_draw()/.
\item
  Uses LBC public information \verb/$!#/.
\item
  Shows how to instantiate a specification.
\item
  Shows how to pass value parameters to an specification at
  instantiation time.
\item
  Shows how convert from C data types into \verb/kdatum/.
  The case shown is the conversion of an \verb/int/ value.
\item
  Shows how to share variables between C and LOTOS worlds.
  The case shown is an \verb/int/ variable called \verb/delay/:
  it is declared (and allocated) in \verb/pc.lot/,
  loaded in \verb/pc.c/,
  and used in \verb/pc.lot/,
\end{itemize}

The example shows the case of a producer and a consumer,
connected by means of two buffers
(or as a two slot buffer, as you prefer).

\begin{center}
\setlength{\unitlength}{1mm}
\begin{picture}(80,42)
  \put (10,30) {\framebox (20,10) {Producer}}
  \put (50,30) {\framebox (20,10) {Consumer}}
  \put (10,10) {\framebox (20,10) {Fast Buffer}}
  \put (50,10) {\framebox (20,10) {Slow Buffer}}

  \put (20,20) {\line (0,1) {10}}
  \put (60,20) {\line (0,1) {10}}
  \put (30,15) {\line (1,0) {20}}

  \put (20,25) {\circle*{2}}
  \put (60,25) {\circle*{2}}
  \put (40,15) {\circle*{2}}

  \put (17,25) {\makebox (0,0) [r] {send}}
  \put (63,25) {\makebox (0,0) [l] {recv}}
  \put (40,17) {\makebox (0,0) [b] {chan}}
\end{picture}
\end{center}

Both buffers are functionally identical.
LOTOS semantics do not make any difference between them.
But a \verb/delay/ annotation makes one of them to act slowly.
The delay is controlled from global variable \verb/delay/.

The producer is made random by the introduction of a \verb/delay/
annotation which value is taken from a call to a random number
generator \verb/rand(3)/.

\newpage
\small
\subsection{pc.lot}
\begin{verbatim}
specification producer_consumer (start: number) : noexit
(*| lbc int delay; |*)
  type Integers is
    sorts number
    opns
      0    (*| constructor |*)
           (*| name zero |*)      :                -> number
      succ (*| constructor |*)
           (*| lexical |*)        :         number -> number
      1    (*| nonconstructor |*) :                -> number
      _+_  (*| nonconstructor |*) : number, number -> number
    eqns
      forall x, y: number
      ofsort number
        1 = succ(0) ;
        x + succ(y) = succ(x + y) ;
        x + 0 = x ;
    endtype

behaviour
  hide send, recv, chan in
    (producer [send] (start) |[]| consumer [recv])
    |[send, recv]|
    (fast_buffer [send, chan] |[chan]| slow_buffer [chan, recv])

where
  process producer [send] (n: number): noexit:=
    (*| delay rand()/500000000 |*) send !n
      (*| C printf ("send %s\n", kd_draw ($!1)); |*) ;
    producer [send] (n + 1)
    endproc

  process consumer [recv]: noexit:=
    recv ?n: number (*| C printf ("recv %s\n", kd_draw ($!1)); |*) ;
    consumer [recv]
    endproc

  process fast_buffer [get, put]: noexit:=
    get ?n: number ;
    put !n ;
    fast_buffer [get, put]
    endproc

  process slow_buffer [get, put] : noexit:=
    get ?n: number ;
    (*| delay delay |*) put !n ;
    slow_buffer [get, put]
    endproc
endspec
\end{verbatim}

\newpage
\subsection{pc.c}
\begin{verbatim}
#include <stdio.h>
#include <lotos.hh>

extern int delay;

extern kdatum zero ();
extern kdatum succ ();

kdatum
int2kdatum (i)
     int i;
{
  kdatum result;

  result= zero ();
  while (i-- > 0)
    result= succ (result);
  return result;
}

main (argc, argv)
     int argc;
     char* argv[];
{
  kdatum spec_args[1];

  if (argc != 3) {
    fprintf (stderr, "usage: %s <delay> <start>\n", argv[0]);
    exit (1);
  }
  ldcinit ();
  delay= atoi (argv[1]);
  spec_args[0]= int2kdatum (atoi (argv[2]));
  lbcinit (1, spec_args);
  exit (sch ());
}
\end{verbatim}

\newpage
\small
\subsection{pc.ctx}
\begin{verbatim}
Library 
Language C
BehaviourName lbc
DataName ldc
BehaviourPieces 1
DataPieces 1
GladLibrary 
Makefile 
\end{verbatim}

%\newpage
\small
\subsection{makefile}
\begin{verbatim}
SPEC=pc

CFLAGS=-I$(TOPOINC)

OBJS=   lbc.o ldc.o $(SPEC).o

$(SPEC):        $(OBJS)
        $(CC) $(CFLAGS) -o $@ $(OBJS) -L$(TOPOLIB) -lotos -lkaos

lbc.o ldc.o:    ldc.hh
lbc.o:          lbc.hh

lbc.c lbc.hh:   $(SPEC).lot $(SPEC).ctx
        $(TOPOBIN)/topo $(SPEC) -verbose -behaviour

ldc.c ldc.hh:   $(SPEC).lot $(SPEC).ctx
        $(TOPOBIN)/topo $(SPEC) -verbose -data

clean tidy::
        rm -f *~ core topocore
        rm -f $(OBJS)
        rm -f $(SPEC).com

clean::
        $(TOPOBIN)/topo $(SPEC) -clean

tidy::
        rm -f $(SPEC)
        $(TOPOBIN)/topo $(SPEC) -tidy
\end{verbatim}

\newpage
\section{Annotations Syntax}
Annotations may only show up in a few places.
The following syntax definition covers those pieces of the standard
language that have been modified to allow for annotations.
The places where annotations may appear are marked by the production
\verb/executable_comment_list/.
The kind of annotations that may appear in a list are stated too.

At each place where annotations are allowed,
there may be several of them of the same class.
See the figures at the end to get a clear idea of allowed
combinations.

\begin{verbatim}
specification::=
  SPECIFICATION
  specification_identifier
  formal_parameter_list
  executable_comment_list       lbc, ldc, ldcinit
  data_type_definitions
  BEHAVIOUR
  definition_block
  ENDSPEC
  executable_comment_list       lbc, ldc
\end{verbatim}

\begin{verbatim}
sorts::=
  [ sort_id_comm + ',' ]
\end{verbatim}

\begin{verbatim}
sort_id_comm::=
  sort_identifier
  executable_comment_list       name, lexical, extern, free, nofree,
                                equal, draw, nodraw, parse, noparse
\end{verbatim}

\begin{verbatim}
operation_descriptor::=
  operation_identifier
  executable_comment_list       using, usingsort, name, lexical,
                                lexicalifpossible, internal,
                                extern, call, partial,
                                constructor, nonconstructor
\end{verbatim}

\begin{verbatim}
operation_descriptor::=
  '_' operation_identifier '_'
  executable_comment_list       extern, name, partial
\end{verbatim}

\begin{verbatim}
action_prefix_expression::=
  executable_comment_list       delay, priority, wait, if
  action_denotation ';'
  action_prefix
\end{verbatim}

\begin{verbatim}
action_denotation::=
  gate_identifier
  executable_comment_list       C
\end{verbatim}

\begin{verbatim}
action_denotation::=
  gate_identifier
  experiment_offer_list
  selection_predicate
  executable_comment_list       C
\end{verbatim}

\begin{verbatim}
action_denotation::=
  I
  executable_comment_list       C
\end{verbatim}

\begin{verbatim}
value_declaration_list::=
  [ mod_value_identifier + ',' ]
\end{verbatim}

\begin{verbatim}
mod_value_identifier::=
  value_identifier
  executable_comment_list       default, use, eval
\end{verbatim}

\begin{verbatim}
atomic_expression::=
  executable_comment_list       delay, priority, wait, if
  EXIT
  [ '(' _exit_entry_list ')' ]
\end{verbatim}

\begin{verbatim}
atomic_expression::=
  executable_comment_list       delay, priority, wait, if
  '(' behaviour_expression ')'
\end{verbatim}

\begin{verbatim}
process_instantiation::=
  executable_comment_list       delay, priority, wait, if
  process_identifier
  [ _actual_gate_list ]
  [ '(' _value_expression_list ')' ]
\end{verbatim}

\newpage

\begin{center}

  \psfig{figure=adexc.eps}

  \psfig{figure=defexc.eps}

  Syntax diagrams for allowed combinations of annotations.
\end{center}

\end{document}
