% from 20.3.1989 hk, version 0.03
% revised 5.11.1989 hk, version 0.30
% language part 4.1.1990 hk
% corrections by haible 25.9.90
% revised language, without specification component 27.2.91 hk
% small letter key words 5.11.95 hk

%\setcounter{chapter}{2}
\chapter{The MAS Language}

\label{lang.chap}
This chapter contains the MAS language description. 
Besides the lexical and syntactical constructs it gives 
information on conventions, program interpretation 
and input / output facilities.
The specification component is discussed 
separately in chapter \ref{spec.chap}.
It does not contain a description of the 
algebraic data structures and functions.

The MAS language is only a 'cover' for the MAS LISP.
The language parser can be switched of and 
programs in pure LISP syntax can be entered as well.
Moreover some MAS facilities are only 
accessible in LISP mode. Therefore also
some LISP constructs are discussed in this chapter.
The reader not interested in them may skip such 
parts during a first reading.
{\small Such parts are indicated by small letter type style.}

The initial language\index{language} definition
was the PL/0\index{PL/0} language
as described in N. Wirth's book "Compilerbau" \cite{Wirth85b}.
This definition was extended to allow procedures with 
parameters and several new declarations where provided.
Some polishing was done to allow the interactive\index{interactive}
use of the parser\index{parser}, e.g. empty programs are accepted.

In the following sections we discuss 
first the lexical conventions and then 
the language syntax.


\section{Lexical Conventions}

The 'atomic' constituents of the language are characters and
tokens (character sequences with special meaning).
\index{lexical conventions}

\subsection{Character Set}

The character set of MAS is a subset of the ASCII character set.
\index{character set}
It consists of the 
\begin{deflist}{letter}
\item[digits] \verb/0123456789/
\item[letters] \verb/aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ/
\item[others] \verb*0.,=+-*/$() !"#%&':;<>?@[\]^_`{}|~0
\end{deflist}
\index{digit}\index{letter}\index{ASCII}
The number of characters is denoted by $\chi$ ($=95$ here).

\subsection{Tokens}

Lexical tokens of the language are:
\index{token}
\begin{quote}
       \verb/#  <  >  =  <=  >=  <>/  \\
       \verb.+  -  *  /  %. \\ 
       \verb/(  )  ,  .  ;  : { }/ \\
       \verb/-> => :=/ \\ 
       \verb/keyword  number  identifier/ \\
       \verb/string  comment/
