\documentstyle{article}
\setlength{\oddsidemargin}{0mm}
\setlength{\evensidemargin}{0mm}
\setlength{\textwidth}{160mm}
\setlength{\topmargin}{-10mm}
\setlength{\textheight}{220mm}
\parindent=0mm
\parskip=5mm

\def\mytitle{S-Lang Programmer's Guide}

\newlength{\pagewidth}
\setlength{\pagewidth}{\textwidth}
%\addtolength\pagewidth\marginparwidth
% \addtolength\pagewidth\marginparsep

\makeatletter
\def\ps@headings{\def\@oddfoot{}%
\def\@oddhead{\makebox[\textwidth][l]{\underline{\hbox to \pagewidth{\bf
\mytitle\hfill\thepage}}}}%
\def\@evenfoot{}%
\def\@evenhead{\makebox[\textwidth][l]{\underline{\hbox to \pagewidth{\bf
\mytitle\hfill\thepage}}}}}%
\pagestyle{headings}

\newcommand{\slang}{{\bf S-Lang}}
\newcommand{\jed}{{\bf jed}}
\newcommand{\exmp}[1]{{\tt #1}}
\newcommand{\var}[1]{{\tt #1}}

%--------------------- end of preamble ---------------------------------

\begin{document}
\thispagestyle{empty}
\vfill
\begin{center}
{\huge\bf
   S-Lang\\
\vspace{0.25in}
   Programmer's\\
\vspace{0.25in}
   Guide\\
}
\large
\vspace{0.5in}
   Version 0.1

\vfill

   John E. Davis\\
   \today
\end{center}
\vfill
\pagebreak

%---------------- end of title page ---------------------------------

\tableofcontents
\section{Introduction}

   \slang{} (pronounced ``sssslang'') is a powerful stack based interpreter
   that supports a C-like syntax.  It has been designed from the beginning
   to be easily embedded into a program to make it extensible. \slang{} also
   provides a way to quickly develop and debug the application embedding it
   in a safe and efficient manner.  Since \slang{} resembles C, it is easy to
   recode \slang{} procedures in C if the need arises.

   The \slang{} language features both global variables and local variables,
   branching and looping constructs, as well as user defined functions.
   Unlike many interpreted languages, \slang{} allows functions to be
   dynamically loaded (function autoloading).  It also provides constructs
   specifically designed for error handling and recovery as well as
   debugging aids (e.g., tracebacks).

   The core language currently implements signed integer, string, and
   floating point data types.  Applications may also create new types
   specific to the application (e.g., complex numbers).  In addition, \slang{}
   supports multidimensional arrays those types as well as any application
   defined types.

   The syntax of the language is quite simple and is very similar to C.
   Unlike C, \slang{} variables are untyped and inherit a type upon
   assignment. The actual type checking is performed at run time.  In
   addition, there is limited support for pointers.

  
\section{Variables}

   \slang{} is an untyped language and only requires that an variable be
   declared before it is used.  Variables are declared using the \var{variable}
   keyword followed by a comma separated list of variable names, e.g.,
\begin{verbatim}
         variable larry, curly, moe;
\end{verbatim}
   As in C, all statements must end with a semi-colon.  Variables can be
   declared to be either {\em global} or {\em local}. Variables defined
   inside functions are of the local variety and have no meaning outside the
   function.

   It is legal to execute statements in a variable declaration list.  That
   is,
\begin{verbatim}
         variable x = 1, y = sin (x);
\end{verbatim}
   are legal variable declarations.  This also provides a convenient way
   of initializing a variable.  
   
   The variable's type is determined when the variable is assigned a value.
   For example, in the above example, \var{x} is an integer and \var{y} is a float
   since \var{1} is an integer and the \var{sin} function returns a floating point
   type.
   

\section{Functions}

   Like variables, functions must be declared before they may be used. The
   \var{define} keyword is used for this purpose.  For example,   
\begin{verbatim}
         define factorial ();
\end{verbatim}
   is sufficient to declare a function named \var{factorial}.  Unlike
   \var{variable} keyword, the \var{define} keyword does not accept a list of names.
   Usually, the above form is used only for recursive functions.  The
   function name is almost always followed by a parameter list and the
   body of the function, e.g.,
\begin{verbatim}
         define my_function (x, y, z)
         {
           <body of function>
         }
\end{verbatim}
   Here \var{x}, \var{y}, and \var{z} are also implicitly declared as local variables.
   In addition, the function body must be enclosed in braces.
   
   Functions may return zero, one or more values.  For example,
\begin{verbatim}
        define sum_and_diff (x, y)
         {
            variable sum, diff;

            sum = x + y;  diff = x - y;
            return (sum, diff);
         }
\end{verbatim}
   is a function returning two values.
   
   Please note when calling a function that returns a value, the value
   returned cannot be ignored.   See the section below on assignment
   statements for more information about this important point.


\section{Statements and Expressions}

   A statement may occur globally outside of functions or locally within
   functions.   If the expression occurs inside a function, it is executed
   only when the function is called.  However, statements which occur
   outside a function context are evaluated immediately.
   
   All statements must end in a semi-colon.
   
   
\subsection{Assignment Statements}

   An assignment statement follows the syntax:
\begin{verbatim}   
      <variable name> = <expression>;
\end{verbatim}
   Whitespace is required on {\em both} sides of the equal sign.  For example,
\begin{verbatim}
        x = sin (y);
\end{verbatim}
   is correct but
\begin{verbatim}
        x =sin(y);  x= sin(y); x=sin(y);
\end{verbatim}
   will generate syntax errors.
   
   Often, functions return more than one value.  For example, 
\begin{verbatim}
        define sum_and_diff (x, y)
         {
            return x + y, x - y;
         }
\end{verbatim}
   returns two values.  The most general assignment statement syntax is 
\begin{verbatim}
     ( <var_1>, <var_2>, ..., <var_n> ) = <expression>;
\end{verbatim}
   e.g.,
\begin{verbatim}
        (s, d) = sum_and_diff (10, 2);
\end{verbatim}
   To ignore one of the return values, simply omit the variable name from
   the list.  For example, 
   
\begin{verbatim}
        (s, ) = sum_and_diff (10, 2);
\end{verbatim}
   may be used if one is only interested in the first return value.
   
   Some functions return a variable number of values.  Usually, the first
   value will indicate the actual number of return values.

   For example, the \var{fgets} function returns either one or two values.  If
   the first value is zero, there is no other return value.  In this case,
   one must use another form of assignment since the previously discussed
   forms are inadequate.  For example,    
\begin{verbatim}
      n = fgets (fd);
      if (n != 0)
        {
           s = ();
           .
           .
        }
\end{verbatim}
   In this example, the first value returned is assigned to \var{n} and tested.
   If it is non-zero, the second return value is assigned to \var{s}.   The
   empty set of parenthesis is required.

   Please note that RETURN VALUES CANNOT BE IGNORED.  There are several ways
   of dealing with a return value when one does not care about it.  For
   example, the function \var{fflush} returns a value.  However, most C
   programs that call this function almost always ignore the return value.
   In \slang{}, one can use any of the following forms:
\begin{verbatim}
       variable dummy;   
       dummy = fflush (fd);
     
       () = fflush (fd);
     
       fflush (fd); pop ();
\end{verbatim}
  The second form is perhaps the most clear way of indicating that the return
  value is being ignored.

\subsection{Binary Operators}

   \slang{} supports a variety of binary operators.  These include the usual
   arithmetic operators (\var{+}, \var{-}, \var{*}, \var{/}, and \var{mod}), the comparison
   operators (\var{>}, \var{>=}, \var{<}, \var{<=}, \var{!=}, and \var{==}) as well boolean
   operators (\var{or} and \var{and}) and bitwise operators (\var{|}, \var{\&}, \var{xor}, \var{shl}
   and \var{shr}).  Like the assignment operator, these operators must also be
   surrounded by whitespace.  That is, 
   
\begin{verbatim}
        x = y + z;
\end{verbatim}
   is a legal statement but \var{x = y+z;} is not legal.

   To use these operators effectively, in addition to understanding the
   meaning of the operation, one must also understand the precedence level
   of the operator.

   In \slang{}, there are only three levels of precedence.  The highest level
   consists of the \var{*}, \var{/}, and \var{mod} operators.  The second level consists
   of the \var{+} and \var{-} operators.  All other binary operators fall into the
   last level of precedence.  Within a precedence level, operators are
   evaluated left to right.  Parenthesis may be used to change the order of
   evaluation.  For example, the expression:   
\begin{verbatim}
        a == b or c == d
\end{verbatim}
   IS NOT the same as:
\begin{verbatim}
        (a == b) or (c == d)
\end{verbatim}
   since \var{==} and \var{or} share the same level of precedence.  In fact, the
   expression without parenthesis is evaluated left to right and is
   equivalent to \var{((a == b) or a) == c}.

   Finally, \slang{} supports the increment and decrement operators \var{++}
   and \var{--}, and the arithmetic assignment operators \var{+=} and
   \var{-=}.  Presently, these operators only work with integer types and a
   type mismatch error will result from the use of these operators with
   other types.

   These following table shows the meaning of these operators.
\begin{verbatim}
        
      Expression         Meaning
      ----------        ---------
       ++x;             x = x + 1;
       x++;             x = x + 1;
       --x;             x = x - 1;
       x--;             x = x - 1;
       x += n;          x = x + n;
       x -= n;          x = x - n;

\end{verbatim}
   Note that \slang{} does not distinguish between \var{x--} and \var{--x}
   since neither of these forms return a value as they do in C.  With this
   in mind, do not use constructs such as:
\begin{verbatim}
      while (i--) ....     % test then decrement 
      while (--i) ....     % decrement first then test 
\end{verbatim}
   Instead, use something like
\begin{verbatim}
      while (i, i--) ....  % test then decrement
      while (i--, i) ....  % decrement first then test
\end{verbatim}
   These operators work only on simple scalar variables. In particular,
   \exmp{++(x)} is NOT the same as \exmp{++x} and will generate an error.

   Whenever possible, these latter four operations should be used since they
   execute 2 to 3 times faster than the longer forms.


\subsubsection{Short Circuit Boolean Evaluation}

   The boolean operators \var{or} and \var{and} ARE NOT SHORT CIRCUITED as they are
   in some languages.  \slang{} uses the \var{orelse} and \var{andelse} operators for
   short circuit boolean evaluation.  However, these are not binary
   operators. Expressions of the form:
\begin{verbatim}
          <expr_1> and <expr_2> and <expr_3> ... and <expr_n>
\end{verbatim}
   can be replaced by the short circuited version using \var{andelse}:
\begin{verbatim}
        andelse {<expr_1>} {<expr_2>} {<expr_3>} ... {<expr_n>}
\end{verbatim}
   A similar syntax holds for the \var{orelse} operator.  For example, consider
   the statement: 
\begin{verbatim}
      if ((x != 0) and (1 / x < 10)) do_something ();
\end{verbatim}
   Here, if \var{x} were to have a value of zero, a division by zero error
   would occur because even though \var{x != 0} evaluates to zero, the
   \var{and} operator is not short circuited and the \var{1 / x} expression
   would be evaluated. For this case, the \var{andelse} operator could be
   used to avoid this problem:
\begin{verbatim}
        if (andelse
            {x != 0}
            {1 / x < 10})  do_something ();
\end{verbatim}

\subsection{Unary Operators}

   The UNARY operators operate only upon a single integer.  They are defined
   by the following table below.  In this table, the variable \var{i} is an
   integer type and \var{x} represents either a floating point or integer
   variable. 
\begin{verbatim}
     Unary Expression      Meaning
     ----------------    -------------------------------------------------
        not (i)          if i is non-zero return zero else return non-zero
        ~(i)             bitwise not
        sqr(x)           the square of x
        mul2(x)          multiplies x by 2
        chs (x)          change the sign of x
        -x               same as chs (x)
        sign (x)         +1 if x > 0, -1 if x < 0, and 0 if x equals 0
        abs (x)          absolute value of x
\end{verbatim}
   Note the following points:
\begin{itemize}   
\item All unary operators except \var{not} and \var{\~{}} operator on both integer
      and floating point types.

\item The \var{!} operator used in C is not used in \slang{},  \var{not} must be
      used instead.

\item The bitwise not operator \var{\~{}} must enclose its argument in
      parenthesis.  \var{\~{}i} will be flagged as a syntax error.

\item Some applications which embed \slang{} may overload these operators
      to work with application defined data types.
\end{itemize}     

\subsection{Data Types}

   Currently, \slang{} only supports integer, floating point (double
   precision), and character string data types.  It is possible for an
   application that embeds \slang{} to define other, application specific,
   data types (e.g., complex numbers).   In addition, the language supports
   arrays of any of these types (including application specific types).
   
\subsubsection{Integers}
   
   Unsigned integers are not supported.  An integer can be specified in one
   of several ways:
\begin{itemize}
\item As a decimal integer consisting of the characters \var{0} through
      \var{9}, e.g., \var{127}.  The number cannot begin with a leading
      \var{0}.  That is, \var{0127} is not the same as \var{127}.

\item Using hexidecimal (base 16) notation consisting of the characters
      \var{0} to \var{9} and \var{A} through \var{F}.  The hexidecimal
      number must be preceded by the characters \var{0x}.  For example,
      \var{0x7F} is the same thing as decimal \var{127}.

\item In Octal notation using characters \var{0} through \var{7}.  The Octal
      number must begin with a leading \var{0}.  For example, \var{0177} is
      the same thing as \var{127} decimal.

\item Using character notation containing a character enclosed in single
      quotes as \exmp{'a'}.   The value of the integer specified this way will
      lie in the range $0$ to $256$ and will be determined by the ascii
      value of the character in quotes.  For example, 
\begin{verbatim}
              i = '0';
\end{verbatim}
      results in a value of 48 for \var{i} since the character \var{0} has an
      ascii value of 48. 

      Strictly speaking, \slang{} has no character type.
\end{itemize}

    Any integer may be preceded by a minus sign to indicate that it is a
    negative integer.
   
   
\subsubsection{Floating Point Numbers}

    Floating point numbers must contain either a decimal point or an
    exponent (or both). Here are examples of specifying the same floating
    point number:
\begin{verbatim}
         12.,    12.0,    12e0,   1.2e1,   120e-1,   .12e2
\end{verbatim}
    Note that \var{12} is NOT a floating point number since it contains neither
    a decimal point nor an exponent.  If fact \var{12} is an integer.
    
      
\subsubsection{Strings}
    
    A literal string must be enclosed in double quotes as in:
\begin{verbatim}
      "This is a string".
\end{verbatim}
    Although there is no imposed limit on the length of a string, literal
    strings must be less than 256 characters.  It is possible to go beyond
    this limit by string concatenation.  Any character except a newline
    (ascii 10) or the null character (ascii 0) may appear in the {\em
    definition} of the string.

    The backslash is a special character and is used to include special
    characters (such as a newline character) in the string. The special
    characters recognized are:
\begin{verbatim}
       \"    --  double quote
       \'    --  single quote
       \\    --  backslash
       \a    --  bell character
       \t    --  tab character
       \n    --  newline character
       \e    --  escape  (S-Lang extension)
       \xhhh --  character expressed in HEXIDECIMAL notation
       \ooo  --  character expressed in OCTAL notation
       \dnnn --  character expressed in DECIMAL (S-Lang extension)
\end{verbatim}
    For example, to include the double quote character as part of the
    string, it is to be preceded by a backslash character, e.g.,
\begin{verbatim}
                            "This is a \"quote\""
\end{verbatim}

\subsection{Mixing integer and floating point arithmetic.}

   If a binary operation (+, -, * , /) is performed on two integers, the
   result is an integer.  If at least one of the operands is a float, the
   other is converted to float and the result is float.  For example:

\begin{verbatim}
    11 / 2           --> 5   (integer)
    11 / 2.0         --> 5.5 (float)
    11.0 / 2         --> 5.5 (float)
    11.0 / 2.0       --> 5.5 (float)
\end{verbatim}
   Finally note that only integers may be used as array indices, for loop
   control variables, shl, shr, etc bit operations.  Again, if there is any
   doubt, use the conversion functions \var{int} and \var{float} where appropriate:

\begin{verbatim}
    int (1.5)         --> 1 (integer)
    float(1.5)        --> 1.5 (float)
    float (1)         --> 1.0 (float)
\end{verbatim}

\subsection{Conditional and Branching Statements}

   \slang{} supports a wide variety of looping (\var{while}, \var{do while},
   \var{loop}, \var{for}, \var{forever}, and \var{\_for}) and branching
   (\var{if}, \var{!if}, \var{else}, \var{andelse}, \var{orelse}, and
   \var{switch}) statements.

   These constructs operate on code statements grouped together in {\em
   blocks}.  A block is a sequence of \slang{} statements enclosed in braces
   and may contain other blocks.  However, a block cannot include function
   declarations; function declarations must take place at the top level.  In
   the following, \var{statement} refers to either a single \slang{} statement
   or to a block of statements and \var{\{ block \}} refers to a block of
   statements.

\subsubsection{if, if-else}
\begin{verbatim}   
              if (expression) statement;
\end{verbatim}
        Evaluates \var{statement} if the result of \var{expression} is
        non-zero.  The \var{if} statement can also be followed by an \var{else}:
\begin{verbatim}
              if (expression) statement; else statement;
\end{verbatim}
    
\subsubsection{!if}
\begin{verbatim}   
              !if (expression) statement;
\end{verbatim}
        Evaluates \var{statement} if \var{expression} is evaluates to zero.  Note
        that there is no \var{!if-else} statement.
        
\subsubsection{orelse, andelse}
   
        These constructs were discussed earlier.  The syntax for the
        \var{orelse} statement is:
\begin{verbatim}        
            orelse { block } { block } ... { block }.
\end{verbatim}
        This causes each of the blocks to be executed in turn until one of
        them returns a non-zero integer value.  The result of this statement
        is the integer value returned by the last block executed.  For
        example,
\begin{verbatim}
            orelse { 0; } { 6; } { 2; } {3; }
\end{verbatim}
        returns \var{6} since the second block returns the non-zero result \var{6}
        and the last two block will not get executed.

        The syntax for the \var{andelse} statement is:
\begin{verbatim}
            andelse { block } { block } ... { block }.
\end{verbatim}
        Each of the blocks will be executed in turn until one of
        them returns a zero value.  The result of this statement is the
        integer value returned by the last block executed.  For example,
\begin{verbatim}        
            andelse { 6; } { 2; } { 0; } {4; }
\end{verbatim}
        returns \var{0} since the third block will be the last to execute.

     
\subsubsection{while}
\begin{verbatim}   
               while (expression) statement;
\end{verbatim}
       Repeat \var{statement} while \var{expression} returns non-zero.  For example, 
\begin{verbatim}
          j = 20; i = 10; while (i) { j = j + i; i = i - 1; }
\end{verbatim}
       will cause the block to execute 10 times.
        
\subsubsection{do-while}
\begin{verbatim}   
               do statement; while (expression);
\end{verbatim}
        Execute \var{statement} then test \var{expression}.  Repeat while
        \var{expression} returns non-zero.  This guarantees that
        \var{statement} will be executed at least once.

\subsubsection{for}
\begin{verbatim}   
               for (expr1; expr2; expr3) statement;
\end{verbatim}
        Evaluate \var{expr1} first.  Then loop executing \var{statement} while
        \var{expr2} returns non-zero.  After every evaluation of \var{statement}
        evaluate \var{expr3}.  For example,
\begin{verbatim}
             variable i, sum;
             sum = 0;
             for (i = 1; i <= 10; i++) sum += i;
\end{verbatim}
        computes the sum of the first 10 integers.
          
\subsubsection{loop}
\begin{verbatim}
               loop (n) statement;
\end{verbatim}
        Evaluate \var{statement} \var{n} times.  If \var{n} is less than
	zero, \var{statement} is not executed.
       
\subsubsection{forever}
\begin{verbatim}    
        forever statement;
\end{verbatim}
       Loop evaluating statement forever.  Forever means until either a
       \var{break} or \var{return} statement is executed.
       
\subsubsection{switch}
    
       The switch statement deviates the most from its C counterpart.  The
       syntax is:
\begin{verbatim}
          switch (x)
            { ...  :  ...}
              .
              .
            { ...  :  ...}
\end{verbatim}
        Here the object \var{x} is pushed onto the stack and the sequence of
        blocks is executed.  The \var{:} operator is a \slang{} special symbol
        which means to test the top item on the stack, if it is non-zero,
        the rest of the block is executed and control then passes out of the
        switch statement.  If the test is false, execution of the block is
        terminated and the process repeats for the next block.
        
        The special keyword \var{case}  may be used to compare the value of
        objects.   It  returns non-zero if the objects correspond to the
        same object and zero otherwise.
        
        For example:
\begin{verbatim}
            variable x = 3;
            switch (x)
              { case 1: print("Number is one.")}
              { case 2: print("Number is two.")}
              { case 3: print("Number is three.")}
              { case 4: print("Number is four.")}
              { case 5: print("Number is five.")}
              { pop(); print ("Number is greater than five.")}
\end{verbatim}
        Here \var{x} is assigned a value of $3$ and the \var{switch}
	statement pushes the $3$ onto the stack.  Control then passes to the
	first block.  The first block uses the \var{case} construct to
	compare the top top stack item ($3$) with $1$. This test will result
	with zero at the top of the stack. The \var{:} operator will then
	pop the top stack item and if it is zero, control will be passed to
	the next block where the process will be repeated.  In this case,
	control will pass to the second block and on to the third block.
	When the \var{:} operator is executed for the third block, a
	non-zero value will be left on the top of the stack and the
	\var{print} function will be called. Control then passes onto the
	statement following the last block of the \var{switch} statement.

        Note that, in this example, the last block does not test the value
	of \var{x} against anything. Instead, if this block is executed, the
	top stack item (the value of \var{x} in this case) will be removed
	from the stack by the \var{pop} function and the rest of the block
	executed.

        Unlike most other languages with some form of switch statement, \var{x}
        does not have to be a simple integer.  For example, the following is
        perfectly acceptable:
\begin{verbatim}
            variable x;
            x = "three";
            switch (x)
              { case "one": print("Number is 1.")}
              { case "two": print("Number is 2.")}
              { case "three": print("Number is 3.")}
              { case "four": print("Number is 4.")}
              { case "five": print("Number is 5.")}
              { pop(); print ("Number is greater than 5.")}
\end{verbatim}
        Again, the \var{case} function is used to test the top stack item and
        the last block serves as a ``catch-all''.
        

\subsubsection{break, return, continue}

   \slang{} also includes the non-local transfer functions \var{return}, \var{break},
   and \var{continue}.  The \var{return} statement causes control to return to the
   calling function while the \var{break} and \var{continue} statements are used in
   the context of loop structures.  Here is an example:

\begin{verbatim}
       define fun ()
       {
          forever 
            {
               s1;
               s2;
               ..
               if (condition_1) break;
               if (condition_2) return;
               if (condition_3) continue;
               ..
               s3;
            }
          s4;
          ..
       }
\end{verbatim}
   Here, a function \var{fun} has been defined that includes a \var{forever}
   loop which consists of statements \var{s1}, \var{s2},\ldots,\var{s3} and
   $3$ boolean conditions.  As long as \var{condition\_1},
   \var{condition\_2}, and \var{condition\_3} return $0$, statements
   \var{s1}, \var{s2},\ldots,\var{s3} will be repeatedly executed.  However,
   if \var{condition\_1} returns a non-zero value, the \var{break} statement
   will get executed, and control will pass out of the \var{forever} loop to
   the statement immediately following the loop which in this case is
   \var{s4}. Similarly, if \var{condition\_2} returns a non-zero number,
   \var{return} will cause control to pass back to the caller of \var{fun}.
   Finally, the \var{continue} statement will cause control to pass back to the
   start of the loop, skipping the statement \var{s3} altogether.

\subsection{Arrays}


   Arrays are created using the function call \var{create\_array}.  The type of
   the array and the size of the array are specified by parameters to this
   function.  The calling syntax is:
   
\begin{verbatim}
       x = create_array (<type>, i_1, i_2 ... i_dim, dim);
\end{verbatim}
   Here a \var{dim} dimensional array of type specified by \var{<type>} is
   created.  The size of the array in the {\em nth} dimension is specified by
   the parameters \var{i\_1}\ldots\var{i\_n} parameter.  The \var{<type>}
   parameter may be any one of the values given in the following table:
\begin{verbatim}
      Parameter         Type of array
      ---------         -------------
        's'             array of strings
        'f'             array of floats
        'i'             array of integers
        'c'             array of characters
\end{verbatim}
   Other integer values for the type may be given for applications which
   defined application specific types to create arrays of those types.

   In the current implementation, \var{dim} cannot be larger than $3$.  Also
   note that space is dynamically allocated for the array and that, upon
   assignment, copies of the array are NEVER used.  Rather, references to
   the array are used by the assignment statements.

   For example:
   
\begin{verbatim}
      variable a = create_array ('f', 10, 20, 2);
      variable b = a;
\end{verbatim}
   This creates a 2 dimensional $10 \times 20$ array of $200$ floats and
   assigns it to \var{a}.  The second statement makes the variable \var{b} also
   refer to the array specified by variable \var{a}.

   Accessing a specific element of the array may be accomplished by placing
   the ``coordinates'' of the element in square brackets.  For example, to
   access the $(3, 4)$ element of the above array use \exmp{a[3, 4]}.  Note
   that this differs from the way the C language specifies array access and
   that, like the C language, array subscripts start from 0.

   Finally, array notation may also be used for extracting characters from a
   string.  For example, if one has:

\begin{verbatim}
         variable ch,  s = "Hello World";
\end{verbatim}

   then \exmp{ch = s[0]} could be used to extract the first character from
   the string \var{s}.  However, this syntax cannot be used to replace
   characters in the string, i.e., \var{s[0] = ch} is illegal and will
   generate an error.  For the latter case, one must either use the
   \var{strsub} function or use a character array.

   Examples:

   Here is a function that computes the trace (sum of the diagonal elements)
   of a square 2 dimensional $n \times n$ array:

\begin{verbatim}
      define array_trace (a, n)
      {
         variable sum = 0, i;
         for (i = 0; i < n; i++) sum = sum + a[i, i];
         return sum;
      }
\end{verbatim}
   This fragment creates a $10 \times 10$ integer array, sets its diagonal
   elements to $5$, and then computes the trace of the array:
\begin{verbatim}
      variable a, j, the_trace;
      a = create_array('i', 10, 10, 2);
      for (j = 0; j < 10; j++) a[j, j] = 5;
      the_trace = array_trace(a, 10);
\end{verbatim}

   Note: The array syntax should be used consistently and should not
   be mixed with lower-level stack manipulations.  For example,
   consider the array \var{a} in the previous example.  While
\begin{verbatim} 
       a[j, j] = 5;
\end{verbatim} 
   works fine, 
\begin{verbatim} 
       5;  % push 5 onto stack
       a[j, j] = ();
\end{verbatim} 
   will not work.

\subsection{Stack Operators}

   The use of local variables greatly simplifies the task of maintaining the
   stack.  Nevertheless, \slang{} is really a stack based language and there
   are times when they are useful.
\begin{verbatim}
               pop        % removes the top object from the stack
               dup        % duplicates the top object on the stack
               exch       % exchanges top 2 objects on the stack
\end{verbatim}
   These operators work on all data types -- they are not limited to
   integers.


\section{Advanced Topics}

   This section should be thoroughly understood by anyone serious about
   using the \slang{} language.

\subsection{Loading Files: evalfile and autoload}

   Most \slang{} based applications will load a startup file which consists
   of \slang{} function definitions.  The file may load other files of
   \slang{} code via the \var{evalfile} intrinsic function.  This function
   takes one string argument (the filename) and returns a non-zero value if
   the file was successfully loaded, otherwise it returns zero.  For
   example,
\begin{verbatim}
      !if (evalfile("my_functs.sl")) error("Error loading File!");
\end{verbatim}
   instructs the interpreter to load the file \var{my\_functs.sl} and returns an
   error message upon failure.

   A nice feature found in \slang{} and not found in many interpreters in
   the ability to automatically load functions when they are used.  For
   example, consider the \jed{} editor which embeds \slang{} as its
   extension language. \jed{} includes a set of \slang{} routines defined in
   a file \var{info.sl} which read GNU info files. In particular, \jed{}'s
   online documentation is in info format. It is extremely unlikely that one
   would read the online documentation every time one edits a file. Thus, it
   is not normally necessary to load this file of \slang{} code.  Since the
   main entry point into the info reader is the function
   \var{info\_run\_info}, \jed{} includes the line
\begin{verbatim}
                    autoload("info_run_info", "info.sl");
\end{verbatim}
   in its main startup file (\var{site.sl}).  This line lets the \slang{}
   interpreter know that when the \var{info\_run\_info} function is called, the
   file \var{info.sl} is to be loaded first.

\subsection{Error Handling}

   Many intrinsic functions signal errors in the event of failure.  This is
   done internally in the underlying C code by setting \var{SLang\_Error} to
   a non-zero value.  Once this happens, \slang{} will start to return to
   top level by ``unwinding'' the stack. However, there are times when some
   cleanup needs to be done. This is facilitated in \slang{} through the
   concept of {\em error blocks}. An error block is a block of code that
   gets executed in the event of an error.  An error block is declared by
   the \var{ERROR\_BLOCK} directive.  As an example, consider the following:
\begin{verbatim}
      define example ()
      {
         ERROR_BLOCK {print("Error Block executed!"); }
         while (1);  % executes forever
      }
\end{verbatim}
   Here a function called \var{example} has been defined.  It assumes an
   intrinsic function \var{print} has been defined and that there is some
   way for the user to signal a quit condition which the underlying C code
   will trap and raise \var{SLang\_Error} to a non-zero value.  The
   \var{while} loop will execute forever until an error condition is
   signaled.  When that happens, the error block will get executed.

   Consider another example from the \jed{} editor.  When the user starts up
   \jed{} with no filename, a message is displayed in the \var{*scratch*}
   buffer until the user hits a key:
\begin{verbatim}
      define startup_hook()
      {
        !if (strcmp("*scratch*", whatbuf())) return;
        insert("This is the JED editor.\n\nFor help, hit Control-H Control-H");
        bob(); update(1);
        () = input_pending(300);    % wait up to 300 seconds for input
        erase_buffer();
      }
\end{verbatim}
   This is a function that \jed{} automatically calls upon startup.  If the
   buffer is the \var{*scratch*} buffer, a short help message is displayed;
   otherwise the function returns.  Then \jed{} will wait $300$ seconds or
   until the user hits a key at which point it will erase the buffer.  This
   will work fine unless the user does something to generate an error.  For
   example, errors will be generated of the user presses the {\sc Ctrl-G}
   key to signal a quit condition, tries to delete past the beginning of the
   buffer, etc\ldots  If an error is generated, \slang{} will abort before
   erasing the buffer. This will leave the help message on the screen and in
   the buffer which is not what is desired.  To prevent this, an error block
   is used:
\begin{verbatim}
     define startup_hook()
     {
        !if (strcmp("*scratch*", whatbuf())) return;
        ERROR_BLOCK {erase_buffer();}
        insert("This is the JED editor.\n\nFor help, hit Control-H Control-H");
        bob(); update(1);
        () = input_pending(300);    % wait up to 300 seconds for input
        EXECUTE_ERROR_BLOCK;
     }
\end{verbatim}
   Here an error block has been declared and consists of the single
   statement \var{erase\_buffer()}. If an error occurs the buffer will be
   erased. The statement \var{EXECUTE\_ERROR\_BLOCK} is a \slang{} directive
   that says to go ahead and execute the error block even if no error has
   occurred.

   Error blocks will not get executed for all errors.  For example, if there
   is a memory allocation error or an error associated with the stack, it
   would make no sense to call the error block.  

   Once an error has been caught by an error block, the error can be cleared
   by the \var{\_clear\_error} function.  After the error has been cleared,
   execution resumes at the next statement at the level of the error block
   following the statement that generated the error.  For example, consider:
\begin{verbatim}
       define make_error ()
       {
           error ("Error condition created.");
           print ("This statement is not executed.");
       }
       
       define test ()
       {
           ERROR_BLOCK 
             {
                _clear_error ();
             }
           make_error ();
           print ("error cleared.");
       }
\end{verbatim}
   Note that although the error was triggered in the \var{make\_error} function,
   the error was cleared in the \var{test} function.  As a result, execution
   resumes after the statement that makes the call to \var{make\_error} since
   this statement is at the same level as the error block that cleared the
   error.
   
   Here is another example that illustrates how multiple error blocks work.
\begin{verbatim}
       define test ()
       {
          variable n = 0, s = "";
          
          ERROR_BLOCK { 
            print (Sprintf ("s = %s, n = %d", s, n, 2));
            _clear_error (); 
          }
          
          forever
          {
             ERROR_BLOCK {
               s = strcat (s, "0");
               _clear_error ();
             }
             if (n == 0) error ("");
             
             ERROR_BLOCK {
               s = strcat (s, "1");
             }
             if (n == 1) error ("");
             
             n++;
          }
       }     
\end{verbatim}
   Here, three error blocks have been declared.  One has been declared
   outside the \var{forever} loop and the other two have been declared
   inside the \var{forever} loop.  Each time through the loop, the variable
   \var{n} is incremented and a different error block is triggered.  The
   error block that gets triggered is the last one encountered.  On the
   first time through the loop, \var{n} will be zero and the first error
   block in the loop will be executed.  This error block clears the error
   and execution will resume following the \var{if} statement that triggered
   the error.  The variable \var{n} will be incremented to $1$ and, on the
   second cycle through the loop, and the second \var{if} statement will
   trigger an error and the second error block will execute. This time, the
   error is not cleared and the \var{forever} loop will abort causing the
   error block outside the \var{forever} loop to fire.  This block prints
   out the values of the variables \var{s} and \var{n}.  It will clear the
   error and execution resumes on the statement {\em following} the
   \var{forever} loop.  In the end, \exmp{s = 01, n = 1} will be printed.

   To summarize, \var{ERROR\_BLOCK} is a directive that declares an error block.
   The \var{EXECUTE\_ERROR\_BLOCK} directive indicates that the error block is to
   be executed at this point--- no error is necessary.  In addition, error
   blocks may be defined at multiple levels.  As the stack unwinds in
   response to an error condition, all error blocks in scope will get
   executed.  The function \var{\_clear\_error} can be used to clear the error
   condition.

   Emacs elisp programmers should note the similarity to the Emacs elisp
   function `unwind-protect'.

\subsection{Exit and User Blocks}

   Error blocks get executed as the result of an error or when the directive
   \var{EXECUTE\_ERROR\_BLOCK} is encountered.  There are two other types of
   blocks that are useful: {\em exit blocks} and {\em user blocks}.
   
\subsubsection{Exit Blocks}
   
   An exit block is declared using the directive \var{EXIT\_BLOCK}.  It is executed
   when the function returns.  For example, consider:
\begin{verbatim}
      define test ()
      {
         variable n = 0;
         
         EXIT_BLOCK { print ("Exit block called."); }
         
         forever
          {
            if (n == 10) return;
            n++;
          }
      }
\end{verbatim}
   Here, the function contains an exit block and a \var{forever} loop.  The
   loop will terminate via \var{return} when \var{n} is $10$.  When it
   returns, the exit block will be called.

   Exit blocks are very useful for cleaning up when a function returns via
   an explicit call to \var{return} deep within the function.  
   
   
\subsubsection{User Blocks}

   A user block is similar to a function within a function.  Up to 5 user
   blocks may be declared per function.  Unlike functions, user blocks do
   not take arguments but do have access the function's local variables.
   User blocks are denoted by the directives \var{USER\_BLOCK0},
   \var{USER\_BLOCK1}, \var{USER\_BLOCK2}, \var{USER\_BLOCK3}, and
   \var{USER\_BLOCK4}.  The directives \var{X\_USER\_BLOCK0},
   \var{X\_USER\_BLOCK1}, \var{X\_USER\_BLOCK2}, \var{X\_USER\_BLOCK3}, and
   \var{X\_USER\_BLOCK4} may be used to call the user blocks.

   Here is an example:
\begin{verbatim}
      define silly ()
      {
         variable s1, s2, ch = 'a';
         
         USER_BLOCK0 
          {
            s1 = ();
            Sprintf ("%s & %c", s1, ch, 2);
            ch++;
          }
          
         s2 = "";
         s2 = X_USER_BLOCK0 (s2);
         s2 = X_USER_BLOCK0 (s2);
         s2 = X_USER_BLOCK0 (s2);
         s2 = X_USER_BLOCK0 (s2);
         print (s2);
      }
\end{verbatim}
   Here a user block has been declared.  Although user blocks are not
   functions, as the example demonstrates, they can be used as functions.
   This is possible because \slang{} is a stack based language and parameters
   are passed via the stack.
   
   
\subsection{Aliases}

   \slang{} supports a limited concept of a pointer known as an \var{alias}.
   Variables can be declared to be aliases for global functions or global
   variables. Consider the following three functions:
\begin{verbatim}
     define first () { print("First"); }
     define second () { print("Second"); }
     define first_second()
     {
        variable f;
        f = &first;  f();      % Line 1 (see text)
        f = &second;  f();     % Line 2 (see text)
     }
\end{verbatim}
   Here three functions have been defined.  The functions \var{first} and
   \var{second} should be quite clear.  However, the function
   \var{first\_second} looks somewhat strange because of the appearance of
   the \var{\&} character. When the interpreter encounters a function or
   variable name immediately preceded by the \var{\&} character, it pushes
   the address of the OBJECT referenced by the name onto the stack rather
   than pushing its value (variable) or executing it (function).  The object
   referred to {\em must be a global object}, either a global variable or a
   global function. Thus \var{\&first} pushes the address of the function
   \var{first} on the stack rather than calling \var{first}. The local
   variable \var{f} is then assigned this address.  Note that after the
   assignment, \var{f} is neither a string type nor an integer type. Rather,
   it becomes a function type and and is synonymous with the function
   \var{first}, i.e., it is an alias for \var{first}. Hence the line labeled
   ``Line 1'' above simply calls the function \var{first}. A similar
   statement holds for ``Line 2'' which results in the function \var{second}
   getting called.

   Finally note that aliases may be passed as arguments.  Consider:
\begin{verbatim}
      define execute_function (f)
      {
         f();
      }
\end{verbatim}
   Then
\begin{verbatim}
       execute_function(&first);  execute_function(&second);
\end{verbatim}
   will work as in the above example.

   This concept should be clear to most C programmers or to LISP programmers
   who will interpret the \var{\&} prefixing the object name as simply
   quoting the object.


\subsection{Functions returning multiple values}

   There are some functions which return multiple values.  For example,
   \slang{}'s implementation of the \var{fgets} function takes a single
   argument, a handle an to open file, and usually returns two values: the
   number of characters read followed by the character string itself.  The
   question immediately arises about how to handle such a function.  The
   answer to this question is to understand the stack.  Consider the
   following function which ``types'' out a file to the standard output
   device.
\begin{verbatim}
     define display_file(file)
     {
        variable n, fp, buf;
        
        fp = fopen(file);
        if (fp == -1) error("fopen failed.");
        
        while (n = fgets(fp), n > 0)
          {
             buf = ();                  % <----- stack
             () = fputs(buf, stdout);   % ignore return value.
          }
        if (fclose(fp) <= 0) error("fclose failed.");
     }
\end{verbatim}
   The \var{fgets} function returns $2$ items to the stack only when it
   reads one or more characters from the file.  If it encounters the end of
   the file, it returns 0 and nothing else.  If an error occurs when
   reading, it returns -1.  The line containing the comment above
   illustrates how to assign the top stack item to a variable.  Note also,
   that the two lines:
\begin{verbatim}
      buf = ();
      () = fputs(buf, 1);
\end{verbatim}
   can be replaced by the single line:  
\begin{verbatim}
      () = fputs((), 1);
\end{verbatim}
   It is also permissible to replace \var{buf = ()} by simply \var{=buf}.
   Note that there is no space between the \var{=} and \var{buf} in the
   latter form.

   Someone might simply suggest to do it like it is done in C, i.e.,
\begin{verbatim}
      n = fgets(buf, fp);
\end{verbatim}
   However, this is impossible in \slang{}, and it is not even desirable.
   \slang{} is an interpreted language and one of the reasons for using it
   over the C language is to free oneself from problems which can arise in
   the above \var{C} expression.

   Finally, note that, when used as an argument, \var{()} is simply a
   disguise for the the {\em top} stack item.  Consider the following code
   fragment:
\begin{verbatim}
    variable div_1, div_2;

    12; div_1 = () / 4;              % push 12 on stack then do division
    4;  div_2 = 12 / ();             % push 4 on stack then do division
\end{verbatim}
   The value of \var{div\_1} will be the expected result of $12 / 4 = 3$;
   however, \var{div\_2} will have the value of $4 / 12$!  The reason is
   that {\em after parsing}, \var{()} will be replaced by the {\em top}
   stack item and in the second case, $12$ will be the top stack item, not
   $4$.   If this point is unclear, it is better to simply avoid the use of
   \var{()} in this manner.
\end{document}
