\documentstyle[11pt,fullpage]{article} 
\pagestyle{myheadings}
\markright{BACI C$- -$ User's Guide}

\begin{document}
\thispagestyle{empty}

\begin{center} 
{\bf USER'S GUIDE \\

                 Ben-Ari C$- -$ Compiler and Concurrent PCODE Interpreter \\

                              Bill Bynum/Tracy Camp \\

                      College of William and Mary/Colorado School of Mines\\
                      
                      \today }

                              
\end{center} 

\subsubsection*{1. Introduction}

     The purpose of this document is to provide a brief description of
the C$- -$ Ben-Ari Compiler and Concurrent PCODE Interpreter 
programs and a description of how to use them.  
The C$- -$ compiler first compiles the user's program
into an intermediate object code called PCODE, which the
interpreter then executes.
Like the Ben-Ari Pascal compiler, 
the C$- -$ compiler supports binary and counting semaphores and Hoare
monitors.
The interpreter  
simulates concurrent process
execution.


The Pascal version of the compiler and the interpreter were originally 
procedures in
a program written 
by M. Ben-Ari, based on the original
Pascal compiler by Niklaus Wirth.  The program source was included as
an appendix in Ben-Ari's book, ``Principles of Concurrent Programming''. 
The original version of the BACI compiler and interpreter
was created from that source
code and was hosted on a PRIME mainframe.  
After several modifications
and additions, this version was ported to a PC version in Turbo
Pascal, then to Sun Pascal, and to C. 
Finally, the compiler and interpreter were split into two separate 
programs.
Recently, the 
C$- -$ compiler was developed to compile source programs 
written in a restricted subset of C++ into PCODE executable by
the interpreter.
The syntax for the C$- -$ compiler
is explained below. 

\subsubsection*{2. C$- -$ Compiler Syntax} 

\begin{enumerate} 
\item  
As in C++, comments can be delimited with `\verb|/*|' and `\verb|*/|' or 
`\verb|//|'.

\item   There are no files other than standard input and output:
\verb|cout|, 
\verb|cin|, and 
\verb|endl| behave in C$- - $ BACI as in  standard C++.  
The main program must have one of the following forms: 
\begin{center} 
         \verb|int main ()|  \\
         \verb|void main ()| \\
         \verb|main ()|
\end{center}

\item   
The only simple C/C++  types available in C$- - $ BACI 
are {\tt int}, and {\tt char}.  
     There are also other
     types related to the control of concurrency; these will be
     discussed below.  

All variables must be declared at the beginning of the code block 
in which they appear.
In particular, the index variable of a \verb|for| loop cannot
be declared in the loop header, but instead must be declared
at the beginning of the block containing the \verb|for| loop. 

\item
     A {\tt string} type is supported.  To declare a string,
the length of the string must be specified.
The following declaration defines a string of length 20:
\begin{center} 
   {\tt string[20] string\_name; }
\end{center} 
The length specifier should be the number of characters
that the string should have
and should not include space for the termination byte.
The compiler takes care of reserving space for the
termination byte.
The length specifier must be either a literal constant
or a program constant.

The {\tt string}
keyword is used in the declaration of a function
for declaring a parameter of type \verb|string|:
\begin{center} 
   {\tt void proc(string formal\_parm) }
\end{center} 
This declaration asserts
that {\tt formal\_parm} is of type {\tt string[n]},
for some positive value of {\tt n}.
Parameters of type {\tt string} are passed by reference.
No check for string overrun is performed.

\begin{center}
{\bf Built-in String Handling Functions}
\end{center}
\begin{itemize}
\item
{\tt void stringCopy(string dest, string src);}\\
copies the {\tt src} string into the {\tt dest} string.
No check for string overrun is performed.
For example,
\begin{verbatim} 
                     string[20] x;
                        ...
                     stringCopy(x,"Hello, world!");
                     stringCopy(x,"");
\end{verbatim} 
will initialize the string \verb|x| to a well-known value.
The second \verb|stringCopy| resets the string \verb|x| 
to a zero-length string.

\item
{\tt void stringConcat(string dest, string src);}\\
concatenates the \verb|src| string to the end of the
\verb|dest|.
No check for string overrun is performed.

\item
{\tt int stringCompare(string x, string y);}\\
has the same semantics as the \verb|strcmp| function
from the C string library:  a positive number is
returned if 
string \verb|x| 
is lexicographically after the
string \verb|y|, 
zero is
returned if the strings are equal,
and a negative number is returned if
string \verb|x| 
is lexicographically before the
string \verb|y|. 

\item
{\tt int stringLength(string x);}\\
returns the length of the string \verb|x|, not including
the termination byte.

\item
{\tt int sscanf(string x, rawstring fmt,...);}\\
like the ``real'' \verb|sscanf|, scans the string
\verb|x| 
according to the format string \verb|fmt|,
storing the values scanned into the variables supplied
in the parameter list, and returns the number of items
scanned.
Only the \verb|%d|, \verb|%x|, and \verb|%s|
format specifiers of the real \verb|sscanf| are supported.
An additional format specifier \verb|%q| (quoted string),
unique to BACI, is supported.
For this specifier, all characters delimited by a pair
of double quotes (\verb|"|) will be scanned into
the corresponding string variable.  
When the \verb|%q| specifier is encountered in the format
string, 
if the next non-whitespace character of the string being
scanned is not a double quote, then the \verb|%q| scan fails,
and scanning of the string terminates.

The variables appearing after the format string are
reference variables (that is, the ampersand (\verb|&|)
is not required.

In the following example, the value of \verb|i| returned
by the \verb|sscanf| call will be 4, the value stored in
the variable \verb|j|
will be 202, the value stored in 
the string stored in string \verb|x| will be 
\verb|alongstring|, the value stored in the variable \verb|k|
will be \verb|0x3c03|, and the string 
stored in 
the string \verb|y| will 
be \verb|a long string|.
{\small
\begin{verbatim}
               string[50] x,y;
               int i,j,k;
               stringCopy(x,"202 alongstring 3c03 \"a long string\"");
               i = sscanf(x,"%d %s %x %q",j,x,k,y);
\end{verbatim}
}

\item
{\tt void sprintf(string x, rawstring fmt,...);}\\
like the ``real'' \verb|sprintf|, creates a string stored in the 
variable \verb|x|, using the format string \verb|fmt| and the
variables following the format string.

The 
\verb|%d|,
\verb|%o|,
\verb|%x|,
\verb|%X|,
\verb|%c|,
and
\verb|%s| format specifiers are supported, in the full
generality of the real \verb|sprintf|.
In addition, the \verb|%q| format specifier will insert
a doubly-quoted string into the output string.
The \verb|%q| format specifier is equivalent to the
\verb|\"%s\"| specifier.

For example, in the following code fragment
\begin{verbatim}
               string[80] x;
               string[15] y,z;

               stringCopy(y,"alongstring");
               stringCopy(z,"a long string");
               sprintf(x,".%12d. .%-20s. .%q. .%08X.",202,y,z,0x3c03);
\end{verbatim}
the string \verb|x| becomes
\begin{center}
{\small
\verb|.         202. .alongstring         . ."a long string". .00003C03.|
}
\end{center}


\end{itemize}

\item
Arrays of 
any valid type
are supported.
Array declaration follows the usual C syntax:
\begin{center} 
   {\tt element\_type arrayname[index1][index2][index3]...[indexN]; }
\end{center} 

\item  
The keyword {\tt typedef} is supported in C$- -$ BACI. For
example, to make the variable name {\tt length} synonym with {\tt int} 
\begin{center}
\verb|typedef int length;|
\end{center}

\item   
Constants ({\tt const}) of simple types are supported: 
\begin{center} 
{\tt const int m = 5; }
\end{center} 

\item
In the declaration of variables of
\verb|int| and \verb|char| types,
initializers are supported.
The value of the initializer must be a literal or program constant:
\begin{verbatim} 
                           const int m = 5;
                           int  j = m;
                           int  k = 3;
                           char c = 'a';
\end{verbatim} 


\item   
Procedures and functions are supported. 
Standard scope rules apply.  Recursion is supported. Parameter
declarations are pass-by-value or pass-by reference:
\begin{verbatim} 
            int afunc( int   a,     /* pass-by-value  */ 
                       int&  b  )   /* pass-by-reference */
\end{verbatim} 
Each program must have a \verb|main()| function of type \verb|int|
or \verb|void|, and this function must be the last function in
the source file.
Execution begins with a call to \verb|main()|.

\item   
The executable statements are {\tt if}-{\tt else}, 
{\tt switch}/{\tt case}, {\tt for}, 
{\tt while}, 
{\tt do-while}, 
{\tt break}, and 
{\tt continue}. 
The syntax of these 
statements are as in standard C/C++. Bracketing of code 
	 is standard, i.e., \verb|{ ... }|. 

\item 
Standard C/C++ file inclusion  is supported:
\begin{center} 
\verb|#include < ... >| \\
\verb|#include " ... "|
\end{center} 
Both styles of \verb|include| statement have the same semantics,
because there is no ``system'' include directory.

\end{enumerate} 

\subsubsection*{3. Concurrency Constructs} 

{\bf a. cobegin}: \\
A C$- -$ process is a \verb|void| function.
A list of processes to be run concurrently is enclosed in a
{\tt cobegin} block.  Such blocks cannot be nested and must appear
in the main program.  

\begin{verbatim} 
                      cobegin {
                           proc1(...); proc2(...); ... ; procN(...); 
                      }
\end{verbatim} 

The PCODE statements belonging to the listed procedures are
interleaved by the interpreter in an arbitrary, `random' order, so
that multiple executions of the same program containing a
{\tt cobegin} block will appear to be non-deterministic.  The main
program is suspended until all of the processes in the {\tt cobegin} 
block terminate, at which time execution of the main program resumes
at the statement following the ending of the block. \\
\par\medskip\noindent
{\bf b. semaphores:} \\
The interpreter has a predeclared {\tt semaphore} type.  
That is, a 
semaphore in C$- -$ is  a non-negative-valued {\tt int}
variable (see definition below) that can be accessed only in
restricted ways. 
\newcommand{\zero}{\verb|0|}
\newcommand{\one}{\verb|1|}
The binary semaphore, one that only assumes the
values \zero\ and \one, is supported 
by the {\tt binarysem} subtype of the 
{\tt semaphore} 
type.  
During compilation and execution, the compiler and interpreter
enforce the restrictions that a {\tt binarysem} variable can only have the
values \zero\ or \one\ and that {\tt semaphore} type can only be non-negative.

     Assignment to a {\tt semaphore} or {\tt binarysem} 
variable is allowed only when the variable is defined.
For example, either of the following declarations is
valid
\begin{verbatim} 
                   semaphore  s = 17;
                   binarysem  b = 0;
\end{verbatim}
The built-in procedure,
\begin{verbatim} 
                   initialsem( semaphore, integer_expression );
\end{verbatim}
is the only method available for initializing a semaphore of either
type a runtime.  In the call, 
\begin{center}
{\tt integer\_expression}
\end{center}
 can be any expression
that evaluates to  an integer and is valid for the semaphore type (non-
negative for a {\tt semaphore} type, \zero\ or \one\ 
for a {\tt binarysem} type).

     The procedures
\begin{verbatim} 
                   p( semaphore );  // or equivalently, wait( semaphore )
\end{verbatim}
and
\begin{verbatim}
                   v( semaphore );  // or equivalently, signal( semaphore )
\end{verbatim} 
are used by concurrently executing processes to synchronize their
actions.  These procedures provide the user with the only way to
change a semaphore's value.  The semantics of {\tt p} and {\tt v} 
are as follows:
\begin{itemize} 
\item {\tt p( sem );} \\
     If {\tt sem} $>$ 0, then decrement {\tt sem} by 1 and return,
allowing {\tt p}'s
caller to continue.  \\
If {\tt sem} = 0, then put {\tt p}'s caller to sleep.

\item {\tt v( sem );} \\
     If {\tt sem} = 0 and one or more processes are sleeping 
on {\tt sem}, then
awake one of these processes.  If no processes are waiting on {\tt sem},
then increment {\it sem} by one.  In any event, {\tt v}'s caller is allowed to
continue.  Some implementations of {\tt v} require that processes waiting on
a semaphore be awakened in FIFO order (queuing semaphores), 
but BACI 
conforms to Dijkstra's original proposal by randomly choosing which
process to re-awaken when a signal arrives.
\end{itemize}

\par\medskip\noindent
{\bf c.  monitors}: \\
     The monitor concept, as proposed by Hoare, is supported with some
restrictions.  A {\tt monitor} is a C$- -$ block, like a block defined by a
procedure or function, with some additional properties.  All
functions in the {\tt monitor} block are visible (that is,
are callable entry procedures) 
from the outside of the block, but the {\tt monitor} variables are
not accessible outside of the block and can only be accessed by the
{\tt monitor} functions.  In C$- -$,
a 
{\tt monitor} can be declared only at the outermost, global level.
Monitors can
not be nested.  
A 
\verb|monitor| 
can have an optional
\verb|init{}| block as its last block for initializing
the values of the 
\verb|monitor|'s
variables.
This code is run when the main program is started.


     Only one procedure or function of the {\tt monitor} block can execute
at any one time.  This feature makes it possible to use monitors to
implement mutual exclusion. Use of monitors to control concurrency is
advantageous, because all of the code controlling concurrency is
located in the monitor and not distributed widely across callers, as
is the case when semaphores  are used.
     
     Three constructs are used by the procedures and functions of a
{\tt monitor} to control concurrency:  {\tt condition} 
variables, {\tt waitc} (wait on a
condition), and {\tt signalc} (signal a condition).

     A {\tt condition} variable can only be defined in a {\tt
monitor},  and thus,
can only be accessed by the {\tt monitor}'s processes.  A {\tt condition} never
actually `has' a value; it is somewhere to wait or something to
signal.  A {\tt monitor} process can wait for a {\tt condition} 
to hold or signal
that a given {\tt condition} now holds through the {\tt waitc} and 
{\tt signalc} calls.

     {\tt waitc} and {\tt signalc} 
calls have the following syntax and semantics:
\begin{itemize} 
\item {\tt void waitc( condition cond, int prio );} \\
     The {\tt monitor} process (and hence, also the outside process calling
the {\tt monitor} process) is blocked and assigned the priority {\tt prio} for
being re-awakened (see {\tt signalc} below). Note that this blocking action
allows some other {\tt monitor} process to execute, if one is ready. 

\item {\tt void waitc( condition cond );} \\
     This call has the same semantics as the {\tt waitc} call above, but the
wait is assigned a default priority of 10.

\item {\tt void signalc( condition cond );} \\
     Wake some process waiting on {\tt cond} with the smallest (highest)
priority; otherwise, do nothing.  Note this is quite unlike the
semaphore {\tt v} or {\tt signal}, 
because {\tt signalc} is a no-op if no one is
waiting, whereas {\tt v( sem )} increments 
{\tt sem} if no one is waiting, thus
``remembering'' the action when future {\tt p( sem )}'s occur.
\end{itemize}

     The priority scheme can be used to implement a FIFO discipline in
re-awakening waiters.  If each {\tt monitor} process increments a {\tt monitor}
variable associated with the current priority assigned to a {\tt condition},
then successive {\tt signalc}'s to the {\tt condition} will awaken the sleeping
processes in a FIFO order.

The C$- -$ compiler provides an \verb|int| function 
{\tt empty( cond )} that returns \verb|1| if there are no processes waiting 
in the queue of the condition {\tt cond} and
\verb|0| otherwise. \\

     {\bf Immediate Resumption Requirement}:  This is the requirement that a
process waiting on a condition that has just been signaled should
have priority in re-entering the {\tt monitor} over new calls to {\tt monitor}
processes (those wanting to enter ``from the top'').  The requirement
rests on the assumption that the {\tt condition} that has just been
signaled has more ``urgent'' business to perform than a new entry into
the {\tt monitor}.  The Immediate Resumption Requirement is implemented in
BACI by suspending the signaler of a condition and
picking (at random) one of the waiters on the condition with the
appropriate priority to run.  Because of this, {\tt monitor} procedures that
{\tt signalc} a condition typically do so as their last instruction.

The following example of an implementation of a general semaphore
with a monitor illustrates the monitor syntax:
{\footnotesize
\begin{verbatim}
                              monitor monSemaphore {

                                 int semvalue;
                                 condition notbusy;

                                 void monP()
                                 {
                                    if (!semvalue) 
                                       waitc(notbusy);
                                    else
                                       semvalue--;
                                 }

                                 void monV()
                                 {
                                    if (empty(notbusy))
                                       semvalue++;
                                    else 
                                       signalc(notbusy);
                                 }

                                 init{ semvalue = 1; }

                              }  // end of monSemaphore monitor
\end{verbatim}
}
\par\medskip\noindent
{\bf d. Other Concurrency Constructs:} \\
BACI C$- -$ provides several low-level concurrency constructs that can
be used to create new concurrency control primitives:
\begin{itemize}
\item {\tt atomic} keyword \\
If a function is defined as \verb|atomic|, then the function is 
{\em non-preemptible}.  
The interpreter will not interrupt 
an \verb|atomic| function with a context switch.
This provides the user with a method for defining new primitives.
The following program illustrates how a 
\verb|test_and_set| primitive can be defined and used 
to enforce mutual exclusion:
{\footnotesize
\begin{verbatim}
            atomic int test_and_set(int& target) {
               int u;
               u = target;
               target = 1;
               return u;
            }

            int lock = 0;

            void proc(int id) {
               int i = 0;
               while(i < 10) {
                  while (test_and_set(lock)) /* wait */ ;
                  cout << id;
                  lock = 0;
                  i++;
               }
            }

            main() {
               cobegin { proc(1); proc(2); proc(3); }
            }
\end{verbatim}
}

\item {\tt void suspend( void );}\\
\verb|suspend()| puts the calling thread to sleep.

\item {\tt void revive( int process\_number );}\\
This function revives the process with the given number. 

\item {\tt int which\_proc( void ); } \\
This function returns the process number of the current thread.

\item {\tt int random( int range ); } \\
This function returns a ``randomly chosen'' integer between
\verb|0| and \verb|range - 1|, inclusive.
It uses a different random number generator stream than the
one used by the interpreter; that is, \verb|random()| calls
do not affect interpreter execution.
\end{itemize}

These functions
can be used to create a ``fair'' (FIFO) queued semaphore.
The code to accomplish this is beyond the scope of this
user's guide.

\subsubsection*{4. Using the Ben-Ari C$- -$ Compiler and PCODE Interpreter} 

There are two steps to executing a program in BACI. 
\begin{enumerate}
\item Compile a ``\verb|.cm|'' file to obtain a ``\verb|.pco|'' file.\\ 
Usage:\quad \verb|bacc [optional_flags]  source_filename| \\
Optional flags:    
\begin{verbatim} 
         -h  show this help
         -c  make a .pob object file for subsequent linking
\end{verbatim} 
The name of the source file is required.  If missing, you
will be prompted for it.  The file suffix ``\verb|.cm|'' will
be appended if you don't supply it.

\item Interpret a ``\verb|.pco|'' file to execute the program \\
Usage:\quad   \verb|baininterp [optional_flags]  pcode_filename| \\
Optional flags: 
\begin{verbatim} 
         -d  enter the debugger, single step, set breakpoints
         -e  show the activation record (AR) on entry to each process
         -x  show the AR on exit from each process
         -t  announce process termination
         -h  show this help
         -p  show PCODE instructions as they are executed
\end{verbatim} 
The name of the PCODE file is required.  If missing, you
will be prompted for it.  
The file suffix ``\verb|.pco|'' will
be appended to the filename you give.
\end{enumerate}

It is not necessary to recompile the
source file each time that you execute the \verb|.pco| file with
\verb|bainterp|.

There is a shell script, \verb|baccint|, that will call
the compiler and then call the interpreter for you.
It passes the options that you give it (see above) along to the interpreter.

\subsubsection*{5. Sample program and output} 

     The following listing was produced by the C $- - $ Ben-Ari compiler. 
The number to the right of the line number is the PCODE offset of the
instruction that begins that line. The Ben-Ari compiler creates this
listing from the file ``\verb|incremen.cm|''. 
The listing is placed in the file ``\verb|incremen.lst|''.  
An ``\verb|incremen.pco|'' file is also  created; this file 
is used by the interpreter. 

\vspace*{0.1in}

{\footnotesize
\begin{verbatim}
BACI System: C-- to PCODE Compiler, 10:31  21 Oct 1997
Source file: incremen.cm  Fri Sep  8 16:51:00 1995
 line  pc
   1    0  const int m = 5;
   2    0  int n;
   3    0  
   4    0  void incr(char id)
   5    0  {
   6    0     int i;
   7    0  
   8    0     for(i = 1; i <= m; i = i + 1)
   9   14     {
  10   14         n = n + 1;
  11   19         cout << id << "  n =" <<  n << "  i =";
  12   25         cout << i << " " << id << endl;
  13   31     }
  14   32  }
  15   33  
  16   33  main()
  17   34  {
  18   34     n = 0;
  19   37     cobegin
  20   38     {
  21   38        incr( 'A'); incr( 'B' ); incr('C');
  22   50     }
  23   51     cout << "The sum is " <<  n << endl;
  24   55  }
\end{verbatim}
}

     The following listing was produced by the Ben-Ari interpreter. 
The interpreter executes the program that was compiled into the
file ``\verb|incremen.pco|''. 

\vspace*{0.1in}
{\footnotesize
\begin{verbatim}
Source file: incremen.cm  Wed Oct 22 21:18:02 1997
Executing PCODE ...
C  n =1  i =A  n =1 C2  i =
1 A
C  n =4  i =2 C
B  n =A  n =5  i =24 A
  i =1 B
AC  n =  n =6  i =3 C6  i =3
A
C  n =7  i =4 C
B  n =9  i =2 BA  n =8
  i =4 A
C  n =8  i =5 A  n =9C
  i =5 A
B  n =10  i =3 B
B  n =11  i =4 B
B  n =12  i =5 B
The sum is 12

\end{verbatim}
}
\end{document}

%
%  $Log: cmimi.tex,v $
%  Revision 1.4  1999/08/31 16:31:56  bynum
%  change Tracy's school to Mines
%
%  Revision 1.3  1998/11/27 12:08:58  bynum
%  change valid array type, file suffix wordings
%
%  Revision 1.2  1998/11/02 18:13:27  bynum
%  update to 11/2/98 version of C--
%
% Revision 1.1  1997/07/09  16:35:54  bynum
% Initial revision
%
%