\end{quote}
\index{\verb/#/}\index{\verb/</}\index{\verb/>/}
\index{\verb/<=/}\index{\verb/>=/}\index{\verb/<>/}
\index{\verb/+/}\index{\verb/-/}\index{\verb/=>/}
\index{\verb/*/}\index{\verb./.}\index{\verb/%/}
\index{\verb/(/}\index{\verb/)/}\index{\verb/,/}
\index{\verb/./}\index{\verb/;/}\index{\verb/:/}
\index{\verb/{}/}
\index{\verb/->/}\index{\verb/=/}%----\index{\verb/:=/}
\index{number}\index{keyword}\index{identifier}
\index{string}\index{comment}

Characters not contained in this list of tokens 
may only appear in strings and comments.

The keywords are:
\index{keyword}
\begin{quote}
      NOT, AND, OR, \\
      IF, THEN, ELSE, END, \\
      WHILE, DO, TO, REPEAT, UNTIL, \\
      PROCEDURE, BEGIN, EXPOSE, \\
      SPECIFICATION, IMPLEMENTATION, MODEL, AXIOMS, \\
      SORT, VAR, IMPORT, SIGNATURE, MAP, RULE, WHEN, \\
      not, and, or, \\
      if, then, else, end, \\
      while, do, to, repeat, until, \\
      procedure, begin, expose, \\
      specification, implementation, model, axioms, \\
      sort, var, import, signature, map, rule, when. 
\end{quote}
\index{NOT! keyword}\index{AND! keyword}\index{OR! keyword}
\index{IF! keyword}\index{THEN! keyword}\index{ELSE! keyword}
\index{END! keyword}
\index{WHILE! keyword}\index{DO! keyword}\index{REPEAT! keyword}
\index{UNTIL! keyword}
\index{PROCEDURE !keyword}\index{BEGIN! keyword}
\index{SPECIFICATION! keyword}\index{IMPLEMENTATION! keyword}
\index{MODEL! keyword}\index{AXIOMS! keyword}\index{EXPOSE! keyword}
\index{VAR! keyword}\index{SORT! keyword}\index{MAP! keyword}
\index{RULE! keyword}
\index{SIGNATURE! keyword}\index{IMPORT! keyword}\index{WHEN! keyword}

The meanings of most of the tokens and keywords 
should be 'as expected' and are discussed later. 
At this place we will only say some words on
numbers, identifiers, strings and comments.


\subsection{Numbers}

Numbers may be only so called $\beta$--integers. 
\index{number}
The set of $\beta$--integers is defined as:
\begin{displaymath} 
{\cal B} = \{ x \in {\bf Z} \vert -\beta < x < \beta \},
\end{displaymath} 
where {\bf Z} denotes the set of integral numbers.

{\small
The magnitude of $\beta$ depends on the
implementation of MAS on the actual computer.
Precisely $\beta$ is defined as a power of $2$ 
such that: 
\begin{displaymath} 
       \chi < \beta \mbox{ and }
       4 \beta \leq \gamma,
\end{displaymath} 
where $\chi$ denotes the number of characters and
$\gamma$ is the least number such that for all, 
representable integral numbers $y$: $\vert y \vert \le \gamma$.
On 32 bit computers $\gamma = 2^{31}$ ($32$ minus one sign bit). 
Some basic constants and ranges are summarized in 
table \ref{tabCR}.
}

Commonly $\beta = 2^{29} = 536870912$.
$\beta$--integers are also called {\bf atoms}.\index{atom}

\begin{table}
\begin{center}
\begin{tabular}{|l|c|l|}
\hline
Name   & Definition & Value \\
\hline
$\gamma$          & integer size          & $2^{31} = 2 147 483 648 $ \\
$\beta$           & $4 \beta \leq \gamma$ & $2^{29} =   536 870 912 $ \\
$\gamma$--integer & $\{ n \in {\bf Z} \mid -\gamma < n < \gamma \}$ & \\
$\beta$--integer  & $\{ n \in {\bf Z} \mid -\beta < n < \beta \}$ & \\
$\nu$             & number of cells       & run time dependent \\
atoms             & $\beta$--integers     & \\
pointers          & $\{ n \in {\bf Z} \mid
                    \beta \leq n \leq \beta+(8 \nu) \}$ &\\
empty list        & $\beta$               & \\
SIL               & $\beta$               & \\
NIL               & $\beta$               & \\
\hline
\end{tabular}
\end{center}
\label{tabCR}
\caption{Constants and Ranges}
\end{table}

Other kinds of numbers such as floating point numbers,
arbitrary precision integral numbers, rational numbers etc.
are provided by library modules. 
These modules also supply read / parse 
and write / pretty print routines for the respective data types.


\subsection{Identifiers}

Identifiers are used as names of variables and names of 
procedures. 
\index{identifier}
The character sequence of an identifier
must start with a letter and may be 
followed by digits and letters.
Identifiers are case sensitive, that means upper case
and lower case letters are distinct.
The length of identifiers is restricted by the 
requirement that they must fit on one input line.

Example: NIL, p123, AL9, XSH, AlongName.

\subsubsection{Naming Conventions}

Identifier names from the ALDES / SAC--2 system
follow the so called 'Implementation ALDES' naming
scheme. However in comments we have already introduced 
upper case and lower case letters according to the
'Publication ALDES' naming scheme. 
So it is useful to know the transliteration between
both conventions.
\index{transliteration}
The transliterations are summarized in table \ref{tabTS}.
Several ornaments are transliterated in clockwise order.
\index{identifier}\index{symbol}\index{variable}

\begin{table}[thbp] %-----------------------------
\begin{center}
\begin{tabular}{|c|c|l|}
\hline
Publication ALDES   & Implementation ALDES & Meaning \\
\hline
$a, b$              & AL, BL               & lower case \\
$A', B'$            & AP, BP               & prime \\
$A^{*}, B^{*}$      & AS, BS               & star \\
$\bar{A}, \bar{B}$  & AB, BB               & bar \\
$\hat{A}, \hat{B}$  & AH, BH               & hat \\
$A_0,B_1$           & A0, B1               & subscript \\
$\bar{a}'_0$        & ALBP0                & clockwise \\
\hline
\end{tabular}
\end{center}
\label{tabTS}
\caption{Transliteration Scheme}
\end{table}

Procedure and variable names from the ALDES / SAC--2 system
are at most 6 characters long and follow certain 
further conventions. The first letters identify the 
data structure and the following letters are chosen 
according to the meaning of the identifier.

Example:
\begin{deflist}{DIRPR}
\item[IPROD]  Integer Product 
\item[MPPROD] Modular Polynomial Product 
\item[DIRPPR] Distributive Rational Polynomial Product
\end{deflist}

\subsection{Strings}

Character sequences enclosed in double or single quotes
are called strings.
\index{string}\index{quote character}
Within the quotes any character from the character set
may appear. Quotes itself can be part of a string, if
they are written twice.
\index{\verb/"/}\index{\verb/'/}

Example:
\begin{quote}
       \verb/"this is a string"/ denotes the string
       \verb/this is a string/, \\
       \verb/"'"/ denotes the string \verb/'/, \\
       \verb/'"'/ denotes the string \verb/"/, \\
       \verb/"x'7""'"/ denotes the string \verb/x'7"'/
\end{quote} 

Strings are internally represented as lists of numbers 
($\beta$--integers). So all list operations are applicable to
strings, like concatenating, reversing.
 

\subsection{Comments}

Comments are sequences of characters enclosed in
\verb/(*/ and \verb/*)/.
Comments may be nested, that means the comment character 
sequence may contain {\em pairs} of \verb/(*/, \verb/*)/.
\index{comment}\index{\verb/(*/}\index{\verb/*)/}

Comments can appear everywhere except in other tokens.


\subsection{Blanks}

Blanks can appear everywhere except in 
numbers, identifiers, keywords or two letter tokens. 
\index{blank}
Blanks must be used in some cases to separate keywords.
So \verb/ENDEND/ would mean the identifier ENDEND and not two
END keywords.

Characters in input lines which do not belong to 
the MAS character set are converted to blanks.
ASCII characters like CR (return), LF (line--feed),
EOL (end--of--line) are {\em ignored} during input form
data sets. 


\section{Syntax}

In this section we discuss the MAS language syntax 
and the meaning of the language constructs.
First we give the complete syntax diagram and the 
list of syntax errors. Then we will concentrate 
the description on the procedural aspects of the 
MAS language. The MAS type system and generic function support
will be discussed later in a separate section.


\subsection{Syntax Diagram}

The syntax\index{syntax} definition is given in extended BNF\index{EBNF}
notation. That means
\verb/name/ denotes syntactic entities,
\verb/{}/ denotes (possibly empty) sequences,
\verb/()/ denotes required entities,
\verb/|/ denotes case selection and
\verb/[]/ denotes optional cases. 
Terminal symbols are enclosed in double quotes
and productions are denoted by \verb/=/. 
The syntax diagram is listed in table \ref{tabSD}.

\begin{table}
\begin{center}
\begin{verbatim}
program      = block"."
block        = { "VAR" identlist  ":" ident [string] ";"
               | "PROCEDURE" ident ["( "[identlist]
                                   [";" "VAR" identlist] ")"]
                             [":" ident]";" block ident ";"
               }
               statement
statement    = [ident ":=" listexpr |
               ident [ "(" [actualparms] ")" ] |
               "RETURN" [ "(" [ expression ] ")" ]
               "BEGIN" statementseq "END" |
               "IF" condition "THEN" statementseq 
                             ["ELSE" statementseq] "END" |
               "WHILE" condition "DO" statementseq "END" |
               "REPEAT" statementseq "UNTIL" condition ]
listexpr     = "{" expression {"," expression} "}" | expression
identlist    = ident {"," ident}
actualparms  = listexpr {"," listexpr}
statementseq = statement {";" statement}
condition    = "NOT" condition |
               "(" condition ")" ("AND"|"OR") "(" condition ")" 
               expression ("="|"#"|"<"|"<="|">"|">=") expression
expression   = ["+"|"-"] term {("+"|"-") term}
term         = power {("*"|"/"|"%") power}
power        = factor [ ("^"|"**") number ]
factor       = ident ["("[actualparms]")"] |
               number | string [ ":" typeexpr ] |
               "(" expression ")"
string       = ('"' {character} '"' | "'" {character} "'")
ident        = letter {letter|digit}
number       = digit {digit}
\end{verbatim}
\end{center}
\label{tabSD}\index{syntax}\index{syntax! diagram}
\caption{MAS Syntax Diagram}
\end{table}

Observe, that a program is a (possibly empty) sequence of 
declarations, followed by a (possibly empty) statement
followed by a period.
\index{program}
A statement can be an assignment, a procedure call or
a IF--, WHILE--, REPEAT-- or BEGIN--statement.
Declarations are VAR and PROCEDURE. 
The syntax of the language constructs for specifications 
is discussed in chapter \ref{spec.chap}. 

The semantics of the statements are discussed next, but
let us first mention the syntax errors and syntax warnings 
detected by the parser
(see tables \ref{tabSE} and \ref{tabSW}).
\index{syntax! error}
\index{syntax! warning}

\begin{table}
\begin{center}
\begin{tabular}{rl}
           1  & \verb/=/ expected \\ 
           2  & type declaration expected \\ 
           4  & identifier expected \\ 
           5  & \verb/;/ or \verb/,/ expected \\ 
           6  & expression expected \\ 
           7  & \verb/)/ expected \\ 
           8  & factor expected \\ 
           9  & \verb/./ expected \\ 
          10  & assignment expected \\ 
          13  & \verb/:=/ or \verb/(/ expected \\ 
          14  & statement expected \\ 
          15  & \verb/:/ expected \\ 
          16  & \verb/THEN/ expected \\ 
          17  & \verb/;/ or \verb/END/ expected \\ 
          18  & \verb/DO/ expected \\ 
          20  & relation expected \\ 
          21  & \verb/,/ or \verb/)/ expected \\
          22  & \verb/->/ expected \\
          23  & \verb/(/ or identifier expected \\ 
          24  & \verb/(/ expected \\ 
          25  & condition expected \\ 
          26  & number expected \\ 
          27  & \verb/,/ or \verb/)/ or \verb/;/ expected \\ 
          28  & \verb/;/ expected \\ 
          29  & \verb/END/ or \verb/;/ expected \\ 
          30  & \verb/,/ or \verb/]/ expected \\ 
          31  & \verb./. expected \\ 
          32  & \verb/==/ expected \\ 
          33  & \verb/END/ or \verb/;/ or \verb/BEGIN/ expected \\
          34  & \verb/,/ or \verb/{/ expected \\
          35  & \verb/TO/ expected
\end{tabular}
\end{center}
\label{tabSE}\index{syntax! error}\index{error}
\caption{Syntax Error Messages}
\end{table}

\begin{table}
\begin{center}
\begin{tabular}{rl}
           1  & identifier expected \\
           2  & algorithm name expected \\
\end{tabular}
\caption{Syntax Warning Messages}
\label{tabSW}\index{syntax! warning}\index{warning}
\end{center}
\end{table}

If a syntax error is detected one of the error messages is
displayed followed by the actual input line where the last
character read is underscored. However this last character
is one character and one lexical token to far. That means 
the syntax error is caused by one token behind.

Error repair is limited to skipping tokens until 
something meaningful is found.

In case syntax errors are detected, the execution of the program 
is totally suppressed, that means no executable code is generated.
If a syntax warning is given execution proceeds.


\subsection{Expressions}

Expressions are built from numbers, strings, identifiers and
function calls. Mathematical operators defined in the 
MAS language are only valid on numbers ($\beta$--integers),
variables having a number as value or function calls with
a number as return value 
or on generic items (defined in chapter \ref{spec.chap}.
Variables are bound to values by means of the assignment 
statement, which is discussed later.

So expressions are sums or differences of terms:
\begin{verbatim}
       expression = ["+"|"-"] term {("+"|"-") term}
\end{verbatim}
\index{expression}
The operators \verb/+/ and \verb/-/ correspond to
the LISP functions \verb/ADD/ and \verb/SUB/ 
or to the generic functions \verb/SUM/, \verb/NEG/ 
and \verb/DIF/.

Terms are themselves products, quotients or remainders 
of powers:
\begin{verbatim}
       term = power {("*"|"/"|"%") power}
\end{verbatim}
\index{term}
The operators \verb/*/, \verb./. and \verb/%/ correspond to
the LISP functions \verb/MUL/, \verb/QUOT/ and \verb/REM/ 
or to the generic functions \verb/PROD/ and \verb/Q/.

{\bf Note:} From the syntax definition follows, that 
'\verb/*/', '\verb./.' and '\verb/%/' have precedence
over '\verb/+/' and '\verb/-/'.

Powers are factors with an optional number as exponent.
\begin{verbatim}
       power = factor [ ("^"|"**") number ]
\end{verbatim}
\index{power}
The operators \verb/+/ and \verb/-/ correspond to
the LISP function \verb/POW/
or to the generic function \verb/EXP/.

Factors are identifiers, function calls, numbers, strings
or expressions enclosed in parenthesis.
\begin{verbatim}
       factor = ident ["("[actualparms]")"] |
                number | 
                string [ ":" typeexpr ] |
                "(" expression ")"
\end{verbatim}
\index{factor}
Strings can be accompanied by type information. 
This is discussed in chapter \ref{spec.chap}.

List expressions are sequences of expressions enclosed by 
curly braces or expressions.
\begin{verbatim}
       listexpr = "{" expression {"," expression} "}" | expression
\end{verbatim}
\index{list expression}\index{listexpr}

Function calls can be supplied by actual parameters which
are sequences of list expressions:
\begin{verbatim}
       actualparms = listexpr {"," listexpr}
\end{verbatim}
\index{actual parameter}\index{parameter}
\index{variable}\index{function}

Note, that function calls are distinguished from 
variables (identifiers) only by syntax. 
Function names {\bf must} be specified with
parenthesis, even if no arguments are supplied.
Names without parenthesis are considered to be
variable names.

Example:
\begin{quote}
       \verb/name/         = variable, \\
       \verb/name()/       = function call without argument, \\
       \verb/name(1)/      = function call with argument '1', \\
       \verb/name1(name2)/ = function call with variable as argument.
\end{quote}


\subsubsection{S--expressions}

We include some information on LISP. This may be skipped during 
a first reading. 

{\small
The main LISP language construct is the so called 
S--expression or symbolic expression.
S--expressions are lists of objects, where the 
first object evaluates to a function symbol. 
For example the S--expression corresponding to 
the MAS expression \verb/2+3/ is the list \verb/(ADD 2 3)/.
The translation scheme between variables and functions 
in MAS and in LISP is the following:
\begin{verbatim}
       MAS expression          S-expression
       name                    name
       name()                  (name)
       name(1)                 (name 1)
       name1(name2)            (name1 name2)
\end{verbatim}
}


\subsection{Conditions} 

Two expressions combined by an relational operator 
are a condition. Further two conditions can be
combined by AND or OR, or a condition can be negated by NOT:
\begin{verbatim}
 condition = "NOT" condition |
             "(" condition ")" ("AND"|"OR") "(" condition ")" |
             expression ("="|"#"|"<>"|"<"|"<="|">"|">=") expression
\end{verbatim}
The hash character (\verb/#/) denotes 'not equal'. 
\index{condition}
The LISP functions corresponding to the relational operators
(in the same sequence as above are):
\verb/EQ/, \verb/NE/, \verb/NE/, \verb/LT/, 
\verb/LEQ/, \verb/GT/ and \verb/GEQ/.
Conditions evaluate to {\bf true} or {\bf false} depending
on the expressions and the relational operators.

How are {\bf true} and {\bf false} defined ?
The are at least two possibilities:
\begin{enumerate}
\item LISP like: \\
      In LISP systems usually {\bf false} is defined to
      be NIL, and every thing which is not NIL is considered
      to be {\bf true}.
      There is additionally a variable \verb/T/ to denote {\bf true}.
\item ALDES / SAC--2 like: \\
      {\bf false} is defined to be \verb/0/ (zero) and
      {\bf true} is defined to be \verb/1/ (one).
      In the implementation of ALDES it is however also
      assumed, that everything $\neq$ \verb/0/ is 
      considered to be {\bf true}. 
\end{enumerate}

In MAS LISP we have implemented the first variant.
But the ALDES / SAC--2 boolean routines return
\verb/0/ or \verb/1/, so some care is needed 
to obtain the right result from the evaluation of the
condition.
 
However the syntax of the MAS language does not
allow a function call as condition.
So one is forced to write a condition with relational
operator. Then one can decide to compare the 
function value against \verb/0/ or \verb/NIL/ or what else.


\section{Statements}

Statements are assignment, procedure call, return,
begin, if, while and repeat:
\begin{verbatim}
       statement = [ assignment | procedurecall |
                     beginend | return |
                     if | while | repeat ]
\end{verbatim}
Observe that a statement can be empty.
\index{statement}


\subsection{Assignment}

The assignment statement has the following syntax:
\begin{verbatim}
       ident ":=" listexpr
\end{verbatim}
\index{assignment}

The expression respectively the list expression is evaluated a
nd the result is bound to the variable named 'ident'.
It is not required to declare variables before they are used
in an assignment statement.
However variables with type information 
must be defined with a VAR statement.

Example:
\begin{quote}
      \verb/x:=4*7+3-29*5./ evaluates to \verb/-114/.
\end{quote}
{\small
The corresponding S--expression is:
\begin{verbatim}
      (ASSIGN x (SUB (ADD (MUL 4 7) 3) (MUL 29 5)))
\end{verbatim}
where \verb/ASSIGN/ denotes the LISP assignment function.
In this case \verb/ASSIGN/ is equivalent 
to the LISP \verb/SETQ/ 
function which might be more familiar. 
}

\begin{quote}
      \verb/y:=x*x./ evaluates to \verb/12996/.
\end{quote}
{\small
The corresponding S--expression is:
\begin{verbatim}
      (ASSIGN y (MUL x x))
\end{verbatim}
}


\subsection{Procedure Call}

A procedure call has the following syntax:
\begin{verbatim}
       ident [ "(" [actualparms] ")" ] 
\end{verbatim}
\index{procedure! call}
\index{actual parameter}\index{parameter}
\index{variable}
The actual parameters can be expressions as described 
in the section on MAS expressions.
If no parameters are required, then the parenthesis can 
be omitted.
Example:
\begin{quote}
      \verb/ADD(1,3)./ evaluates to \verb/4/.
\end{quote}

{\small
The corresponding S--expression is:
\begin{verbatim}
      (ADD 1 3)
\end{verbatim}
Contrary to other LISP systems, but closer to Modula--2 syntax, 
identifiers as statements are supposed to be 
procedure calls and not variable names.
Schematically we have:
\begin{verbatim}
       MAS statement           S-expression
       name.                   (name)
       name().                 (name)
       name(2).                (name 2)
\end{verbatim}
By this translation scheme we obtain several equivalent
formulations of MAS statements. 
For example the S--expression 
\begin{verbatim}
       (ASSIGN x (ADD 1 3))
\end{verbatim}
is generated from any of the following MAS statements:
\begin{verbatim}
       ASSIGN(x,ADD(1,3)).
       x:=ADD(1,3).
       x:=1+3.
\end{verbatim}
So all 3 statements are equivalent.
}

Further examples:
\begin{quote}
      \verb/x:=IEXP(2,100)./ evaluates to \verb/(0 0 0 8192)/.
\end{quote}
The function \verb/IEXP/ stands for integer exponentiation and
delivers the internal representation of $2^{100}$.
Then \verb/x/ is bound to the list \verb/(0 0 0 8192)/.
\begin{quote}
      \verb/IWRITE(x)./ evaluates to \verb/()/ and as a side effect
      produces \verb/12...376/.
\end{quote}
This statement is a procedure call. 
First \verb/x/ is evaluated to the value to which it is bound
\verb/(0 0 0 8192)/. This list is then supplied as input to 
the procedure \verb/IWRITE/, which means integer write.
Procedures always evaluate to \verb/NIL/ (= \verb/()/).
\verb/IWRITE/ writes the external (decimal) representation 
\verb/12...376/
of \verb/(0 0 0 8192)/ to the terminal.


\subsubsection{External and Internal Functions}

We have to distinguish between {\em internal},
{\em external} and {\em user defined} functions or procedures.
User defined functions are those declared with the
PROCEDURE declaration in MAS.

Internal functions are the functions which are builtin 
LISP functions, that means functions implemented in the 
LISP evaluator. Especially all functions which 
correspond to MAS operators are builtin.
\index{internal function}

External functions are {\bf compiled} Modula--2 procedures 
which are accessible from the interpreter.
\index{external function}
A list of all external functions can be displayed 
with the \verb/help(all)/ procedure.
\index{HELP}
The output looks like the following: 
{\small
\begin{verbatim}
     List of all compiled functions and procedures: 

     PROCEDURE ADV(LIST; LIST,LIST)
     FUNCTION  APFINT(LIST): LIST
     FUNCTION  APFRN(LIST): LIST
     ...
     PROCEDURE TIME
     PROCEDURE TRACE
     FUNCTION  TSGBASE(LIST,LIST,LIST): LIST

     65 functions and 27 procedures accessible.
\end{verbatim}
}
The first column contains the type \verb/FUNCTION/ 
or \verb/PROCEDURE/, which indicates if a value is
returned or not. In the second column follows 
the name of the function. Finally the type of
input and output parameters is shown. 
Currently all displayed parameters types are \verb/LIST/,
so this gives only a hint on the number of input 
and output parameters. 

The description of the procedures and the meaning of the
parameters must be taken from the 
Modula--2 library definition modules.
A procedure to module cross reference is contained in
the data set \verb/browse.rc/. 
The definition modules are contained in a folder
named \verb/HELP/.
See the section on help facilities for more
information on the system browser. 


\subsubsection{Bindings}

The assignment statement is one way to bind a value to 
a variable. In MAS a variable and a procedure cannot 
both have the same name, that means the identifier names are 
unique. 
\index{binding}
Caution: Other LISP systems allow variables and procedures 
to have the same name but to mean different objects. 

MAS allows procedure names to be used as variable names. 
So procedure names can be bound to variables and the 
variable can then be used as synonym for the procedure.

Consider the example:
\begin{quote}
       \verb/say:=IWRITE./ 
\end{quote}
Note that no parenthesis are following the \verb/IWRITE/ name.
The variable \verb/say/ is now bound to the 
procedure \verb/IWRITE/. So it is valid to 
use it in a procedure call:
\begin{quote}
       \verb/say(7)./
\end{quote}
which writes \verb/7/ to the terminal.

But don't bind a value to a procedure name, since this 
overwrites the procedure definition (unless you want to
bind it to a different procedure body).

Example:
\begin{quote}
       \verb/IWRITE:=foo./ now \\
       \verb/IWRITE(7)./ leads to a run time error: \\
       \verb/** error: invalid function object in APPLY: foo/.
\end{quote}
Such a problem can be `resolved' by the following 
assignment.
\begin{quote}
       \verb/IWRITE:=QUOTE(QUOTE(IWRITE))./
\end{quote}
This assures that \verb/IWRITE/ is bound to 
\verb/QUOTE(IWRITE)/ which evaluates to
\verb/IWRITE/ when used.

One further remark on bindings is that you can produce 
infinite loops with them. 
Consider the example:
\begin{quote}
       \verb/x:=y./ assume \verb/x/ and \verb/y/ are undefined, \\
       \verb/y:=x./ \verb/y/ is bound to itself, \\
       \verb/a:=y./ evaluates infinitely.
\end{quote}
\index{infinite loop}

The actual (top level) bindings can be displayed
by the \verb/DUMPV/ and \verb/LISTV/ procedures. 

\verb/LISTV/ lists the variable values in the syntax:
\begin{verbatim}
       name:=value.
\end{verbatim}
\verb/value/ is listed in MAS syntax as far as possible,
but it is not always guaranteed that such listings
can be read by the MAS parser again.

The output of \verb/LISTV/ may look like:

\begin{verbatim}
       exit:=EXIT.

       PROCEDURE tuwas();
       EDIT(was) tuwas.

       PROCEDURE run();
       IN(was) run.

       PROCEDURE masini();
       BEGIN was:="MAS.INI"; EDIT(was) END masini.

       NIL:=().
\end{verbatim}

\verb/DUMPV/ lists the variable values in the syntax:
\begin{verbatim}
       (SETQ name value)
\end{verbatim}
\verb/value/ is listed in LISP syntax, so it is 
always guaranteed, that such listings can be read 
in LISP mode again.

The output of \verb/DUMPV/ may look like:

\begin{verbatim}
       (SETQ exit EXIT)
       (SETQ was (25 21 39 21 49 29 17 68 29 39))
       (SETQ tuwas (LAMBDA () (EDIT was)))
       (SETQ run (LAMBDA () (IN was)))
       (SETQ masini (LAMBDA () (PROGN (ASSIGN was (STRING 37
                    12 51 68 29 39 29)) (EDIT was))))
       (SETQ NIL ())
\end{verbatim}


\subsubsection{VAR parameters}

Usually function and procedure parameters are evaluated from
left to right upon invocation. 
Exceptions to this rule are 
so called FEXPR functions or 
{\em external} Modula--2 functions with VAR parameters.
\index{VAR! parameter}
VAR parameters mean that only a reference to a variable
is used as parameter and not the value bound to a variable.

FEXPR functions do not evaluate their arguments at all.
They are described in the section on LISP and not discussed 
here.

The ALDES / SAC--2 libraries contain many procedures
with VAR parameters. The VAR and non VAR parameters
are organized in the scheme:
first all non VAR parameters, then all VAR parameters.
This is respected by the MAS interpreter 
when external procedures are called. The user may
therefore supply only variable names in places were 
VAR parameters appear. Upon exit from the procedure
the variables are bound to the computed values.

Example: 
\begin{quote}
\verb/PROCEDURE ADV(L: LIST; VAR a, LP: LIST);/
\end{quote}
This procedure expects one value input parameter \verb/L/ 
and two VAR parameters \verb/a/ and \verb/LP/.
\verb/ADV/ selects the first element of a list and the rest of
a list:
\begin{quote}
       \verb/ADV(LIST(1,2,3),a,B)./ binds 
       \verb/a/ to \verb/1/ and \verb/B/ to \verb/(2,3)/.
\end{quote}
The integer quotient and remainder function is
another example:
\begin{quote}
       \verb/IQR(44,7,a,b)./ binds 
       \verb/a/ to \verb/6/ and \verb/b/ to \verb/2/.
\end{quote}


\subsection{Statement Sequence}

In certain situations it is allowed to write sequences
of statements separated by semicolons (\verb/";"/).
Note that since statements may be empty one can view
the semicolon also as statement terminator character. 
The syntax of statement sequences is:
\begin{verbatim}
       statement { ";" statement } 
\end{verbatim}
\index{statement! sequence}


\subsection{BEGIN--END Statement}

In cases where no statement sequences are allowed, but 
only a statement, the BEGIN--END statement can be used to 
enclose a statement sequence.
Its syntax is:
\begin{verbatim}
       "BEGIN" statement-sequence "END" 
\end{verbatim}
\index{BEGIN-END! statement}

Note: BEGIN--END does not create a new block with new 
local variables !

{\small
The LISP code generated from BEGIN--END is the
PROGN S--expression. 
This implies that the value of a BEGIN--END statement
is the value of the last executed statement.
}

Example:
\begin{verbatim}
       BEGIN a:=IEXP(2,49); IWRITE(a) END.
\end{verbatim}
{\small
The corresponding LISP expression is
\begin{verbatim}
       (PROGN (ASSIGN a (IEXP 2 49) (IWRITE a))
\end{verbatim}
}
On the interpreter top level the BEGIN--END statement is 
often useful to suppress unused output: in the above example 
the internal representation of $2^{49}$ is not 
written, only the external representation appears in
the output stream.


\subsection{IF Statement}

The syntax of the IF statement is:
\begin{verbatim}
       "IF" condition "THEN" statementseq1 
                     ["ELSE" statementseq2] "END" 
\end{verbatim}
\index{IF! statement}

When the evaluation of \verb/condition/ yields
{\bf true} then \verb/statementseq1/ is executed,
otherwise \verb/statementseq2/ is executed (if present).

Example:
\begin{verbatim}
       a:=1. b:=2.
       IF a = b THEN CLOUT("equal")
                ELSE CLOUT("not equal") END.
\end{verbatim}
{\small
The LISP equivalent of the IF statement is:
\begin{verbatim}
       (IF (EQ a b) (CLOUT "equal")
                    (CLOUT "not equal"))
\end{verbatim}
The expression produces \verb/not equal/ as side effect.
}

Note: The IF statement returns the value of the
statement sequence which gets evaluated.

Note: With the Modula--2 like IF statements all
ambiguities of nested IF statements in Pascal are resolved.


\subsection{WHILE Statement}

The syntax of the WHILE statement is:
\begin{verbatim}
       "WHILE" condition "DO" statementseq "END" 
\end{verbatim}
\index{WHILE! statement}
The condition is evaluated. When the result is {\bf true},
the statement sequence is executed, when 
the result is {\bf false} then the evaluation of the
WHILE statement is finished.
After execution of the statement sequence the
WHILE statement is again evaluated.

Note: The WHILE statement returns the value of the 
last executed statement sequence or NIL if 
the first evaluation of condition is {\bf false}. 

Example:
\begin{verbatim}
       i:=0. a:=0.
       WHILE i < 17 DO i:=i+1; a:=a+i*i END.
\end{verbatim}
The WHILE statement evaluates to \verb/1785/, the
sum of the squares of the numbers from 0 to 17.


\subsection{REPEAT Statement}

The syntax of the REPEAT statement is:
\begin{verbatim}
       "REPEAT" statementseq "UNTIL" condition
\end{verbatim}
\index{REPEAT! statement}
First the statement sequence is executed, then
the condition is evaluated. When the result is {\bf true},
the execution of the REPEAT statement is finished. 
When the result is {\bf false}, the REPEAT statement is
again executed. 

Note: The REPEAT statement returns the value of the 
last executed statement sequence.

Example:
\begin{verbatim}
       i:=0. a:=1.
       REPEAT i:=i+1; a:=a*2 UNTIL i > 5.
\end{verbatim}
The REPEAT statement evaluates to \verb/64/, the
6--th power of 2.


\section{Declarations}

Elementary declarations can be
\begin{verbatim}
       { variabledecl | proceduredecl }
\end{verbatim}
In this place we will only discuss elementary 
declarations, the specification declarations 
will be described in a later section.


\subsection{VAR Declaration}

The syntax of the VAR declaration is:
\begin{verbatim}
       "VAR" identifierlist ":" identifier [ string ]
\end{verbatim}
\index{VAR! declaration}
The VAR declaration is used to define global or local
variables. In general it is not required to
declare variables in MAS. But certain usages
(support type information, generic function arguments)
require defined variables.
The \verb/identifier/ in the above definition 
denotes an arbitrary name. The meaning of \verb/string/
is explained in chapter \ref{spec.chap}.

The \verb/identifierlist/ has the following syntax:
\begin{verbatim}
       identifier { "," identifier }
\end{verbatim}
This is a sequence of identifiers separated by commas.
\index{identifier! list}


\subsection{PROCEDURE Declaration}

The syntax of the PROCEDURE declaration is:
\begin{verbatim}
       "PROCEDURE" ident1 
                   [ "(" [identlist] [";" "VAR" identlist] ")" ]
                   [ ":" ident2 ] ";" 
                   block ident1 ";"
\end{verbatim}
\index{PROCEDURE! declaration}
With this declaration it is possible to define a new
procedure, which can be used afterwards in the same way as the
builtin procedures.
\verb/ident1/ denotes the name of the procedure, it must be
repeated at the end of the procedure declaration.

\verb/[ "(" [identlist] [";" "VAR" identlist] ")" ]/ denotes the 
so called {\bf formal parameter list}.
\index{formal parameter! list}
The formal parameter list is a list of identifiers
separated by commas, followed optionaly
by a VAR parameter list.
\index{identifier! list} 
\index{formal parameter}\index{VAR! parameter} 

When the procedure is called (used, invoked) the so called
{\bf actual parameters}\index{actual parameter}
are evaluated and bound to the formal parameters and
are then accessible within the procedure body.
The numbers of actual and formal parameters
must be equal at runtime, otherwise an 
error occurs.
The formal parameters should be pair wise disjoint, 
otherwise only the last (that is the right most) 
actual parameter is bound to the formal parameter. 
The VAR parameters are not evaluated and must 
be identifiers. Uppon return from a procedure with 
VAR parameters, the local values of these parameters are 
bound to the actual parameter symbols.

The \verb/[ ":" ident2 ]/ construct specifies the 
type of the return value. However this information is
not used further by the interpreter. 
\verb/block/ denotes a sequence of 
declarations followed by a statement.

Results computed within the body of a procedure can be
returned to the caller by function values. 
The return values can be specified {\em explicitly}
be the RETURN statement or {\em implicitly}
as value of the last evaluated statement.
Several return values can only be returned as 
a single list.

The syntax of the RETURN statement is:
\begin{verbatim}
       "RETURN" [ "(" [ expression ] ")" ]
\end{verbatim}
\index{RETURN! statement}
The expression is evaluated and the result is
returned to the caller. The execution of
statement sequences or iteration statements is 
suspended after evaluation of a RETURN statement.

{\small
The generated code for the procedure declaration is
\begin{verbatim}
       (DE ident1 (identifierlist) block) 
\end{verbatim}
\verb/DE/ stands for `Define--Expr--function', and 
means that the actual parameters are evaluated before
they are bound to the formal parameters.
`fexpr' functions, which do not evaluate their 
arguments, and `macros' are discussed in the 
section on LISP. They cannot be defined in the
MAS language, but only in LISP.
}

The following examples define 
a function, that squares its argument, in
several ways:
\begin{verbatim}
       PROCEDURE sqr(a);
       RETURN(a*a) sqr.
\end{verbatim}
The square of 'a' is explicit returned
with a RETURN statement.

\begin{verbatim}
       PROCEDURE sqr(a);
       VAR b: ANY; 
       b:=a*a sqr.
\end{verbatim}
A local variable 'b' is declared to be of ANY type.
The square of 'a' is bound to 'b'. 
Since the assignment statement returns a value,
this value is then returned by the function. 

\begin{verbatim}
       PROCEDURE sqr(a);
       VAR b: ANY; 
       BEGIN b:=a*a END sqr.
\end{verbatim}
The assignment statement can also be enclosed in a BEGIN--END
statement. 

\begin{verbatim}
       PROCEDURE sqr(a): LIST;
       BEGIN RETURN(a*a) END sqr.
\end{verbatim}
This is almost in Modula--2 syntax except the
missing type specification of the
formal parameter 'a'.

\subsubsection{Scoping Rules}

The scope of a variable is the 'area' within
the variable is 'visible'. 
The visibility can be determined {\em statically} from
the program text, or {\em dynamically} during
execution of the program. 
\index{static scope}
\index{dynamic scope}\index{scope}
The MAS parser uses statical scoping and
the MAS interpreter uses dynamical scoping.

Variables which are defined on the top level
interpreter are {\em global} variables.
{\em Local} variables are those which are 
only visible in a procedure body.
\index{local! variable}
\index{global! variable}
But there is a case, when a variable is 
defined within a procedure, but used within
a further procedure called from the first procedure.
These variables are called {\em fluid} variables.
\index{fluid! variable}
The values of fluid variables depend on the actual (run--time)
environment of the procedure.

For MAS the following scoping rules apply:
\begin{enumerate}
\item Variables which are defined in the procedure header,
      (formal parameters) are {\em local} variables. 
\item Variables defined with the VAR declaration after the 
      procedure header are {\em local} variables.
\item For {\em undeclared} variables the following
      cases apply:
      \begin{enumerate}
      \item If there does not exist a global variable 
            or a local variable in a calling procedure 
            in the textual scope with the same name, 
            then the variable is declared as {\em local}.
            In this case a VAR declaration is generated 
            by the parser and a warning message is issued.
      \item If there exists a global variable 
            or a local variable in a calling procedure
            in the textual scope with the same name, 
            then the variable is {\em fluid}.
            Care has to be taken in the case when a procedure 
            containing fluid variables is transfered 
            (assigned to a global variable or returned as value)
            outside of its lexical block. 
            In this case the dynamical scoping of the interpreter 
            is used.
      \end{enumerate}
\end{enumerate}
{\bf Note:} Declare variables to ensure 
the correct usage of them.

{\bf Note:} Mutual recursive procedures will 
need a dummy forward reference to be in the textual scope 
when they are used.


\subsubsection{Procedure Variables}

{\small
In a procedure declaration the name of the
procedure becomes a variable, which is bound to the
S--expression corresponding to the procedure body.
In other words 
\begin{verbatim}
       (DE name (formals) body) 
\end{verbatim}
is equivalent to 
\begin{verbatim}
       (ASSIGN name (LAMBDA (formals) body)) 
\end{verbatim}
where LAMBDA is a tag to denote procedure bodies.
}

By this definition it is 
possible to use procedures as input to 
other procedures or to assign procedures to variables.
Compiled procedures are not defined 
in this way and have no associated LAMBDA expressions. 
However the evaluation mechanism takes care
that also compiled procedures can be used
as parameters.

Example:
Definition of a function \verb/apply/, which
applies its first argument to its second argument.
\begin{verbatim}
       PROCEDURE apply(f,x); RETURN(f(x)) apply.

       apply(INEG,4).         --> -4
       x:=INEG. apply(x,4).   --> -4
\end{verbatim}

A definition of a function \verb/mapcar/, which
applies its first argument 
to each list element of its second argument
is discussed in the section on list processing.

This completes the discussion of the basic MAS language.
In the next section we discuss input and output.
Although it is not defined in the language 
it is included here since it's understanding is required to 
write MAS programs.


\section{Input and Output}

The facilities for reading and writing data 
are described in this section.
\index{input}\index{output}
\index{read}\index{write}

The concept for input and output in MAS is
based on streams. Streams are continuous sequences of
characters.
A stream is called {\em open}, when it is connected
to a physical device. MAS allows maximal 25 streams to be open
at a time.

From these streams at any time two are the
{\em current} streams. That means all read operations
go to the current (or actual) input stream 
and all write operations
go to the current output stream.
It is possible to switch between open streams and 
a switch to a non open stream implies
a open operation for that stream.

From the beginning of the execution the
current input stream is connected to the
terminal (the keyboard) and the 
current output stream is also connected to
the terminal (the screen).
These two streams are always open. 
Further the terminal never becomes full during a write operation
and never becomes empty during a read operation.

One exception to the concept of current streams is
the error stream. It is always connected to the terminal
and can not be switched. So all error messages
appear on the terminal and response to them is 
expected from the terminal.

The streams are moreover managed like a stack.
If an open input stream becomes empty, then 
the next open input stream becomes automatically 
the current input stream. If an open output stream 
becomes full, then the next open output stream
is used.
'Last stream' means the stream which was current before
the last stream switch operation.

The stream switching functions are:
\begin{deflist}{SHUT("stream")}
\item[IN("stream")]   the current input stream is switched to
                      the stream `stream',
\item[OUT("stream")]  the current output stream is switched to
                      the stream `stream',
\item[SHUT("stream")] the specified stream is closed. 
\end{deflist}

The `stream' name may be prefixed by a 'device name' to specify
non--disk data sets:

\begin{description}
\item[CON:] is the terminal
\item[WIN:] is a window (not yet implemented)
\item[RAM:] is an internal memory stream, 
            `RAM--disk'
\item[GRA:] is a graphic\index{graphic} window (not yet implemented)
\item[NUL:] is a dummy stream to suppress output\index{output}, 
            always empty on input, never full on output,
\end{description}
\index{WIN}\index{CON}\index{RAM}\index{GRA}\index{NUL}

Other 'device names' are passed to the 
operating system\index{operating system} and
are usually interpreted as disk data sets.

Notes on the usage of the IN function.
Consider the following two MAS inputs:
\begin{verbatim}
      a)  IN("x.y"). statement.
\end{verbatim}
and
\begin{verbatim}
      b)  BEGIN IN("x.y"); statement END.
\end{verbatim}
In a) the IN function switches the 
actual stream to `x.y'. The contents of this stream
are evaluated, then the statement is executed.

In b) the BEGIN--END statement is
parsed and evaluated. The IN function switches the 
actual stream to `x.y'. 
But now the statement is executed and afterwards the
contents of the stream `x.y' are executed.

In other words the IN function does only a switch
to the next stream. If MAS is already executing
some statements it finishes first and 
afterwards takes the next input from
the new stream. 

The following two functions are for output:
\begin{deflist}{CLOUT("string")}
\item[BLINES(i)]        writes i blank lines to the output stream
\item[CLOUT("string")]  writes this string to the output stream
\end{deflist}


Example:

We will write a function, which puts a character string
to the input stream.
\begin{verbatim}
  PROCEDURE cltis(S);
  (*Character list to input stream. S is a character list.
  S is transferred to the input stream. *)
  BEGIN
  (*1*) SHUT("RAM:help"); OUT("RAM:help");
        CLOUT(S);
        SHUT("RAM:help"); IN("RAM:help");
  (*9*) END cltis.
\end{verbatim}
An utility stream `RAM:help' is opened for output.
Then the string is written to this stream and finally
the current input stream is switched to `RAM:help'.

As an application we discuss a function to convert
a string to an integer. 
(A detailed description of integers will be given later.)
\begin{verbatim}
  PROCEDURE s2i(S);
  (*Character list to integer. S is a character list. S is
  converted to an integer and the result is returned.*)
  BEGIN
  (*1*) cltis(CCONC(S," ")); 
        RETURN(IREAD());
  (*9*) END s2i.
\end{verbatim}
The string `S' is put to the input stream, then 
`IREAD' reads an integer from the current input stream.
Note that a blank must be appended 
with the CCONC function to the string to 
stop `IREAD' from requesting more digits from 
the terminal, or whatever stream is open.
With this function it is now more convenient to write
\begin{verbatim}
       a:=s2i("12345678901234567890").
\end{verbatim}
instead of
\begin{verbatim}
       a:=IREAD().  12345678901234567890 
\end{verbatim}


\subsection{Stream Summary}

A list of all streams can be obtained by the
\verb/BIOS/ function.
Its output look like the following:
{\small
\begin{verbatim}
 Summary of stream IO 
 
 Name     temp.out, 
 Output,  Byte-IO 11, Line-IO 14, Lmarg 0, Rmarg 79, Size 79. 
 Name     MAS.INI, 
 Closed,  Byte-IO 11, Line-IO 14, Lmarg 0, Rmarg 79, Size 79. 
 Name     CON:, 
 Output,  Byte-IO 25, Line-IO 13, Lmarg 0, Rmarg 79, Size 79. 
 Name     CON:, 
 Input,   Byte-IO 3, Line-IO 0, Lmarg 0, Rmarg 79, Size 79. 
 
 4 Files used. 
\end{verbatim}}

The first line contains the name of the stream. 
The second line contains information on the
status of the stream \verb/Closed/ etc. 
Next the number of bytes and lines transferred to or
received from the respective stream are displayed.
Finally the left margin \verb/Lmarg/, the
right margin \verb/Rmarg/ and line length \verb/Size/
are shown.


\subsection{Operating System}

On some computers the MAS system provides 
access to the operating system.
Most important is the possibility to call an editor
from within MAS. 
The two functions \verb/DOS/ and \verb/EDIT/ are summarized
as follows:
\begin{deflist}{EDIT("data set name")}
\item[DOS("prog parms")]  Calls the program 'prog' 
                          with the parameters 'parms'. \\
                          The meaning of the string depends 
                          on the operating system.
\item[EDIT("data set name")] Edits the specified data set.  \\
          The editor\index{editor} is expected to be 
          'EDITOR.PRG' on the current
          directory\index{directory}. 
          The editor on disk is 'microEMACS 3.9'. 
          The data set name string is prefixed by the
          string " @MAS.RC " which specifies the startup file
          for EMACS to be 'MAS.RC'. 
\end{deflist}

Examples: 

List the directory on an IBM PC:
\begin{verbatim}
       PROCEDURE dir;
       DOS("c:\command.com /c dir/p") dir.
\end{verbatim}

Call the PC command interpreter:
\begin{verbatim}
       PROCEDURE command;
       DOS("c:\command.com") command.
\end{verbatim}


