\documentclass{report}
\newif\ifpdf\ifx\pdfoutput\undefined\pdffalse\else\pdfoutput=1\pdftrue\fi
\newcommand{\pdfgraphics}{\ifpdf\DeclareGraphicsExtensions{.jpg,.pdf}\else\fi}

% Thanks to Sven Hartrumpf for providing all the options for conversion
% to pdf 
\usepackage[bookmarks=true,bookmarksnumbered=true,bookmarksopen=false,colorlinks=true,pdfpagemode=none,plainpages=false]{hyperref} 
\usepackage{graphics}

\let\urlfootnote\footnote

\author{(c) 2000-2003, Felix L.~Winkelmann}
\setcounter{secnumdepth}{3} 
\setcounter{tocdepth}{3} 

% ok, there are some shennanigans going on here. If this file is being
% processed by LaTex, it will assume a .eps exptension for images, however, if 
% this file is processed by pdflatex, then it will use the \pdfgraphics
% command and assume .jpg format instead. Not only that, but AFAICT
% latex2html assumes .eps format, and converts it to .png. *sigh* -psilord
\title{
        CHICKEN - A practical and portable Scheme system\\
        User's manual\\
        (Version 1, Build 7) \\
        \resizebox{70mm}{74mm}
                {\includegraphics{chicken}}}
% (c) 2000-2003, Felix L. Winkelmann
% All rights reserved.
% Translated to LaTeX by Peter Keller
\begin{document}
\pdfgraphics
\sloppy
\maketitle
\tableofcontents
\newpage

% The emph is split up here because if there is too much text in a command
% LaTeX thinks it is a runaway command.

\emph{Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
\begin{itemize}
\item Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
\item Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
\item Neither the name of the author nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.  
\end{itemize} }

\emph{THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE,
DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.}

\chapter{Introduction}
CHICKEN is a compiler that translates Scheme source-files into C, which in
turn can be fed to a C-compiler to generate a standalone executable. This
principle, which is used by several existing compilers, achieves high
portability because C is implemented on nearly all available platforms.

This package is distributed under the BSD license and as such is free
to use and modify. An interpreter is also available and can be used as
a scripting environment or for testing programs before compilation.

The method of compilation and the design of the runtime-system
follow closely Henry Baker's \emph{Cheney on the M.T.A}
\cite{cotmta} paper and expose a number of interesting properties:
consing (creation of data on the heap) is relatively inexpensive,
because a generational garbage collection scheme is used, in which
short-lived data structures are reclaimed extremely quickly.  Moreover,
\texttt{call-with-current-continuation} is practically for free and
CHICKEN does not suffer under any performance penalties if first-class
continuations are used in complex ways.  The generated C code is fully
tail-recursive.

Some of the features supported by CHICKEN:
\begin{itemize}
\item SRFIs 0, 1, 2, 4, 6, 7, 8, 9, 10, 13, 14, 16, 18, 22, 23, 25, 28, 30 and 37
\item \texttt{syntax-case} highlevel macros
\item Lightweight threads based on first-class continuations
\item Pattern matching with Andrew Wright's \texttt{match} package
\item Record structures
\item An object system with multiple inheritance, multimethods and a
                meta-object protocol
\item Extended comment- and string-literal syntaxes
\item Libraries for regular expressions, string handling, Common LISP
                style \texttt{format},
UNIX system calls and extended data structures
\item Create interpreted or compiled shell scripts written in Scheme
                for UNIX or Windows
\item Compiled C files can be easily distributed
\item On systems that support it, compiled code can be loaded dynamically
\end{itemize}

\chapter{Basic mode of operation}

The compiler translates Scheme source code into fairly portable C that
can be compiled and linked with most available C compilers. Separate
compilation is supported by so-called \emph{unit}s.  A unit is a single
compiled object module that contains a number of toplevel expressions that
are executed when either when the unit is the \emph{main} unit or if the
unit is \emph{used}.  To use a unit, the unit has to be \emph{declare}ed
as used, like this:

\begin{verbatim}
(declare (uses UNITNAME))
\end{verbatim}


The toplevel expressions of used units are executed in the order in
which the units appear in the \texttt{\textbf{uses}} declaration. Units
may be used multiple times and \texttt{\textbf{uses}} declarations may
be circular (the unit is initialized at most once).  To compile a file
as a unit, add a \texttt{\textbf{unit}} declaration:

\begin{verbatim}
(declare (unit UNITNAME))
\end{verbatim}

When compiling different object modules, make sure to have one main
unit. This unit is called initially and initializes all used units
before executing its toplevel expressions. The main-unit has no
\texttt{\textbf{unit}} declaration.

Another method of using definitions in separate source files is to
\emph{include} them. This simply inserts the code in a given file into
the current file:

\begin{verbatim}
(include "FILENAME")
\end{verbatim}

One important thing: macro definitions are only available when
included. Macro definitions in separate units are not available, since
they are defined at compile time, i.e the time when that other unit
was compiled.  (macros defined using the low-level macro system are also
available at runtime, see \texttt{\textbf{define-macro}}).


\chapter{Using the compiler}

The interface to \texttt{chicken} is intentionally simple.  System
dependent makefiles, shell-scripts or batch-files should perform
any necessary steps before and after invocation of \texttt{chicken}.
On UNIX-compatible systems, a shell script named \texttt{chicken-config}
is supplied that emits the correct options for the host system's C
compiler. Enter

\begin{verbatim}
chicken-config -help
\end{verbatim}

on the command line for a list of available options.  On most UNIX
systems, a Scheme script named \texttt{csc} provides a much simpler
interface to the Scheme- and C-compilers and linker. Enter

\begin{verbatim}
csc -help
\end{verbatim}

on the command line for more information.  A batch-file (\texttt{csc.bat})
with the same functionality is also available for Windows platforms.

\section{Commmand line format} \label{compileroptions}

\texttt{chicken FILENAME \{OPTION\}}

\texttt{FILENAME} is the complete pathname of the source-file that is to
be translated into C. A filename argument of \texttt{``-''} specifies that
the source text should be read from standard input.  Possible options are:

\begin{description}

\item[-analyze-only]
Stop compilation after first analysis pass.

\item[-benchmark-mode]
Equivalent to \texttt{-debug-level 0 -optimize-level 3}
\texttt{-fixnum-arithmetic -disable-interrupts -block}.

\item[-block]
Enable block-compilation. When this option is specified, the
compiler assumes that global variables are not modified outside this
compilation-unit.  Specifically, toplevel bindings are not seen by
\texttt{eval} and unused toplevel bindings are removed.

\item[-case-sensitive]
Enables the reader to read symbols case sensitive. The default is to read
non case sensitive.  This option registers the \texttt{case-sensitive}
feature identifier.

\item[-check-syntax]
Aborts compilation process after macro-expansion and syntax checks.

\item[-compile-time-macros-only]
Makes low-level macros (compiled without the \texttt{-hygienic} option) only available
at compile-time. By default low-level macros are also available at
run-time. Note that highlevel-macros (\texttt{syntax-case}) defined in
compiled code are never available at run-time.

\item[-compress-literals THRESHOLD]
Compiles quoted literals that exceed the size \texttt{THRESHOLD} as strings
and parse the strings at run-time. This reduces the size of the code and
speeds up compile-times of the host C compiler, but has a small run-time
performance penalty. The size of a literal is computed by counting recursively the objects
in the literal, so a vector counts as 1 plus the count of the elements,
a pair counts as the counts of the car and the cdr, respectively.
All other objects count 1.

\item[-debug MODES]
Enables one or more compiler debugging modes. \texttt{MODES} is a string
of characters that select debugging information about the compiler that
will be printed to standard output.

\begin{tabular}{|ll|}
\hline
    t & show time needed for compilation\\
    b & show breakdown of time needed for each compiler pass\\
    o & show performed optimizations\\
    r & show invocation parameters\\
    s & show program-size information and other statistics\\
    a & show node-matching during simplification\\
    p & show execution of compiler sub-passes\\
    l & show lambda-lifting information\\
    m & show GC statistics during compilation\\
    n & print the line-number database \\
    c & print every expression before macro-expansion\\
    x & display information about experimental features\\
    N & show the real-name mapping table\\
    U & show expressions after the secondary user pass\\
    0 & show database before lambda-lifting pass\\
    L & show expressions after lambda-lifting\\
    1 & show source expressions\\
    2 & show canonicalized expressions\\
    3 & show expressions converted into CPS\\
    4 & show database after each analysis pass\\
    5 & show expressions after each optimization pass\\
    6 & show expressions after each inlining pass\\
    7 & show expressions after complete optimization\\
    8 & show database after final analysis\\
    9 & show expressions after closure conversion\\
\hline
\end{tabular}

\item[-debug-level LEVEL]
Selects amount of debug-information. \texttt{LEVEL} should be an integer.


\begin{itemize}
\item \texttt{-debug-level 0} is equivalent to \texttt{-no-trace}.
\item \texttt{-debug-level 1} does nothing.
\end{itemize}

\item[-disable-interrupts]
Equivalent to the \texttt{(disable-interrupts)} declaration. No
interrupt-checks are generated for compiled programs.

\item[-epilogue FILENAME] Includes the file named
\texttt{FILENAME} at the end of the compiled source file. The include-path
is not searched. This option may be given multiple times.

\item[-explicit-use]
Disables automatic use of the units \texttt{library} and \texttt{eval}.
Use this option if compiling a library unit instead of an application
unit.

\item[-extend FILENAME]
Loads a Scheme source file or compiled Scheme program (on systems that
support it) before compilation commences. This feature can be used to
extend the compiler.  This option may be given multiple times.

\item[-feature SYMBOL]
Registers \texttt{SYMBOL} to be a valid feature identifier for
\texttt{cond-expand}.

\item[-fixnum-arithmetic]
Equivalent to \texttt{(fixnum-arithmetic)} declaration. Assume all
mathematical operations use small integer arguments.

\item[-heap-size NUMBER]
Sets a fixed heap size of the generated executable to \texttt{NUMBER}
bytes. The parameter may be followed by a 
\texttt{M} (\texttt{m}) or \texttt{K} (\texttt{k})
suffix which stand for mega- and kilobytes, respectively.  The default
heap size is 5 kilobytes. Note that only half of it is in use at every
given time.

\item[-heap-initial-size NUMBER]
Sets the size that the heap of the compiled application should have at
startup time.

\item[-heap-growth PERCENTAGE]
Sets the heap-growth rate for the compiled program at compile time
(see: \texttt{-:hg}).

\item[-heap-shrinkage PERCENTAGE]
Sets the heap-shrinkage rate for the compiled program at compile time
(see: \texttt{-:hs}).

\item[-help]
Print a summary of available options and the format of the command line
parameters and exit the compiler.

\item[-hygienic]
Load ``syntax-case'' macro package and enable high-level macros in
compiled code.  This option registers the \texttt{hygienic-macros}
feature identifier.

\item[-hygienic-at-run-time]
Makes hygienic (``syntax-case'') macro system available at run-time. Note
that this has a slight overhead, because the hygienic macro definitions
have to be loaded. This will only install the standard R5RS macros,
plus SRFI-0 (\texttt{cond-expand}). To load all further macros, execute:

\begin{verbatim}
(require 'moremacros)
\end{verbatim}

\item[-include-path PATHNAME]
Specifies an additional search path for files included via the
\texttt{include} special form. This option may be given multiple times. If
the environment variable \texttt{CHICKEN\_INCLUDE\_PATH} is set, it
should contain a list of alternative include pathnames separated by
\texttt{``;''}. The environment variable \texttt{CHICKEN\_HOME} is also
considered as a search path.

\item[-keyword-style STYLE]
Enables alternative keyword syntax, where \texttt{STYLE} may be either
\texttt{prefix} (as in Common Lisp) or \texttt{suffix} (as in DSSSL).
Any other value is ignored.

\item[-lambda-lift]
Enable the optimization known as lambda-lifting.

\item[-no-trace]
Disable generation of tracing information. If a compiled executable should
halt due to a runtime error, then a file containing a stack-trace will
be written to the current directory under the name \texttt{STACKTRACE}.
Each line in the created file gives the name and the line-number (if
available) of a procedure call.  With this option given, the generated
code is slightly faster.

\item[-no-feature SYMBOL]
Unregisters feature identifier \texttt{SYMBOL}.

\item[-no-warnings]
Disable generation of compiler warnings.

\item[-no-winding-callcc]
Identical to the \texttt{(no-winding-callcc)} declaration. All
uses of \texttt{call-with-current-continuation} do not respect
\texttt{dynamic-wind} before- and after-thunks.

\item[-nursery NUMBER -stack-size NUMBER]
Sets the size of the first heap-generation of the generated executable
to \texttt{NUMBER} bytes. The parameter may be followed by a \texttt{M}
(\texttt{m}) or \texttt{K} (\texttt{k}) suffix.  The default stack-size
depends on the target platform.

\item[-optimize-leaf-routines]
Enable leaf routine optimization.

\item[-optimize-level LEVEL]
Enables certain sets of optimization options. \texttt{LEVEL} should be
an integer.


\begin{itemize}
\item \texttt{-optimize-level 0} does nothing.
\item \texttt{-optimize-level 1} is equivalent to
      \texttt{-optimize-leaf-routines -lambda-lift}.
\item \texttt{-optimize-level 2} is equivalent to
      \texttt{-optimize-leaf-routines -lambda-lift -usual-integrations}.
\item \texttt{-optimize-level 3} is equivalent to
      \texttt{-optimize-leaf-routines -lambda-lift -usual-integrations -unsafe}.
\end{itemize}

\item[-output-file FILENAME]
Specifies the pathname of the generated C file. Default is \texttt{FILENAME.c}.

\item[-postlude EXPRESSIONS]
Add \texttt{EXPRESSIONS} after all other toplevel expressions in the
compiled file.  This option may be given multiple times. Processing of
this option takes place after processing of \texttt{-epilogue}.

\item[-prelude EXPRESSIONS]
Add \texttt{EXPRESSIONS} before all other toplevel expressions in the
compiled file.  This option may be given multiple times. Processing of
this option takes place before processing of \texttt{-prologue}.

\item[-profile]
Instruments the source code to count procedure calls and execution
times. After the program terminates (either via an explicit \texttt{exit}
or implicitly), profiling statistics are written to a file named
\texttt{PROFILE}. Each line of the generated file contains a list with
the procedure name, the number of calls and the time spent executing
it. Use the script \texttt{formatprofile} to display the profiling
information in a more user-friendly form. Enter \texttt{formatprofile}
with no arguments at the command line to get a list of available options.
Note that the file is only important in the compilation of the main
compilation unit. For library units the option is still needed (to record
procedures defined in that unit), but the filename is ignored.

\item[-prologue FILENAME]
Includes the file named \texttt{FILENAME} at the start of the compiled
source file.  The include-path is not searched. This option may be given
multiple times.

\item[-quiet]
Disables output of compile information.

\item[-srfi-7]
Process the source as a SRFI-7 configuration language file (see: the
SRFI-7 document\urlfootnote{http://srfi.schemers.org/srfi-7/srfi-7.html})

\item[-strict]
Disable non-standard macros. This option registers the \texttt{strict}
feature identifier.

\item[-strict-srfi-0]
Disable non-standard macros except \texttt{cond-expand}.  This option
registers the \texttt{strict} feature identifier.

\item[-strict-reader]
Disables non-standard read syntax.

\item[-strict-letrec]
Enable fully R5RS compliant \texttt{letrec}. This generates slightly less
efficient code but preserves standard semantics.

\item[-to-stdout]
Write compiled code to standard output instead of creating a \texttt{.c} file.

\item[-unit NAME]
Compile this file as a library unit. Equivalent to 

\begin{verbatim}
-prelude "(declare (unit NAME))"
\end{verbatim}

\item[-visit FILENAME]
Reads the source-file \texttt{FILENAME} and performs macro-expansions.
This makes macros/syntax, constant- and inline-function definitions defined in that file available 
without actually compiling the code. 

\item[-unsafe]
Disable runtime safety checks.

\item[-uses NAME]
Use definitions from the library unit \texttt{NAME}. This is equivalent to

\begin{verbatim}
-prelude "(declare (uses NAME))"
\end{verbatim}

\item[-usual-integrations]
Specifies that standard procedures and certain internal procedures are
never redefined, and can be inlined. This is equivalent to declaring
\texttt{(usual-integrations)}.

\item[-version]
Prints the version and some copyright information and exit the compiler.

\item[-verbose]
Prints progress information to standard output during compilation.

\end{description}

The environment variable \texttt{CHICKEN\_OPTIONS} can be set to a string
with default command-line options for the compiler.

\section{Runtime options}

After successful compilation a C source-file is generated and can be
compiled with a C compiler. Executables generated with CHICKEN (and the
compiler itself) accept a small set of runtime options:

\begin{description}
\item[-:?]
Shows a list of the available runtime options and exits the program.

\item[-:c]
Forces console mode. Currently this is only used in the interpreter
(\texttt{csi}) to force output of the \textbf{$>>>$} prompt even if stdin
is not a terminal (for example if running in an \texttt{emacs} buffer
under Windows).

\item[-:d]
Prints some debug-information during startup.

\item[-:hNUMBER]
Specifies fixed heap size

\item[-:hiNUMBER]
Specifies the initial heap size

\item[-:hgPERCENTAGE]
Sets the growth rate of the heap in percent. If the heap is exhausted,
then it will grow by \texttt{PERCENTAGE}.
The default is 200.

\item[-:hsPERCENTAGE]
Sets the shrink rate of the heap in percent. If no more than a quarter
of \texttt{PERCENTAGE} of the heap is used, then it will shrink to
\texttt{PERCENTAGE}. The default is 50.  Note: If you want to make sure
that the heap never shrinks, specify a value of \texttt{0}.  (this can
be useful in situations where an optimal heap-size is known in advance).

\item[-:sNUMBER]
Specifies stack size

\item[-:tNUMBER]
Specifies symbol table size

\item[-:w]
Enables garbage collection of unused symbols. By default unused and
unbound symbols are not garbage collected.

\item[-:r]
Writes trace output to stdout. This option has no effect with
in files compiled with the \texttt{-no-trace} or \texttt{-debug-level 0}
options.

\end{description}

The argument values may be given in bytes, in kilobytes (suffixed with
\texttt{K} or \texttt{k}) or in megabytes suffixed with \texttt{M}
or \texttt{m}). Runtime options may be combined, like \texttt{-:dc},
but everything following a \texttt{NUMBER} argument is ignored. So
\texttt{-:wh64m} is OK, but \texttt{-:h64mw} will not enable GC of
unused symbols.


\section{An example}

To compile a Scheme program (assuming a UNIX-like environment) we perform
the following steps:

\begin{itemize}

\item Consider this Scheme source file, named \texttt{foo.scm}
\begin{verbatim}
  ;;; foo.scm

  (define (fac n)
    (if (zero? n)
        1
        (* n (fac (- n 1))) ) )

  (write (fac 10))
  (newline)
\end{verbatim}

\item Compile the file \texttt{foo.scm}
\begin{verbatim}
% chicken foo.scm
\end{verbatim}

\item Compile the generated C file \texttt{foo.c}
\begin{verbatim}
% gcc foo.c -o foo `chicken-config -cflags -libs`
\end{verbatim}

\item Start the compiled program
\begin{verbatim}
% foo
\end{verbatim}
\begin{verbatim}
3628800
\end{verbatim}

\end{itemize}


If multiple bodies of Scheme code are to be combined into a single
executable, then we have to compile each file and link the resulting
object files together with the runtime system: 

\begin{itemize}

\item Consider these two Scheme source files, named \texttt{foo.scm}
and \texttt{bar.scm}

\begin{verbatim}
  ;;; foo.scm

  (declare (uses bar))

  (write (fac 10)) (newline)


  ;;; bar.scm

  (declare (unit bar))

  (define (fac n)
    (if (zero? n)
        1
        (* n (fac (- n 1))) ) )
\end{verbatim}

\item Compile the files \texttt{foo.scm} and \texttt{bar.scm}
\begin{verbatim}
% chicken foo.scm
% chicken bar.scm -explicit-use
\end{verbatim}

\item Compile the generated C files \texttt{foo.c} and \texttt{bar.c}
\begin{verbatim}
% gcc -c foo.c `chicken-config -cflags`
% gcc -c bar.c `chicken-config -cflags`
\end{verbatim}

\item Link the object files \texttt{foo.o} and \texttt{bar.o}
\begin{verbatim}
% gcc foo.o bar.o -o foo `chicken-config -libs`
\end{verbatim}

\item Start the compiled program
\begin{verbatim}
% foo
3628800

\end{verbatim}

\end{itemize}


The declarations specify which of the compiled files is the main
module, and which is the library module. An executable can only have
one main module, since a program has only a single entry-point. In this
case \texttt{foo.scm} is the main module, because it doesn't have a
\texttt{unit} declaration.


Extensions to the basic CHICKEN runtime libraries are available in a
separate utility library (\textbf{libsrfi-chicken.[a|so]}
and \texttt{libstuffed-chicken.[a|so]} on UNIX-like platforms,
\texttt{libsrfi-chicken.lib} and \texttt{libstuffed-chicken.lib} on Windows
systems). Whenever you use one or more of the units \texttt{extras,
format, srfi-1, srfi-4, srfi-13, srfi-14, srfi-18, srfi-25, srfi-37,
posix, script-utils, lolevel, tinyclos} or \texttt{regex}, then you
should add these library to the command line of the C compiler or
linker (this is equivalent to adding the \texttt{-extra-libs} option
to \texttt{chicken-config}):

\begin{verbatim}
  ;;; foo.scm

  (declare (uses posix format))

  (format #t "Anno Domini ~@R~%" 
        (+ 1900 (vector-ref (seconds->local-time (current-seconds)) 5))

  % chicken foo.scm
  % gcc foo.c `chicken-config -cflags -extra-libs -libs` -o foo
  % foo
\end{verbatim}


\section{Extending the compiler}


The compiler supplies a couple of hooks to add user-level passes to the
compilation process. Before compilation commences any Scheme source-files
or compiled code specified using the \texttt{-extend} option are loaded
and evaluated.  The parameters \texttt{user-options-pass, user-read-pass,
user-preprocessor-pass, user-pass, user-pass-2} and \texttt{user-post-analysis-pass} can be set
to procedures that are called to perform certain compilation passes
instead of the usual processing (for more information about parameters
see: \ref{parameters}.

\begin{description}

\item[{[}parameter{]} user-options-pass]
Holds a procedure that will be called with a list of command-line
arguments and should return two values: the source-filename and the actual
list of options, where compiler switches have their leading \texttt{-}
(hyphen) removed and are converted to symbols.  Note that this parameter
is invoked \textbf{before} processing of the \texttt{-extend} option,
and so can only be changed in compiled user passes.

\item[{[}parameter{]} user-read-pass]
Holds a procedure of three arguments. The first argument is a list
of strings with the code passed to the compiler via \texttt{-prelude}
options. The second argument is a list of source files including any files
specified by \texttt{-prologue} and \texttt{-epilogue}. The third argument
is a list of strings specified using \texttt{-postlude} options. The
procedure should return a list of toplevel Scheme expressions.

\item[{[}parameter{]} user-preprocessor-pass]
Holds a procedure of one argument. This procedure is applied
to each toplevel expression in the source file \textbf{before}
macro-expansion. The result is macro-expanded and compiled in place of
the original expression.

\item[{[}parameter{]} user-pass]
Holds a procedure of one argument. This procedure is applied to each
toplevel expression \textbf{after} macro-expansion.  The result of the
procedure is then compiled in place of the original expression.

\item[{[}parameter{]} user-pass-2]
Holds a procedure of two arguments, which is called with the canonicalized
node-graph and the analysis database as arguments. The result is ignored,
so this pass has to mutate the node-structure to cause any effect.

\item[{[}parameter{]} user-post-analysis-pass]
Holds a procedure that will be called after the
last performed program analysis. The procedure (when defined) will be
called with three arguments: the program database, a getter and a 
setter-procedure which
can be used to access and manipulate the program database, which
holds various information about the compiled program. The getter procedure
should be called with two arguments: a symbol representing the
binding for which information should be retrieved, and a symbol
that specifies the database-entry. The current value of the database
entry will be returned or \texttt{\#f}, if no such entry is
available. The setter procedure is called with three arguments: the
symbol and key and the new value.

For information about the contents of the program database contact
the author.

\end{description}

Loaded code (via the \texttt{-extend} option) has access to the library
units \texttt{extras, srfi-1, srfi-4, script-utils, regex} and the pattern matching macros. 
The highlevel macro-system and multithreading is not available.


Note that the macroexpansion/canonicalization phase of the compiler adds
certain forms to the source program.  These extra expressions are not
seen by \texttt{user-preprocessor-pass} but by \texttt{user-pass}.


\section{Distributing compiled C files}

It is relatively easy to create distributions of Scheme projects that
have been compiled to C.  The runtime system of CHICKEN consists of only
two handcoded C files (\texttt{runtime.c} and \texttt{chicken.h}). All
other modules of the runtime system and the extension libraries are just
compiled Scheme code.

An example:

\begin{itemize}
\item Consider these two source files:

\begin{verbatim}
;;; foo.scm

(declare (uses bar))

(say-hello)
\end{verbatim}

and

\begin{verbatim}
;;; bar.scm

(declare (unit bar) (uses posix))

(define (say-hello)
  (print "Hello, " (nth-value 0 (user-information (current-user-id)))) )
\end{verbatim}

\item Compiling them yields two C files:

\begin{verbatim}
% chicken foo.scm -quiet
% chicken bar.scm -quiet -explicit-use
\end{verbatim}

\item The makefile for generating the executable \texttt{foo} would look
like this:

\begin{verbatim}
CC = gcc
CFLAGS = -I. -O3 -fomit-frame-pointer -fstrict-aliasing

foo : foo.o bar.o libchicken.a libsrfi-chicken.a libstuffed-chicken.a
        gcc -s -L. foo.o bar.o -o $@ -lchicken -lsrfi-chicken -lstuffed-chicken
foo.o : foo.c chicken.h
bar.o : bar.c chicken.h

libchicken.a : runtime.o library.o eval.o syntax-case.o
        ar rus $@ $^
libsrfi-chicken.a : srfi-1.o srfi-4.o srfi-13.o srfi-14.o scheduler.o srfi-18.o srfi-25.o srfi-37.o
        ar rus $@ $^
libstuffed-chicken.a : extras.o format.o match-support.o lolevel.o regex.o posix.o script-utils.o tcp.o
        ar rus $@ $^
runtime.o : runtime.c chicken.h
eval.o : eval.c chicken.h
library.o : library.c chicken.h
extras.o : extras.c chicken.h
srfi-1.o : srfi-1.c chicken.h
srfi-4.o : srfi-4.c chicken.h
match-support.o : match-support.c chicken.h
syntax-case.o : syntax-case.c chicken.h
srfi-18.o : srfi-18.c chicken.h
scheduler.o : scheduler.c chicken.h
format.o : format.c chicken.h
tinyclos.o : tinyclos.c chicken.h
srfi-13.o : srfi-13.c chicken.h
srfi-14.o : srfi-14.c chicken.h
srfi-25.o : srfi-25.c chicken.h
srfi-37.o : srfi-37.c chicken.h
lolevel.o : lolevel.c chicken.h
regex.o : regex.c chicken.h
posix.o : posix.c chicken.h
script-utils.o : script-utils.c chicken.h
tcp.o : tcp.c chicken.h
\end{verbatim}

\item If CHICKEN was properly installed, then the C files needed can be
found in the directory \texttt{\$(CHICKEN\_HOME)/src} (or just take them
from the original \textbf{tar} archive).  Don't forget \texttt{chicken.h}.

\item Some of the libraries created during the build process might not be
needed. In this case it is safe to remove the associated rules from the
makefile. Most of the time not all library units are needed for a given application.
For the example above, a minimal makefile would look like this:

\begin{verbatim}
CC = gcc
CFLAGS = -I. -O3 -fomit-frame-pointer -fstrict-aliasing

foo : foo.o bar.o libchicken0.a libstuffed-chicken0.a
        gcc -s -L. foo.o bar.o -o $@ -lchicken0 -lstuffed-chicken0
foo.o : foo.c chicken.h
bar.o : bar.c chicken.h

libchicken0.a : runtime.o library.o eval.o
        ar rus $@ $^
libstuffed-chicken0.a : posix.o regex.o extras.o script-utils.o
        ar rus $@ $^
runtime.o : runtime.c chicken.h
eval.o : eval.c chicken.h
library.o : library.c chicken.h
posix.o : posix.c chicken.h
regex.o : regex.c chicken.h
extras.o : extras.c chicken.h
script-utils.o : script-utils.c chicken.h
\end{verbatim}

\item Most library units can be used independently. Here is a table that
shows library units that depend on other library units:
\begin{tabular}{|ll|}
\hline
format&extras\\
srfi-13&srfi-14\\
lolevel&extras\\
tinyclos&extras\\
posix&extras regex script-utils\\
script-utils&extras regex\\
srfi-18&scheduler\\
tcp&extras scheduler\\
\hline \end{tabular}

In the example above \texttt{bar} uses \texttt{posix}.  The units
\texttt{library} and \texttt{eval} are used by \texttt{foo} (these are
used by default).  The file \texttt{runtime.c} is needed in any case.

\end{itemize}


\chapter{Extensions and \texttt{csi -setup}}

To simplify the management of extension libraries, a simple mechanism
based on shared object files and dynamic loading is used to allow the
loading of extension libraries at run-time. Currently this mechanism is
only available on platforms that support dynamic loading of shared object
files, at the time of writing this is Linux, FreeBSD, HP/UX, Windows (Cygwin) and Solaris.
The macro \texttt{chicken-setup} is used to make packaging, building and
installation as simple as possible for the user.

An \emph{extension} is a compressed archive containing the source-code,
compilation parameters and additional information. Technically an
extension is a gzipped tar-archive, containing the source file (or a
directory hierarchy with source-files, in the case extensions containing
multiple modules)
and a \emph{setup} script with additional information.

The CHICKEN interpreter provides an option for performing basic
operations on extensions. To build and install an extension, enter

\begin{verbatim}
% csi -setup EXTENSION
\end{verbatim}

(Note that you have to have write-access for the directory
where system-wide extensions are installed. Normally this
directory is \texttt{/usr/local/lib/chicken}. You can create this
directory by entering \texttt{csi -setup} without additional
parameters.)

The registry will be created automatically on its first use.
Do create the registry explicitly, enter

\begin{verbatim}
csi -setup -init
\end{verbatim}

This will overwrite any existing registry (after asking the
user for confirmation). This may also be needed should
the extension-registry be damaged.

If you want to have your extensions installed at a different 
location than the default, you have two choices: either set
the environment-variable \texttt{CHICKEN\_REGISTRY} to the name
of your desired registry-directory, or create a directory named
\texttt{\$HOME/.chicken-registry}.

To ``wrap'' up an extension, that is, to create a packaged archive
ready for distribution, enter

\begin{verbatim}
% csi -setup EXTENSION -wrap
\end{verbatim}

The \texttt{-setup} option loads the setup-script
\texttt{EXTENSION.setup} and passes any arguments that follow the
extension-name as command-line arguments.

A setup-script is a normal Scheme-program, which should contain an
invocation of the \texttt{chicken-setup} macro, like this:

\begin{verbatim} 
(chicken-setup (command-line-arguments) SPEC ...)
\end{verbatim}

\begin{description}

\item[{[}syntax{]} (chicken-setup ARGUMENTS SPEC ...)]
Installs or wraps extension libraries with the specifications
\texttt{SPEC ...}. \texttt{ARGUMENTS} should be a list of
strings, where the string may be one of the following:

\begin{itemize}

\item[-b -build --build]
Builds the extension by compiling any provided source files.

\item[-i -install --install]
Installs the extension. You might have to have
root-privileges, if the registry of installed extensions
is located in a system-directory. The extension will be built,
if it isn't already.

\item[-w -wrap --wrap]
Creates an archive from all source files and the setup-script.
If the extension contains more than a single source file, then
there must exist a directory with the same name as the extension,
which all source files.

\end{itemize}

If no argument is given, then the extension will be extracted, built
and installed in one step.

\texttt{SPEC} is a \emph{setup-specification} that describes
the structure and attributes of the extension:

\begin{verbatim}
(EXTENSION-NAME
  (ATTRIBUTE ...)
  SUBMODULE ...) )
\end{verbatim}

\begin{itemize}
\item \texttt{EXTENSION-NAME} is a symbol naming the extension.

\item \texttt{ATTRIBUTE} is a list with one or more elements, where the
first element must be a symbol naming an extension attribute.

\item \texttt{SUBMODULE} is again an setup-specification of a nested extension-module.
\end{itemize}

The following attributes are allowed:

\begin{description}

\item[(author STRING)]
The name of the author of the module.

\item[(license STRING)]
The type of license this module is distributed under.

\item[(comment STRING ...)]
Additional comments.

\item[(syntax)]
\item[(source)]
Marks this module as source, that is, it is not compiled. Use
this attribute for syntax/macro modules.

\item[(file STRING)]
If the module (or sub-module) has a different filename than the
module-name, then the actual filename is declared using this property.

\item[(make STRING-OR-EXP)]
Defines the command used to build the module. This defaults to an
invocation of the compiler-script \texttt{csc} with the appropriate arguments
and options to build the shared library object.
The argument may also be a Scheme expression that is evaluated to
build the current module.

\item[(when EXP)]
If the evaulation of \texttt{EXP} returns \texttt{\#f}, then this
module will not be built.

\item[(options STRING ...)]  Sets the compiler options for Scheme files
that are to be compiled using \texttt{csc}.

\item[(c-options STRING ...)]  Sets the C-compiler options for Scheme
files that are to be compiled using \texttt{csc}.

\item[(link-options STRING ...)]  Sets the linker options for Scheme
files that are to be compiled using \texttt{csc}.

\item[(require EXTENSION ...)]  Lists extensions that are required by
the current module.

\item[(require-for-syntax EXTENSION ...)]  Lists extensions that are
required at compile-time by the current module.

\item[(require-at-runtime EXTENSION ...)] Lists extensions that are
required at runtime to support a syntax-extension. This means that
an expansion of 

\begin{verbatim}
(require-for-syntax EXT)
\end{verbatim}

where \texttt{EXT} is defined with a specification that contains an
attribute like

\begin{verbatim}
(require-at-runtime EXTR1 EXTR2)
\end{verbatim}

will result in this code

\begin{verbatim}
(require 'EXTR1 'EXTR2)
\end{verbatim}

\item[(provide EXTENSION)] Declares the given extensions as aliases for
the current extension.

\end{description}

\end{description}

As an example, we take two simple extensions: an implementation of
red-black trees and a simple ``functor''-like syntax that encapsulates
the operations on the rb-tree data-type. The files for an extension
should reside in a separate directory, so in the case of our simple
functor-implementations we have the following directory-structure:

\begin{verbatim}
functor.scm
functor/
  utils.scm
\end{verbatim}

Here we put the macro-definition for \texttt{define-functor}
in a separate file, this simplifies the use in compiled code.
The code follows:

\begin{verbatim}
;;; functor.scm

(require 'srfi-1)
(require-for-syntax 'match)

(define-macro (define-functor name imports . body)
  (let ([exports 
         (filter-map
          (match-lambda
            [('define (name . llist) . body) name]
            [('define name val) name] 
            [_ #f] )
          body) ] )
    `(define (,name ,@imports)
       ,@body
       (values ,@exports) ) ) )

\end{verbatim}

and

\begin{verbatim}
;;; functor/utils.scm

(define (instantiate-functor f . imports)
  (apply f imports) )
\end{verbatim}

One more thing is needed: a \emph{setup specification} that
contains information about the files and settings of the
extension. In this case we have:

\begin{verbatim}
;;; functor.setup

(chicken-setup (command-line-arguments)
  (functor ((syntax)
            (require-at-runtime (functor utils)) )
    (utils ()) ) )
\end{verbatim}

Now we create an extension package:

\begin{verbatim}
% csi -setup functor -wrap
wrapping extension `functor' ...
functor.setup
functor.scm
functor/
functor/utils.scm
\end{verbatim}

This will create the compressed archive \texttt{functor.egg}.

A user of this package can now use \texttt{csi} in combination with
the \texttt{-setup} option to extract the contents from the archive, to build its components
and install it in his Chicken system for easy use.

\begin{verbatim}
% ls
functor.egg
% csi -setup functor -build
extracting files from extension `functor' ...
functor.setup
functor.scm
functor/
functor/utils.scm
building extension `functor' ...
backing up registry...
adding entry for `/home/felix/chicken/lib/functor.setup' ...
compiling: csc -s ./functor/utils.scm -o ./functor/utils.so -O1 
removing temporary extension `/home/felix/chicken/lib/functor.setup' ...
restoring registry
\end{verbatim}

Note that \texttt{functor.scm} is not compiled, because
it is explicitly marked as \texttt{syntax}, which means it is only
meant to be used at compile-time, in source-form.

The extension is now installed and ready for use.

\begin{verbatim}
% csi -quiet
>>> (require-for-syntax 'functor)
; loading /home/felix/chicken/lib/functor.scm ...
; loading /home/felix/chicken/lib/functor/utils.so ...
>>> (define-functor adder (+) 
      (define (make-adder init)
        (lambda (x)
          (set! init (+ init x))
          init) ) )
>>> (define ma (instantiate-functor adder +))
>>> (define a1 (ma 99))
>>> (a1 1)
100
>>> (a1 22)
122
>>>
\end{verbatim}

The extension for red/black trees is created in much the same way:

\begin{verbatim}
;;; rbtree.scm
;
; taken directly from Chris Okasaki's ``Purely functional Data Structures''

(require-for-syntax 'match)
(require-for-syntax 'functor)

(define-functor rb-tree (rb<?)

  (define (member? x t)
    (match t
      [() #f]
      [(_ a y b) 
       (cond [(rb<? x y) (member? x a)]
             [(rb<? y x) (member? x b)]
             [else #t] ) ] ))

  (define balance
    (match-lambda
      [(or ('black ('red ('red a x b) y c) z d)
           ('black ('red a x ('red b y c)) z d)
           ('black a x ('red ('red b y c) z d))
           ('black a x ('red b y ('red c z d))) )
       `(red (black ,a ,x ,b) ,y (black ,c ,z ,d)) ]
      [body body] ) )

  (define (insert x s)
    (define ins
      (match-lambda
        [() `(red () ,x ())]
        [(and s (color a y b))
         (cond [(rb<? x y) (balance (list color (ins a) y b))]
               [(rb<? y x) (balance (list color a y (ins b)))]
               [else s] ) ] ) )
    (match (ins s)
      [(_ a y b) `(black ,a ,y ,b)] ) ) )
\end{verbatim}

The setup-specification looks like this. Since we only have a single file,
we don't need to put it in a separate directory:

\begin{verbatim}
(chicken-setup (command-line-arguments)
  (rb-tree ((options "-O2")
            (file "rbtree.scm")
            (require-for-syntax functor match) ) ) )
\end{verbatim}

Note the properties used: \texttt{(options "-O2")} overrides the
default compiler-options (\texttt{"-O1"}) and we use a different
name for the source-file\footnote{just for the heck of it}.
This extension requires the \texttt{define-functor} extension,
we have to use \texttt{require-for-syntax} to make sure
that the macro is included at compile-time.

The wrapping, unwrapping, building and installation works
identical to the previously given example. Here is some code
that uses both extensions:

\begin{verbatim}
% cat testrb.scm
(require 'rb-tree 'srfi-1 'extras)
(require '(functor utils))

(define-values (num-rb-member? num-rb-balance num-rb-insert)
  (instantiate-functor rb-tree <) )

(randomize)
(print "building list...")
(define vals (list-tabulate 10000 (lambda (_) (random 100000))))

(print "building rb-tree...")
(define t1 '())
(for-each (lambda (n) (set! t1 (num-rb-insert n t1))) vals)

(print "building hash-table...")
(define ht (make-hash-table))
(for-each (lambda (n) (hash-table-set! ht n #t)) vals)

(print "linear list:")
(time (every (lambda (n) (memq n vals)) vals))

(print "hash-table:")
(time (every (lambda (n) (hash-table-ref ht n)) vals))

(print "rb:")
(time (every (lambda (n) (num-rb-member? n t1)) vals))
% csc testrb.scm -O2
% testrb
building list...
building rb-tree...
building hash-table...
linear list:
    1.74 seconds elapsed
       0 seconds in GC
       0 mutations
     161 minor GCs
       0 major GCs
hash-table:
    0.03 seconds elapsed
       0 seconds in GC
       0 mutations
     779 minor GCs
       0 major GCs
rb:
    0.27 seconds elapsed
    0.02 seconds in GC
       0 mutations
    4684 minor GCs
       0 major GCs
\end{verbatim}

A special case of extensions is one that consists only of a single source
file and which doesn't provide any additional syntax definitions. In this case, we can 
build and install the extensions simply by entering:

\begin{verbatim}
% csi -setup foo
\end{verbatim}

where \texttt{foo.scm} is the name of the source file containing the code.

It should be noted that the extension-mechanism does not address any
namespace-issues. It is recommended to use the \texttt{export} declaration-
specifier to export toplevel names that are to be used by client code. This
will hide module-local definitions. Prefixing exported names with something
like \texttt{<extension-name>:<definition>} avoids
namespace-collisions with other libraries and names of client code.


\chapter{Using the interpreter}


CHICKEN provides an interpreter for evaluating Scheme programs
and expressions.  This interpreter can be used on its own and a simple
read-eval-print loop is provided in the file \texttt{csi.scm}.

\section{Command line format}

\texttt{csi \{FILENAME|OPTION\}}

where \texttt{FILENAME} specifies a file with Scheme source-code.  If the
extension of the source-file is \texttt{.scm}, it may be omitted. The
runtime options described in \ref{compileroptions} are also available
for the interpreter.  If the environment variable \texttt{CSI\_OPTIONS}
is set to a list of options, then these options are additionally passed
to every direct or indirect invocation of \texttt{csi}. Please note that
runtime options (like \texttt{-:...}) can not be passed using this method.
The options recognized by the interpreter are:

\begin{description}

\item[--]
Ignore everything on the command-line following this marker. Runtime
options (``\texttt{-:...}'') are still recognized.

\item[-case-sensitive]
Enables the reader to read symbols case sensitive. The default is to read
non case sensitive.  This option registers the \texttt{case-sensitive}
feature identifier.

\item[-batch]
Quit the interpreter after processing all command line options.

\item[-eval EXPRESSIONS]
Evaluate \texttt{EXPRESSIONS}.

\item[-feature SYMBOL]
Registers \texttt{SYMBOL} to be a valid feature identifier for
\texttt{cond-expand}.

\item[-help]
Write a summary of the available command line options to standard ouput
and exit.

\item[-hygienic]
Load \textbf{syntax-case} macro package and enable high-level macros in
interpreted code.  This option registers the \texttt{hygienic-macros}
feature identifier.

\item[-include-path PATHNAME]
Specifies an alternative search-path for files included via the
\texttt{include} special form. This option may be given multiple times. If
the environment variable \texttt{CHICKEN\_INCLUDE\_PATH} is set, it
should contain a list of alternative include pathnames separated by
\textbf{``;''}. The environment variable \texttt{CHICKEN\_HOME} is also
considered as a search path.

\item[-keyword-style STYLE]
Enables alternative keyword syntax, where \texttt{STYLE} may be either
\texttt{prefix} (as in Common Lisp) or \texttt{suffix} (as in DSSSL).
Any other value is ignored.

\item[-no-feature SYMBOL]
Unregisters feature identifier \texttt{SYMBOL}.

\item[-no-init]
Do not load initialization-file. If this option is not given and the file
\texttt{~/.csirc} exists, then it is loaded before the read-eval-print
loop commences.

\item[-no-warnings]
Disables any warnings that might be issued by the reader or evaluated code.

\item[-quiet]
Do not print a startup message.

\item[-script PATHNAME]
This is equivalent to \texttt{-batch -quiet -no-init
PATHNAME}. Arguments following \texttt{PATHNAME} are available by using
\texttt{command-line-arguments} and are not processed as interpreter
options.

\item[-script-meta PATHNAME]
This is similar to the \texttt{-script} option, but the file specified
by \texttt{PATHNAME} is opened, the first line is treated as containing
additional command line options and (after processing all the options)
the code from the given file is loaded.

\item[-srfi-7]
Process any source files as SRFI-7 configuration language.  (see: the
SRFI-7 document\urlfootnote{http://srfi.schemers.org/srfi-7/srfi-7.html})

\item[-strict]
Disable non-standard macros.

\item[-strict-srfi-0]
Disable non-standard macros except \texttt{cond-expand}.

\item[-strict-reader]
Disables non-standard read syntax.

\item[-strict-letrec]
Enable fully R5RS compliant \texttt{letrec}. This generates slightly less
efficient code but preserves standard semantics.

\item[-version]
Write the banner with version information to standard output and exit.

\item[-visit FILENAME]
Reads the source-file \texttt{FILENAME} and performs macro-expansions.
This makes macros defined in that file available without actually
loading the code.

\item[-setup EXTENSION | OPTION ... ARG1 ...]
Extracts, builds and/or installs a setup script.

\end{description}

\section{Writing Scheme scripts}

\begin{itemize}
\item Since UNIX shells use the \textbf{\#!} notation for starting scripts,
the interpreter registers the special read-syntax \texttt{\#!} as a
comment and the reader ignores everything after the two characters up
to the end of the current line.

The easiest way is to use the \texttt{-script} option like this:

\begin{verbatim}
% cat foo
#! /usr/local/bin/csi -script
(print (eval (with-input-from-string (car (command-line-arguments)) read)))

% chmod +x foo
% foo "(+ 3 4)"
7
\end{verbatim}

The parameter \texttt{command-line-arguments} is set to a list of the
parameters that were passed to the Scheme script.  Scripts can be compiled
to standalone executables (don't forget to declare used library units).
Note that the compiler does \textbf{not} parse the extra arguments passed
to a script via the \texttt{-script-meta} option!

To overcome a limitation of UNIX that allows only a single argument to
scripts, the \texttt{-script-meta} options is provided:


\begin{verbatim}
% cat foo
#! /usr/local/bin/csi -script-meta
-case-sensitive
(print (with-input-from-string (car (command-line-arguments)) read))

% chmod +x foo
% foo "FooBar"
"FooBar"
\end{verbatim}

\item CHICKEN implements SRFI-22 and provides the Scheme script
interpreters \texttt{scheme-r4rs, scheme-ieee-1178-1990, scheme-r5rs,
scheme-srfi-0} and \texttt{scheme-srfi-7}.  Scheme scripts can be
compiled, the compiler determines language dialect from the invocation
line:

\begin{verbatim}
% cat bar
#! /usr/bin/env scheme-r5rs
(define (main args)
  (write (list->string (reverse (string->list (cadr args)))))
  (newline) )

% chmod +x bar
% bar "one two three"
"eerht owt eno"
% chicken bar -quiet
% gcc bar.c `chicken-config -cflags -libs` -o cbar
% cbar "one two three"}
"eerht owt eno"
\end{verbatim} 

\textbf{Note:} The Scheme script interpreters \texttt{scheme-r5rs} and
\texttt{scheme-srfi-0} invoke the CHICKEN interpreter (\texttt{csi})
with the \texttt{-hygienic} option, which installs the highlevel macro
definitions. This will result in slightly longer startup times for
these scripts than for, say, scripts invoked via \texttt{scheme-r4rs}.
Compiling the script to native code will of course eliminate the problem.

The additional script interpreters \texttt{scheme-chicken-hygienic} and \texttt{scheme-chicken}
are provided,
which run \texttt{csi} in normal mode, with or without hygienic macros.

Compiled scheme scripts that invoke \texttt{scheme-chicken, scheme-chicken-hygienic} or \texttt{csi -script}
are automatically linked with all library modules that are normally available in the interpreter.

What follows is a list that shows what options are passed to \texttt{csi}
when the respective script interpreter is invoked:

{\tt
\begin{tabular}{|ll|}
\hline
scheme-chicken &\\
scheme-chicken-hygienic & -hygienic\\
scheme-r4rs & -strict\\
scheme-r5rs & -strict -hygienic\\
scheme-srfi-0 & -strict-srfi-0 -hygienic\\
scheme-srfi-7 & -strict -srfi-7 -hygienic\\
scheme-ieee-1178-1990 & -strict \\
\hline \end{tabular}}

(All script interpreters pass \texttt{-no-init -quiet -batch})

For more information, see the SRFI-22 document\urlfootnote{http://srfi.schemers.org/srfi-22/srfi-22.html}

\item Windows and DOS:

CHICKEN supports writing shell scripts in Scheme for these platforms as well,
using a slightly different approach. The first example would look like
this on Windows:

\begin{verbatim}
C:>type foo.bat
@;csibatch %0 %1 %2 %3 %4 %5 %6 %7 %8 %9
(print (eval (with-input-from-string (car (command-line-arguments)) read)))

C:>foo "(+ 3 4)"
7
\end{verbatim}

Like UNIX scripts, batch files can be compiled.

\end{itemize}

\section{Toplevel commands}

The toplevel loop understands a number of special commands:

\begin{description}
\item[,?]
Show summary of available toplevel commands.

\item[,NUM]
Evaluate \texttt{NUM}th command in history-list

\item[,h]
List history of last commands

\item[,l FILENAME]
Load file with given \texttt{FILENAME} (may be a symbol or string).

\item[,ln FILENAME]
Load file and print result(s) of each top-level expression.

\item[,p EXP]
Pretty-print evaluated expression \texttt{EXP}.

\item[,d EXP]
Describe result of evaluated expression \texttt{EXP}.

\item[,du EXP]
Dump contents of the result of evaluated expression \texttt{EXP}.

\item[,dur EXP N]
Dump \texttt{N} bytes of the result of evaluated expression \texttt{EXP}.

\item[,q]
Quit the interpreter.

\item[,r]
Show system information.

\item[,s STRING-OR-SYMBOL]
Execute shell-command.

\item[,t EXP]
Evaluate form and print elapsed time.

\item[,x EXP]
Pretty-print macroexpanded expression \texttt{EXP} (the expression is
not evaluated).

\end{description}

\section{Macros and procedures implemented in the interpreter}

The interpreter contains the definitions of the library units
\texttt{extras, srfi-1, srfi-4, srfi-18, srfi-37, lolevel, format,
regex, script-utils} and \texttt{syntax-case}.  If available, the units
\texttt{posix, chicken-setup} and \texttt{tcp} are also included.

Additional macros and procedures available in the interpreter are:

\begin{description}

\item[{[}syntax{]} (advise NAME MODE PROC)]
Modifies the behaviour of the procedures named \texttt{NAME}, according
to \texttt{MODE}:

\begin{description}
\item[before] 
Call the procedure \texttt{PROC} before every invocation of \texttt{NAME},
with the same arguments.

\item[after]
Call the procedure \texttt{PROC} with the result value(s) of \texttt{NAME}.

\item[around]
Call the procedure \texttt{PROC} with the arguments passed to
\texttt{NAME}.  Additionally the (original) value of \texttt{NAME}
is passed as the first argument to \texttt{PROC}.

\end{description}

Only the \texttt{PROC} argument is evaluated. Note that multiple pieces
of advice on the same procedure are allowed.

\begin{verbatim}
>>> (define (fac n)
      (if (zero? n) 1 (* n (fac (sub1 n)))))
>>> (define count 0)
>>> (advise fac before (lambda _ (set! count (add1 count))))
>>> (fac 10)                                                 ==> 3628800
>>> count                                                    ==> 11
>>> (advise fac around
      (let ((i 0))
        (define (indent)
          (do ((i i (sub1 i)))
              ((zero? i))
            (write-char #\space)))
      (lambda (f n)
        (indent)
        (print "fac: " n)
        (set! i (add1 i))
        (let ((x (f n)))
          (set! i (sub1 i))
          (indent)
          (print "-> " x)
          x))))
>>> (fac 3)
fac: 3
 fac: 2
  fac: 1
   fac: 0
   -> 1
  -> 1
 -> 2
-> 6                                                         ==> 6
>>> count                   ==> 15
>>> (set! count 0)
>>> (unadvise fac)
>>> (fac 10)                                                 ==> 3628800
>>> count           ==> 0
\end{verbatim}

\item[{[}syntax{]} (unadvise NAME ...)]
Removes all pieces of advice from the procedures \texttt{NAME ...}
and restores their original behaviour.

\item[{[}syntax{]} (trace NAME ...)]
Switches tracing on for the procedures with the given names.

\begin{verbatim}
>>> (fac 10)                       ==> 3628800
>>> (trace fac)
>>> (fac 3)
|(fac 3)
| (fac 2)
|  (fac 1)
|   (fac 0)
|   fac -> 1 
|  fac -> 1 
| fac -> 2 
|fac -> 6                          ==> 6
>>> (untrace fac)
>>> (fac 3)                        ==> 6
\end{verbatim}

\item[{[}syntax{]} (untrace NAME ...)]
Switches tracing of the given procedures off.

\item[{[}procedure{]} (\$ {[}INDEX{]})]
Returns entry number \texttt{INDEX} in the history list.

\item[{[}procedure{]} (\& {[}INDEX{]})]
Returns result(s) of entry number \texttt{INDEX} in the history list.

\end{description}


\chapter{Supported language}

\section{Deviations from the standard}

[6.2.4]  The runtime system uses the numerical string-conversion
routines of the underlying C library and so does only understand standard
(C-library) syntax for floating-point constants.

[6.2.5]  The routines \texttt{complex?}, \texttt{real?}
and \texttt{rational?} are identical to the standard procedure
\texttt{number?}. The procedures \texttt{numerator}, \texttt{denominator}
and \texttt{rationalize} are not implemented.  Also not implemented are
all procedures related to complex numbers.

[6.2.6] The procedure \texttt{string-$>$number} does not obey read/write
invariance on inexact numbers.

[6.5] Code evaluated in \texttt{scheme-report-environment} or
\texttt{null-environment} still sees non-standard syntax unless running
under the interpreter (\texttt{csi}) invoked with the \texttt{-strict}
option.

[6.6.2] The procedure \texttt{char-ready?} is handling terminal input
ports only under DJGPP correctly. On other platforms it returns always
\texttt{\#t}.  The procedure \texttt{read} does not obey read/write
invariance on inexact numbers.

[6.6.3] The procedures \texttt{write} and \texttt{display} do not obey
read/write invariance to inexact numbers.

\section{Extensions to the standard}

[2.1] Identifiers may contain special characters if delimited with
\texttt{| ... |}.

[2.3] The brackets \texttt{[ ... ]} are provided as an alternative syntax
for \texttt{( ... )}.  A number of reader extensions is provided. See
\ref{readsyntax}.

[4] Numerous non-standard macros are provided. See \ref{specialforms}
for more information.

[4.2.3] \texttt{(begin)} is allowed in non-toplevel contexts and evaluates
to an unspecified value.

[4.2.5] Delayed expressions may return multiple values.

[5.2.1]  A \texttt{define} occurring anywhere but at the beginning of
a \texttt{lambda}- or \texttt{let}-body is in every aspect equivalent
to \texttt{set!}.

[5.2.2] \texttt{define-values} may be used in internal definitions if
the R5RS macro system is not used.

[6] CHICKEN provides numerous non-standard procedures. See the manual
sections on library units for more information.

[6.3.4] User defined character names are supported. See
\texttt{char-name}.

[6.3.5]  CHICKEN supports special characters preceded with
a backslash ``\textbf{\textbackslash}'' in quoted string
constants. \texttt{\textbackslash n} denotes the newline-character and
\texttt{\textbackslash t} is equivalent to the TAB character.

[6.4] \texttt{force} called with an argument that is not a promise returns
that object unchanged.  Captured continuations can be safely invoked
inside before- and after-thunks of a \texttt{dynamic-wind} form and
execute in the outer dynamic context of the \texttt{dynamic-wind} form.

[6.5] The second argument to \texttt{eval} is optional and
defaults to the value of \texttt{(interaction-environment)}.
\texttt{scheme-report-environment} and \texttt{null-environment} accept
an optional 2nd parameter: if not \texttt{\#f} (whish is the default),
toplevel bindings to standard procedures are mutable and new toplevel
bindings may be introduced.

[6.6.1] if the procedures \texttt{current-input-port} and
\texttt{current-output-port} are called with an argument (which should
be a port), then that argument is selected as the new current input- and
output-port, respectively.  The procedures \texttt{open-input-file},
\texttt{open-output-file}, \texttt{with-input-from-file},
\texttt{with-output-to-file}, \texttt{call-with-input-file} and
\texttt{call-with-output-file} accept an optional second (or third)
argument which should be one or more keywords, if supplied. These
arguments specify the mode in which the file is opened. Possible
values are the keywords \texttt{\#:text}, \texttt{\#:binary} or
\texttt{\#:append}.

\section{Non standard read syntax} \label{readsyntax}

\begin{description}

\item[{[}read syntax{]} \#$|$ \ldots $|$\#]
A multiline ``block'' comment. May be nested. Implements SRFI-30
\urlfootnote{http://srfi.schemers.org/srfi-30/srfi-30.html})

\item[{[}read syntax{]} \#;EXPRESSION]
Treats \texttt{EXPRESSION} as a comment.

\item[{[}read syntax{]} \#,(CONSTRUCTORNAME DATUM ...)]
Allows user-defined extension of external representations.
(For more information see the documentation for
SRFI-10\urlfootnote{http://srfi.schemers.org/srfi-10/srfi-10.html})

\item[{[}read syntax{]} \#'EXPRESSION]
An abbreviation for \texttt{(syntax EXPRESSION)}.

\item[{[}read syntax{]} \#:SYMBOL]
Syntax for keywords. Keywords are symbols that evaluate to themselves,
and as such don't have to be quoted.

\item[{[}read syntax{]} \#{\tt<<}TAG]
Specifies a multiline string constant. Anything up to a line equal to
\texttt{TAG} will be returned as a single string:

\begin{verbatim}
(define msg \#<<END
"Hello, world!", she said.
END
)
\end{verbatim}
is equivalent to
\begin{verbatim}
(define msg "\"Hello, world!\", she said.")
\end{verbatim}

\item[{[}read syntax{]} \#{\tt<}\#TAG]
Similar to \texttt{\#<<}, but allows substitution of embedded Scheme
expressions prefixed with \texttt{\#} and optionally enclosed in
\texttt{\{ ...\ \}}.  Two consecutive \texttt{\#}s are translated to a
single \texttt{\#}:

\begin{verbatim}
(define three 3)
(display #<#EOF
This is a simple string with an embedded `##' character
and substituted expressions: (+ three 99) ==> #(+ three 99)
(three is "#{three}")
EOF
)
\end{verbatim}

prints

\begin{verbatim}
This is a simple string with an embedded `#' character
and substituted expressions: (+ three 99) ==> 102
(three is "3")
\end{verbatim}

\end{description}


\section{Non-standard macros and special forms} \label{specialforms}

\subsection{Binding forms for optional arguments}

\begin{description}

\item[{[}syntax{]} (:optional ARGS DEFAULT)]
Use this form for procedures that take a single optional argument. If
\texttt{ARGS} is the empty list \texttt{DEFAULT} is evaluated and
returned, otherwise the first element of the list \texttt{ARGS}. It is
an error if \texttt{ARGS} contains more than one value.

\begin{verbatim}
(define (incr x . i) (+ x (:optional i 1)))
(incr 10)                                   ==> 11
(incr 12 5)                                 ==> 17
\end{verbatim}

\item[{[}syntax{]} (case-lambda (LAMBDA-LIST1 EXP1 ...) ...)]
SRFI-16. Expands into a lambda that invokes the body following the first
matching lambda-list.

\begin{verbatim}
(define plus
  (case-lambda 
    (() 0)
    ((x) x)
    ((x y) (+ x y))
    ((x y z) (+ (+ x y) z))
    (args (apply + args))))

(plus)                      ==> 9
(plus 1)                    ==> 1
(plus 1 2 3)                ==> 6
\end{verbatim}

For more information see the documentation for
SRFI-16\urlfootnote{http://srfi.schemers.org/srfi-16/srfi-16.html}

\item[{[}syntax{]} (let-optionals ARGS ((VAR1 DEFAULT1) ...) BODY ...)]
\item[{[}syntax{]} (let-optionals* ARGS ((VAR1 DEFAULT1) ... [RESTVAR]) BODY ...)]
Binding constructs for optional procedure arguments. \texttt{ARGS} should
be a rest-parameter taken from a lambda-list. \texttt{let-optionals}
binds \texttt{VAR1 ...} to available arguments in parallel, or
to \texttt{DEFAULT1 ...} if not enough arguments were provided.
\texttt{let-optionals*} binds \texttt{VAR1 ...} sequentially, so every
variable sees the previous ones. If a single variable \texttt{RESTVAR}
is given, then it is bound to any remaining arguments, othersise it is
an error if any excess arguments are provided.

\begin{verbatim}
(let-optionals '(one two) ((a 1) (b 2) (c 3))
  (list a b c) )                               ==> (one two 3)
(let-optionals* '(one two) ((a 1) (b 2) (c a))
  (list a b c) )                               ==> (one two one)
\end{verbatim}

\end{description}

\subsection{Other binding forms}

\begin{description}

\item[{[}syntax{]} (and-let* (BINDING ...) EXP1 EXP2 ...)]
SRFI-2. Bind sequentially and execute body. \texttt{BINDING} can
be a list of a variable and an expression, a list with a single
expression, or a single variable. If the value of an expression
bound to a variable is \texttt{\#f}, the \texttt{and-let*} form
evaluates to \texttt{\#f} (and the subsequent bindings and the body
are not executed).  Otherwise the next binding is performed. If
all bindings/expressions evaluate to a true result, the body is
executed normally and the result of the last expression is the
result of the \texttt{and-let*} form. See also the documentation for
SRFI-2\urlfootnote{http://srfi.schemers.org/srfi-2/srfi-2.html}.

\item[{[}syntax{]} (cut SLOT ...)]
\item[{[}syntax{]} (cute SLOT ...)]
Syntactic sugar for specializing parameters.
\urlfootnote{http://srfi.schemers.org/srfi-26/srfi-26.html}

\item[{[}syntax{]} (define-values (NAME ...) EXP)]
Defines several variables at once, with the result values of expression
\texttt{EXP}.  This form may also be used in internal definitions unless
the highlevel (syntax-case) macro system is used.

\item[{[}syntax{]} (fluid-let ((VAR1 X1) ...) BODY ...)]
Binds the variables \texttt{VAR1 ...} dynamically to the values \texttt{X1
...} during execution of \texttt{BODY ...}.

\item[{[}syntax{]} (let-values (((NAME ...) EXP) ...) BODY ...)]
Binds multiple variables to the result values of \texttt{EXP ...}.
All variables are bound simultaneously.

\item[{[}syntax{]} (let*-values (((NAME ...) EXP) ...) BODY ...)]
Binds multiple variables to the result values of \texttt{EXP ...}.
The variables are bound sequentially.
\begin{verbatim}
(let*-values (((a b) (values 2 3))
              ((p) (+ a b)) )
  p)                               ==> 5
\end{verbatim}

\item[{[}syntax{]} (letrec-values (((NAME ...) EXP) ...) BODY ...)]
Binds the result values of \texttt{EXP ...} to multiple variables at once.
All variables are mutually recursive.
\begin{verbatim}
(letrec-values (((odd even)
                   (values 
                     (lambda (n) (if (zero? n) #f (even (sub1 n))))
                     (lambda (n) (if (zero? n) #t (odd (sub1 n)))) ) ) )
  (odd 17) )                                                             ==> #t
\end{verbatim}

\item[{[}syntax{]} (parameterize ((PARAMETER1 X1) ...) BODY ...)]
Binds the parameters \texttt{PARAMETER1 ...} dynamically to the values
\texttt{X1 ...} during execution of \texttt{BODY ...}.  (see also:
\texttt{make-parameter})

\item[{[}syntax{]} (receive (NAME1 ... {[}. NAMEn{]}) VALUEEXP BODY ...)]
SRFI-8. Syntactic sugar for \texttt{call-with-values}. Binds variables
to the result values of \texttt{VALUEEXP} and evaluates \texttt{BODY ...}.

\item[{[}syntax{]} (set!-values (NAME ...) EXP)]
Assigns the result values of expression \texttt{EXP} to multiple
variables.

\end{description}

\subsection{Substitution forms and macros}

\begin{description}

\item[{[}syntax{]} (define-constant NAME CONST)]
Define a variable with a constant value, evaluated at compile-time. 
Any reference to such a
constant should appear textually \textbf{after} it's definition. This
construct is equivalent to \texttt{define} when evaluated or interpreted.
Constant definitions should only appear at toplevel. Note that constants
are local to the current compilation unit and are not available outside
of the source-file in which they are defined. Names of constants still
exist in the Scheme namespace and can be lexically shadowed.  If the
value is mutable, then the compiler is careful to preserve its identity.

\item[{[}syntax{]} (define-id-macro NAME EXP)]
Defines a globally visible identifier macro. Every occurrence of
the variable \texttt{NAME} will be substituted by the expression
\texttt{EXP}. Note that \texttt{EXP} is not evaluated at macro-definition
time.  Only global identifier macros can be defined using this form.

\item[{[}syntax{]} (define-inline (NAME VAR ... [. VAR]) BODY ...)]
\item[{[}syntax{]} (define-inline NAME EXP)]
Defines an inline procedure. Any occurrence of \texttt{NAME} will be
replaced by \texttt{EXP} or \texttt{(lambda (VAR ... [. VAR]) BODY
...)}. This is similar to a macro, but variable-names and -scope will
be correctly handled.  Inline substitutions take place \textbf{after}
macro-expansion.  \texttt{EXP} should be a lambda-expression. Any
reference to \texttt{NAME} should appear textually \textbf{after}
it's definition. Note that inline procedures are local to the current
compilation unit and are not available outside of the source-file in
which they are defined. Names of inline procedures still exist in the
Scheme namespace and can be lexically shadowed.  This construct is
equivalent to \texttt{define} when evaluated or interpreted. Inline
definitions should only appear at toplevel.

\item[{[}syntax{]} (define-macro (NAME VAR ... [. VAR]) EXP1 ...)]
\item[{[}syntax{]} (define-macro NAME (lambda (VAR ... [. VAR]) EXP1 ...))]
Define a globally visible macro special form. The macro is available
as soon as it is defined, i.e. it is registered at compile-time. If
the file containing this definition invokes \texttt{eval}, then the
macro is visible in evaluated expressions during runtime. The second
possible syntax for \texttt{define-macro} is allowed for portability
purposes only. In this case the second argument \textbf{must} be a
lambda-expression.  Only global macros can be defined using this form.

This form is also available with the \texttt{syntax-case} macro
system.

\item[{[}syntax{]} (let-id-macro ((NAME EXP) ...) EXP1 ...)]
Defines an identifier macro. Every occurrence of the variable
\texttt{NAME} will be substituted by the expression \texttt{EXP}.
The defined identifier macros are only valid inside the body
\texttt{EXP1 ...}.  Note that the \texttt{EXP} forms are not evaluated
at macro-definition time.

\item[{[}syntax{]} (let-macro (MACRODEF ...) EXP1 ...)]
Defines locally scoped macros. \texttt{MACRODEF} may be of the form
\texttt{(NAME (lambda LAMBDALIST BODY ...))} or of the form \texttt{((NAME
. LAMBDALIST) BODY ...)}.  The defined macros are only valid inside the
body \texttt{EXP1 ...}.

\end{description}

\subsection{Conditional forms}

\begin{description}

\item[{[}syntax{]} (switch EXP (KEY EXP1 ...) ... {[}(else EXPn ...){]})]
This is similar to \texttt{case}, but a) only a single key is allowed,
and b) the key is evaluated.

\item[{[}syntax{]} (unless TEST EXP1 EXP2 ...)]
Equivalent to: 
\begin{verbatim}
(if (not TEST) (begin EXP1 EXP2 ...))
\end{verbatim}

\item[{[}syntax{]} (when TEST EXP1 EXP2 ...)]
Equivalent to:
\begin{verbatim}
(if TEST (begin EXP1 EXP2 ...))
\end{verbatim}

\end{description}

\subsection{Record structures}

\begin{description}

\item[{[}syntax{]} (define-record NAME SLOTNAME ...)]
Defines a record type. Call \texttt{make-NAME} to create an instance
of the structure (with one initialization-argument for each slot).
\texttt{(NAME? STRUCT)} tests any object for being an instance of this
structure.  Slots are accessed via \texttt{(NAME-SLOTNAME STRUCT)}
and updated using \texttt{(NAME-SLOTNAME-set!} \texttt{STRUCT}
\texttt{VALUE)}.

\begin{verbatim}
(define-record point x y)
(define p1 (make-point 123 456))
(point? p1)                      ==> #t
(point-x p1)                     ==> 123
(point-y-set! p1 99)
(point-y p1)                     ==> 99
\end{verbatim}

\item[{[}syntax{]} (define-record-printer (NAME RECORDVAR PORTVAR) BODY ...)]
\item[{[}syntax{]} (define-record-printer NAME PROCEDURE)]
Defines a printing method for record of the type \texttt{NAME} by
associating a procedure with the record type. When a record of this
type is written using \texttt{display, write} or \texttt{print}, then
the procedure is called with two arguments: the record to be printed
and an output-port.

\begin{verbatim}
(define-record foo x y z)
(define f (make-foo 1 2 3))
(define-record-printer (foo x out)
  (fprintf out "#,(foo ~S ~S ~S)" (foo-x x) (foo-y x) (foo-z x)) )
(define-reader-ctor 'foo make-foo)
(define s (with-output-to-string (lambda () (write f))))
s                                            ==> "#,(foo 1 2 3)"
(equal? f (with-input-from-string s read)))  ==> #t
\end{verbatim}

\texttt{define-record-printer} works also with SRFI-9 record types.

\item[{[}syntax{]} (define-record-type NAME (CONSTRUCTOR TAG ...) PREDICATE (FIELD ACCESSOR {[}MODIFIER{]}) ...)]
SRFI-9 record types. For more information see the documentation for
SRFI-9 \urlfootnote{http://srfi.schemers.org/srfi-9/srfi-9.html}

\end{description}

\subsection{Other forms}

\begin{description}

\item[{[}syntax{]} (assert EXP {[}STRING ARG ...{]})]
Signal error if \texttt{EXP} evaluates to false. An optional message
\texttt{STRING} and arguments \texttt{ARG ...} may be supplied to give a
more informative error-message.  If compiled in \emph{unsafe} mode (either
by specifiying the \texttt{-unsafe} compiler option or by declaring
\texttt{(unsafe)}), then this expression expands to an unspecified value.

\item[{[}syntax{]} (cond-expand FEATURE-CLAUSE ...)]
SRFI-0. Expands by selecting feature clauses. Predefined
feature-identifiers are \texttt{srfi-0}, \texttt{srfi-2}, \texttt{srfi-6},
\texttt{srfi-8}, \texttt{srfi-9}, \texttt{srfi-10},
 and \texttt{chicken}. In \texttt{strict-srfi-0} mode only \texttt{srfi-0}
and \texttt{chicken} are defined.  If the source-file containing
this form is currently compiled, the feature \texttt{compiling}
is defined.  For further information, see the documentation for
SRFI-0\urlfootnote{http://srfi.schemers.org/srfi-0/srfi-0.html} This form
is allowed to appear in non-toplevel expressions.

\item[{[}syntax{]} (critical-section BODY ...)]
Evaluate \texttt{BODY ...} with timer-interrupts temporarily disabled.

\item[{[}syntax{]} (ensure PREDICATE EXP {[}ARGUMENTS ...{]})]
Evaluates the expression \texttt{EXP} and applies the one-argument
procedure \texttt{PREDICATE} to the result. If the predicate returns
\texttt{\#f} an error is signaled, otherwise the result of \texttt{EXP}
is returned.  If compiled in \emph{unsafe} mode (either by specifiying
the \texttt{-unsafe} compiler option or by declaring \texttt{(unsafe)}),
then this expression expands to an unspecified value.  If specified,
the optional \texttt{ARGUMENTS} are used as arguments to the invocation
of the error-signalling code, as in \texttt{(error ARGUMENTS ...)}. If
no \texttt{ARGUMENTS} are given, a generic error message is displayed
with the offending value and \texttt{PREDICATE} expression.

\item[{[}syntax{]} (eval-when (SITUATION ...) EXP ...)]
Controls evaluation/compilation of subforms. \texttt{SITUATION} should
be one of the symbols \texttt{eval}, \texttt{compile} or \texttt{load}.
When encountered in the evaluator, and the situation specifier
\texttt{eval} is not given, then this form is not evaluated and an
unspecified value is returned.  When encountered while compiling code,
and the situation specifier \texttt{compile} is given, then this form is
evaluated at compile-time.  When encountered while compiling code, and the
situation specifier \texttt{load} is not given, then this form is ignored
and an expression resulting into an unspecified value is compiled instead.

Note: It is currently not possible to use \texttt{define-syntax} or
\texttt{define} inside \texttt{eval-when} forms when hygienic macros
are enabled.

\item[{[}syntax{]} (include STRING)]
Include toplevel-expressions from a given source-file in the currently
compiled/interpreted program.  If the included file has the extension
\texttt{.scm}, then it may be omitted.  The file is searched in the
current directory and, if not found, in all directories specified in the
\texttt{-include-path} option.  The expressions are treated as toplevel
expressions, so it's generally a good idea to use \texttt{include}
only in a toplevel context.

\item[{[}syntax{]} (nth-value N EXP)]
Returns the \texttt{N}th value (counting from zero) of the values returned
by expression \texttt{EXP}.

\item[{[}syntax{]} (time EXP1 ...)]
Evaluates \texttt{EXP1 ...} and print elapsed time and memory
information. The result of the last expression is returned.

\end{description}

\section{Declarations}

\begin{description}

\item[{[}syntax{]} (declare DECLSPEC ...)]
Process declaration specifiers. Declarations always override
any command-line settings.  Declarations are valid for the whole
compilation-unit (source file), the position of the declaration in
the source file can be arbitrary. \texttt{DECLSPEC} may be any of the
following:

\begin{description}

\item[{[}declaration specifier{]} (always-bound SYMBOL ...)]
Declares that the given variables are always bound and
accesses to those have not to be checked.

\item[{[}declaration specifier{]} (block)]
Assume global variables are never redefined. This is the same as
specifying the \texttt{-block} option.

\item[{[}declaration specifier{]} (block-global SYMBOL ...)]
\item[{[}declaration specifier{]} (hide SYMBOL ...)]
Declares that the toplevel bindings for \texttt{SYMBOL ...}
should not be accessible from code in other compilation units or by
\texttt{eval}. Access to toplevel bindings declared as block global is
also more efficient.

\item[{[}declaration specifier{]} (bound-to-procedure SYMBOL ...)]
Declares that the given identifiers are always bound to procedure values.

\item[{[}declaration specifier{]} (compile-time-macros-only)]
Equivalent to the compiler option of the same name - low-level
macros defined in the compiled code are not made available at
runtime.

\item[{[}declaration specifier{]} (compress-literals [THRESHOLD [INITIALIZER]])]
The same as the \texttt{-compress-literals} compiler option.
The threshold argument defaults to 50. If the optional argument \texttt{INITIALIZER}
is given, then the literals will not be created at module startup,
but when the procedure with this name will be called.

\item[{[}declaration specifier{]} (foreign-declare STRING ...)]
Include given strings verbatim into header of generated file.

\item[{[}declaration specifier{]} (interrupts-enabled)]
Enable timer-interrupts checks in the compiled program (the default).

\item[{[}declaration specifier{]} (disable-interrupts)]
\item[{[}declaration specifier{]} (not interrupts-enabled)]
Disable timer-interrupts checks in the compiled program. Threads can
not be preempted in main- or library-units that contain this declaration.

\item[{[}declaration specifier{]} (no-argc-checks)]
Disables argument count checking.

\item[{[}declaration specifier{]} (no-bound-checks)]
Disables the bound-checking of toplevel bindings.

\item[{[}declaration specifier{]} (no-procedure-checks)]
Disables checking of values in operator position for being of procedure type.

\item[{[}declaration specifier{]} (no-winding-callcc)]
Declares that all known uses of \texttt{call-with-current-continuation}
use non-winding semantics.  So any invocation of captured continuations
will not execute any pending before- or after-thunks.  This means that
the following forms should be used with care, since they expand into or
call \texttt{dynamic-wind}:

\begin{verbatim}
critical-section
dynamic-wind
fluid-let
with-exception-handler
handle-exceptions
condition-case
\end{verbatim}

\item[{[}declaration specifier{]} ([number-type] TYPE)]
\item[{[}declaration specifier{]} (fixnum-arithmetic)]
Declares that only numbers of the given type are used. \texttt{TYPE}
may be \texttt{fixnum} or \texttt{generic} (which is
the default).

\item[{[}declaration specifier{]} ({[}not{]} standard-bindings SYMBOL ...)]
Declares that all given standard procedures (or all if no symbols are
specified) are never globally redefined.  If \texttt{not} is specified,
then all but the given standard bindings are assumed to be never
redefined.

\item[{[}declaration specifier{]} ({[}not{]} extended-bindings SYMBOL ...)]
Declares that all given non-standard and CHICKEN-specific procedures
(or all if no symbols are specified) are never globally redefined.
If \texttt{not} is specified, then all but the given extended bindings
are assumed to be never redefined.

\item[{[}declaration specifier{]} ({[}not{]} usual-integrations SYMBOL ...)]
Declares that all given standard and extended bindings (or all if no
symbols are specified) are never globally redefined.  If \texttt{not}
is specified, then all but the given standard and extended bindings are
assumed to be never redefined.

\item[{[}declaration specifier{]} (unit SYMBOL)]
Specify compilation unit-name (if this is a library)

\item[{[}declaration specifier{]} (unsafe)]
\item[{[}declaration specifier{]} (not safe)]
Do not generate safety-checks. This is the same as specifying the
\texttt{-unsafe} option.  Also implies

\begin{verbatim}
(declare (no-bound-checks) (no-procedure-checks) (no-argc-checks))
\end{verbatim}

\item[{[}declaration specifier{]} (uses SYMBOL ...)]
Gives a list of used library-units. Before the toplevel-expressions
of the main-module are executed, all used units evaluate their
toplevel-expressions in the order in which they appear in this
declaration. If a library unit A uses another unit B, then B's toplevel
expressions are evaluated before A's.  Furthermore, the used symbols
are registered as features during compile-time, so \texttt{cond-expand}
knows about them.

\end{description}

\end{description}

\section{Interface to external functions and variables}

\subsection{Accessing external objects}

\begin{description}

\item[{[}syntax{]} (define-foreign-type NAME TYPE {[}ARGCONVERT {[}RETCONVERT{]}{]})]
Defines an alias for \texttt{TYPE}. \texttt{TYPE} may be a type-specifier
or a string naming a C type. The namespace of foreign type specifiers
is separate from the normal Scheme namespace.  The optional arguments
\texttt{ARGCONVERT} and \texttt{RETCONVERT} should evaluate to procedures
that map argument- and result-values to a value that can be transformed
to \texttt{TYPE}:

\begin{verbatim}
(declare (uses extras))

(define-foreign-type char-vector 
  nonnull-c-string
  (compose list->string vector->list)
  (compose list->vector string->list) )

(define strlen
  (foreign-lambda int "strlen" char-vector) )

(strlen '#(#\a #\b #\c))                      ==> 3

(define memset
  (foreign-lambda char-vector "memset" char-vector char int) )

(memset '#(#\_ #\_ #\_) #\X 3)                ==> #(#\X #\X #\X)
\end{verbatim}                 

Foreign type-definitions are only visible in the compilation-unit in which
they are defined, so use \texttt{include} to use the same definitions
in multiple files.

\item[{[}syntax{]} (define-foreign-variable NAME TYPE {[}STRING{]})]
Defines a foreign variable of name \texttt{NAME}. \texttt{STRING}
should be the real name of a foreign variable or parameterless macro. If
\texttt{STRING} is not given, then the variable name \texttt{NAME} will
be converted to a string and used instead. All references and assignments
(via \texttt{set!}) are modified to correctly convert values between
Scheme and C representation. This foreign variable can only be accessed
in the current compilation unit, but the name can be lexically shadowed.
Note that \texttt{STRING} can name an arbitrary C expression. If no
assignments are performed, then \texttt{STRING} doesn't even have to
specifiy an lvalue.

\begin{verbatim}
(declare
  (foreign-declare "enum { abc=3, def, ghi };") )

(define-macro (define-foreign-enum . items)
  `(begin
     ,@(map (match-lambda 
              [(name realname) `(define-foreign-variable ,name int ,realname)]
              [name `(define-foreign-variable ,name int)] )
     items) ) )

(define-foreign-enum abc def ghi)

ghi                               ==> 5
\end{verbatim}

\item[{[}syntax{]} (foreign-callback-lambda RETURNTYPE NAME ARGTYPE)]
This is similar to \texttt{foreign-lambda}, but also allows the called
function to call Scheme functions. See \ref{callbacks}.

\item[{[}syntax{]} (foreign-callback-lambda* RETURNTYPE ((ARGTYPE VARIABLE)
...) STRING ...)]  
This is similar to \texttt{foreign-lambda*}, but also allows the called
function to call Scheme functions. See \ref{callbacks}.

\item[{[}syntax{]} (foreign-lambda RETURNTYPE NAME ARGTYPE ...)]  Represents a
binding to an external routine. This form can be used in the position
of an ordinary \texttt{lambda} expression. \texttt{NAME} specifies the
name of the external procedure and should be a string or a symbol.

\item[{[}syntax{]} (foreign-lambda* RETURNTYPE ((ARGTYPE VARIABLE) ...) STRING ...)]
Similar to \texttt{foreign-lambda}, but instead of generating code to
call an external function, the body of the C procedure is directly given
in \texttt{STRING ...}:

\begin{verbatim}
(define my-strlen
  (foreign-lambda* int ((c-string str))
    "int n = 0;
     while(*(str++)) ++n;
     return(n);") )

(my-strlen "one two three")             ==> 13
\end{verbatim}

For obscure technical reasons any use of the \texttt{return} statement
should enclose the result value in parantheses. For the same reasons
\texttt{return} without an argument is not allowed.

\end{description}

\subsection{Foreign type specifiers}

Here is a list of valid foreign type specifiers:

\begin{description}

\item[scheme-object]
An arbitrary Scheme data object (immediate or non-immediate). 

\item[bool]
As argument: any value (\texttt{\#f} is false, anything else is true).
As result: anything different from 0 and the \texttt{NULL}-pointer
is \texttt{\#t}.

\item[char unsigned-char]
A character.

\item[short unsigned-short]
A short integer number.

\item[int unsigned-int]
An small integer number in fixnum range (at least 30 bit).

\item[integer unsigned-integer]
Either a fixnum or a flonum in the range of a (unsigned) machine ``int''.

\item[long unsigned-long]
Either a fixnum or a flonum in the range of a (unsigned) machine ``long''.

\item[float double]
A floating-point number. If an exact integer is passed as an argument,
then it is automatically converted to a float.

\item[pointer]
An untyped pointer to the contents of a non-immediate Scheme object
(not allowed as return type).  The value \texttt{\#f} is also allowed
and is passed as a \texttt{NULL} pointer. 

\item[nonnull-pointer]
As \texttt{pointer}, but guaranteed not to be \texttt{\#f}.

\item[c-pointer]
An untyped operating-system pointer or a locative.  The value \texttt{\#f} is also
allowed and is passed as a \texttt{NULL} pointer.  If uses as the type of
a return value, a \texttt{NULL} pointer will be returned as \texttt{\#f}.

\item[nonnull-c-pointer]
As \texttt{c-pointer}, but guaranteed not to be \texttt{\#f/NULL}.

\item[{[}nonnull-{]}byte-vector]
A byte-vector object, passed as a pointer to it's contents. Arguments
of type \texttt{byte-vector} may optionally be \texttt{\#f}, which is
passed as a NULL pointer.  This is not allowed as a return type.

\item[{[}nonnull-{]}u8vector]
\item[{[}nonnull-{]}u16vector]
\item[{[}nonnull-{]}u32vector]
\item[{[}nonnull-{]}s8vector]
\item[{[}nonnull-{]}s16vector]
\item[{[}nonnull-{]}s32vector]
\item[{[}nonnull-{]}f32vector]
\item[{[}nonnull-{]}f64vector]
A SRFI-4 number-vector object, passed as a pointer to it's
contents. Arguments of type \texttt{byte-vector} may optionally be
\texttt{\#f}, which is passed as a NULL pointer.  These are not allowed
as return types.

\item[c-string]
A C string (terminated by a "{\\}0" character). The value \texttt{\#f}
is also allowed and is passed as a \texttt{NULL} pointer. If uses as
the type of a return value, a \texttt{NULL} pointer will be returned as
\texttt{\#f}. Note that the string is copied (with a zero-byte appended)
when passed as an argument to a foreign function. Also a return value
of this type is copied into garbage collected memory.

\item[nonnull-c-string]
As \texttt{c-string}, but guaranteed not to be \texttt{\#f/NULL}.

\item[{[}nonnull-{]}c-string*]
Similar to \texttt{[nonnull-]c-string}, but if used as a result-type,
the pointer returned by the foreign code will be freed (using the
C-libraries \texttt{free()})
after copying.

\item[void]
Specifies an undefined return value. Not allowed as argument type.

\item[(pointer TYPE)]
\item[(c-pointer TYPE)]
An operating-system pointer or a locative to an object of \texttt{TYPE}.

\item[(nonnull-pointer TYPE)]
\item[(nonnull-c-pointer TYPE)]
As \texttt{(pointer TYPE)}, but guaranteed not to be \texttt{\#f/NULL}.

\item[(struct NAME)]
A struct of the name \texttt{NAME}, which should be a string. Structs
can not be directly passed as arguments to foreign function, neither
can they be result values. Pointers to structs are allowed, though.

\item[(union NAME)]
A union of the name \texttt{NAME}, which should be a string. Unions can
not be directly passed as arguments to foreign function, neither can
they be result values. Pointers to unions are allowed, though.

\item[(function RESULTTYPE (ARGUMENTTYPE1 ... {[}...{]}) {[}CALLCONV{]})]
A function pointer. \texttt{CALLCONV} specifies an optional calling
convention and should be a string. The meaning of this string is entirely
platform dependent.  The value \texttt{\#f} is also allowed and is passed
as a \texttt{NULL} pointer.

\end{description}

Foreign types are mapped to C types in the following manner:

% XXX figure out {\tt }if this is the right way to do this...
{\tt
\begin{tabular}{|ll|}
\hline
bool&int\\
{[unsigned-]}char&{[unsigned]} char\\
{[unsigned-]}short&{[unsigned]} short\\
{[unsigned-]}int&{[unsigned]} int\\
{[unsigned-]}integer&{[unsigned]} int\\
{[unsigned-]}long&{[unsigned]} long\\
float&float\\
double&double\\
{[nonnull-]}pointer&void *\\
{[nonnull-]}c-pointer&void *\\
{[nonnull-]}byte-vector&unsigned char *\\
{[nonnull-]}u8vector&unsigned char *\\
{[nonnull-]}s8vector&char *\\
{[nonnull-]}u16vector&unsigned short *\\
{[nonnull-]}s16vector&short *\\
{[nonnull-]}u32vector&uint32\_t *\\
{[nonnull-]}s32vector&int32\_t *\\
{[nonnull-]}f32vector&float *\\
{[nonnull-]}f64vector&double *\\
{[nonnull-]}c-string&char *\\
void&void\\
([nonnull-]pointer TYPE)&TYPE *\\
(struct NAME)&struct NAME\\
(union NAME)&union NAME\\
(function RTYPE (ATYPE ...) [CALLCONV])&[CALLCONV] RTYPE (*)(ATYPE, ...)\\
\hline \end{tabular}
}

\subsection{Entry points} \label{entrypoints}

To simplify embedding compiled Scheme code into arbitrary programs, one
can define so called ``entry points'', which provide a uniform interface
and parameter conversion facilities.

\begin{description}

\item[{[}syntax{]} (define-entry-point INDEX ((VAR1 TYPE1) ...) (RTYPE1 ...) EXP1 EXP2 ...)]
Defines a new entry-point with index \texttt{INDEX} which should evaluate
to an exact integer. During execution of the body \texttt{EXP1 EXP2 ...}
the variables \texttt{VAR1 ...} are bound to the parameters passed from
the host program to the invoked entry point. The parameters passed
are converted according to the foreign type specifiers \texttt{TYPE1
...}. The expressions should return as many values as foreign type
specifiers are given in \texttt{RTYPE1 ...}. The results are then
transformed into values that can be used in the host program.

\end{description}

\textbf{Note:} if one or more of the result types \texttt{RTYPE ...}
specify the type \texttt{c-string}, then the parameter types at the same
positions in \texttt{TYPE1 ...} have to be \texttt{c-string}s as well,
because the result strings are copied into the same area in memory.
You should also take care that the passed buffer is long enough to hold
the result string or unpredictable things will happen.

If entry points were defined then the program will not terminate after
execution of the last toplevel expression, but instead it will enter a
loop that waits for the host to invoke one of the defined entry points.

The following C functions and data types are provided:

\begin{description}

\item[{[}C function{]} void CHICKEN\_parse\_command\_line(int argc, char *argv{[}{]}, int *heap, int *stack int *symbols)]
Parse the programs command-line contained in \texttt{argc} and
\texttt{argv} and return the heap-, stack- and symbol table limits
given by runtime options of the form \texttt{-:...}, or choose default
limits. The library procedure \texttt{argv} can access the command-line
only if this function has been called by the containing application.

\item[{[}C function{]} int CHICKEN\_initialize(int heap, int stack, int symbols, void *toplevel)]
Initializes the Scheme execution context and memory. \texttt{heap}
holds the number of bytes that are to be allocated for the secondary
heap. \texttt{stack} holds the number of bytes for the primary
heap. \texttt{symbols} contains the size of the symbol table. Passing
\texttt{0} to one ore more of these parameters will select a default
size. 
\texttt{toplevel} should be a pointer to the toplevel entry point
procedure. You should pass \texttt{C\_toplevel} here. In any subsequent
call to \texttt{CHICKEN\_run} or \texttt{CHICKEN\_invoke} you can simply
pass \texttt{NULL}.
Calling this function more than once has no effect. If enough
memory is available and initialization was successful, then \texttt{1}
is returned, otherwise this function returns \texttt{0}.

\item[{[}C function{]} void CHICKEN\_run(void **data, int *bytes, int *maxlen, void *toplevel)]
Starts the Scheme program. \texttt{data, bytes} and \texttt{maxlen}
contain invocation parameters in raw form. Pass \texttt{NULL} here.
Call this function once to execute all toplevel expressions in your
compiled Scheme program. If the runtime system was not initialized before,
then \texttt{CHICKEN\_initialize} is called with default sizes.
\texttt{toplevel} is the toplevel entry-point procedure.

\item[{[}C function{]} void CHICKEN\_invoke(int index, C\_parameter *params, int count, void *toplevel)]
Invoke the entry point with index \texttt{index}. \texttt{count} should
contain the number of parameters passed. \texttt{params} is a pointer
to parameter data:

\begin{verbatim}
typedef union
{
  C_word x;           /* parameter type scheme-object */
  long i;             /* parameter type bool, [unsigned] int/short/long */
  long c;             /* parameter type [unsigned] char */
  double f;           /* parameter type float/double */
  void *p;            /* any pointer parameter type and C strings */
} C_parameter;
\end{verbatim}


This function calls \texttt{CHICKEN\_run} if it was not called at least
once before.

\end{description}

Here is a simple example (assuming a UNIX-like environment):

\begin{verbatim}
% cat foo.c
#include <stdio.h>
#include "chicken.h"

int main(void)
{
  C_parameter p[ 3 ];
  char str[ 32 ] = "hello!";  /* We need some space for the result string! */

  memset(p, 0, sizeof(p));
  p[ 0 ].i = -99;
  p[ 1 ].p = str;
  p[ 2 ].f = 3.14;
  CHICKEN_invoke(1, p, 3, C_toplevel);
  printf("->\n%d\n%s\n", p[ 0 ].i, p[ 1 ].p);
  return 0;
}

% cat bar.scm
(define-entry-point 1
    ((a integer) (b c-string) (c double))
    (int c-string)
  (print (list a b c))
  (values 123 "good bye!") )

% chicken bar.scm -quiet
% gcc foo.c bar.c -o foo `chicken-config -cflags -embedded`
% foo
(-99 "hello!" 3.14)
->
123
good bye!
\end{verbatim}


Note the use of \texttt{-embedded}. We have to compile with additional compiler
options, because the host program provides the \texttt{main}
function.


\subsection{Callbacks} \label{callbacks}


To enable an external C function to call back to Scheme, the form
\texttt{foreign-callback-lambda} (or \texttt{foreign-callback-lambda*})
has to be used. This generates special code to save and restore important
state information during execution of C code. There are two ways of
calling Scheme procedures from C: the first is to invoke the runtime
function \texttt{C\_callback} with the closure to be called and the number
of arguments.  The second is to define an externally visible wrapper
function around a Scheme procedure with the \texttt{define-external}
or \texttt{foreign-callback-wrapper} forms. *****

Note: the names of all functions, variables and macros exported by the
Chicken runtime system start with ``\texttt{C\_}''. It is advisable to
use a different naming scheme for your own code to avoid name clashes.

\begin{description}

\item[{[}syntax{]} (define-external [QUALIFIERS] (NAME (ARGUMENTTYPE1 VARIABLE1) ...) RETURNTYPE BODY ...)]
\item[{[}syntax{]} (define-external NAME TYPE [INIT])]
The first form defines an externally callable Scheme
procedure. \texttt{NAME} should be a symbol, which, when converted to a
string, represents a legal C identifier. \texttt{ARGUMENTTYPE1 ...} and
\texttt{RETURNTYPE} are foreign type specifiers for the argument variables
\texttt{VAR1 ...} and the result, respectively.  \texttt{QUALIFIERS}
is an optional qualifer for the foreign procedure definition, like
\texttt{\_\_stdcall}.

\begin{verbatim}
(define-external (foo (c-string x)) int (string-length x))
\end{verbatim}

is equivalent to

\begin{verbatim}
(define foo 
  (foreign-callback-wrapper int "foo" 
    (c-string) (lambda (x) (string-length x))))
\end{verbatim}

The second form of \texttt{define-external} can be used to define
variables that are accessible from foreign code. It declares
a global variable named by the symbol \texttt{NAME} that
has the type \texttt{TYPE}. \texttt{INIT} can be an arbitrary
expression that is used to initialize the variable. \texttt{NAME} is
accessible from Scheme just like any other foreign variable defined by
\texttt{define-foreign-variable}.  

\begin{verbatim}
(define-external foo int 42)
((foreign-lambda* int ()
  "return(foo);"))           ==> 42
\end{verbatim}

\textbf{Note:} don't be tempted to
assign strings or bytevectors to external variables. Garbage collection
moves those objects around, so it is very bad idea to assign pointers
to heap-data. If you have to do so, then copy the data object into
statically allocated memory (for example by using \texttt{evict}).

\item[{[}syntax{]} (foreign-callback-wrapper RETURNTYPE NAME {[}QUALIFIERS{]} (ARGUMENTTYPE1 ...) EXP)]
Defines an externally callable wrapper around the procedure
\texttt{EXP}. \texttt{EXP} \textbf{must} be a lambda expression
of the form \texttt{(lambda \ldots)}. The wrapper will have the name
\texttt{NAME} and will have a signature as specified in the return- and
argument-types given in \texttt{RETURNTYPE} and \texttt{ARGUMENTTYPE1
...}.  \texttt{QUALIFIERS} is a qualifier string for the function
definition (see \texttt{define-external}).

\item[{[}C function{]} C\_word C\_callback(C\_word closure, int argc)]
This function can be used to invoke the Scheme procedure \texttt{closure}.
\texttt{argc} should contain the number of arguments that are passed to
the procedure on the temporary stack. Values are put onto the temporary
stack with the \texttt{C\_save} macro.

\end{description}


\subsection{Locations} \label{locations}


It is also possible to define variables containing unboxed C data,
so called \emph{locations}. It should be noted that locations may
only contain simple data, that is: everything that fits into a
machine word, and double-precision floating point values. 

\begin{description}

\item[{[}syntax{]} (define-location NAME TYPE {[}INIT{]})]
Identical to \texttt{(define-external NAME TYPE [INIT])}, but the variable
is not accessible from outside of the current compilation unit (it is 
declared \texttt{static}).

\item[{[}syntax{]} (let-location ((NAME TYPE {[}INIT{]}) ...) BODY ...)]
Defines a lexically bound location.

\item[{[}syntax{]} (location NAME)]
\texttt{NAME} should be an external variable defined by
\texttt{(define-external NAME ...)} or a location defined by \texttt{define-location}
or \texttt{let-location}.  This form returns a pointer object
that contains the address of the variable \texttt{NAME}.

\begin{verbatim}
(define-external foo int)
((foreign-lambda* void (((pointer int) ip)) "*ip = 123;") 
  (location foo))
foo                                                                               ==> 123
\end{verbatim}

This facility is especially useful in sitatuations, where a C function
returns more than one result value:

\begin{verbatim}
(declare 
  (foreign-declare "#include <math.h>") )

(define modf
  (foreign-lambda double "modf" double (pointer double)) )

(let-location ([i double])
  (let ([f (modf 1.99 (location i))])
    (print "i=" i ", f=" f) ) )
\end{verbatim}

\end{description}


\subsection{C interface}


The following functions and macros are available for C code that invokes
Scheme:

\begin{description}

\item[{[}C function{]} void C\_save(C\_word x)]
Saves the Scheme data object \texttt{x} on the temporary stack.

\item[{[}C macro{]} C\_word C\_fix(int integer)]
\item[{[}C macro{]} C\_word C\_make\_character(int char\_code)]
\item[{[}C macro{]} C\_word C\_SCHEME\_END\_OF\_LIST]
\item[{[}C macro{]} C\_word C\_SCHEME\_END\_OF\_FILE]
\item[{[}C macro{]} C\_word C\_SCHEME\_FALSE]
\item[{[}C macro{]} C\_word C\_SCHEME\_TRUE]
These macros return immediate Scheme data objects.

\item[{[}C function{]} C\_word C\_string(C\_word **ptr, int length, char *string)]
\item[{[}C function{]} C\_word C\_string2(C\_word **ptr, char *zero\_terminated\_string)]
\item[{[}C function{]} C\_word C\_intern2(C\_word **ptr, char *zero\_terminated\_string)]
\item[{[}C function{]} C\_word C\_intern3(C\_word **ptr, char *zero\_terminated\_string, C\_word initial\_value)]
\item[{[}C function{]} C\_word C\_pair[C function] (C\_word **ptr, C\_word car, C\_word cdr)]
\item[{[}C function{]} C\_word C\_flonum(C\_word **ptr, double number)]
\item[{[}C function{]} C\_word C\_int\_to\_num(C\_word **ptr, int integer)]
\item[{[}C function{]} C\_word C\_mpointer(C\_word **ptr, void *pointer)]
\item[{[}C function{]} C\_word C\_vector(C\_word **ptr, int length, ...)]
\item[{[}C function{]} C\_word C\_list(C\_word **ptr, int length, ...)]
These functions allocate memory from \texttt{ptr} and initialize a fresh
data object. The new data object is returned. \texttt{ptr} should be the
\textbf{address} of an allocation pointer created with \texttt{C\_alloc}.

\item[{[}C macro{]} C\_word *C\_alloc(int words)]
Allocates memory from the C stack and returns a pointer to
it. \texttt{words} should be the number of words needed for all data
objects that are to be created in this function.  Note that the allocated
data objects have to be passed to the Scheme function, or they will
not be seen by the garbage collector. This is really only usable for
callback procedure invocations, make sure not to use it in normal code,
because the allocated memory will be re-used after the foreign procedure
returns. When invoking Scheme callback procedures a minor garbage
collection is performed, so data allocated with \texttt{C\_alloc()}
will already have moved to a safe place.

\item[{[}C macro{]} int C\_SIZEOF\_LIST(int length)]
\item[{[}C macro{]} int C\_SIZEOF\_STRING(int length)]
\item[{[}C macro{]} int C\_SIZEOF\_VECTOR(int length)]
\item[{[}C macro{]} int C\_SIZEOF\_INTERNED\_SYMBOL(int length)]
\item[{[}C macro{]} int C\_SIZEOF\_PAIR]
\item[{[}C macro{]} int C\_SIZEOF\_FLONUM]
\item[{[}C macro{]} int C\_SIZEOF\_POINTER]
\item[{[}C macro{]} int C\_SIZEOF\_LOCATIVE]
\item[{[}C macro{]} int C\_SIZEOF\_TAGGED\_POINTER]
These are macros that return the size in words needed for a data object
of a given type.

\item[{[}C macro{]} int C\_character\_code(C\_word character)]
\item[{[}C macro{]} int C\_unfix(C\_word fixnum)]
\item[{[}C macro{]} double C\_flonum\_magnitude(C\_word flonum)]
\item[{[}C function{]} char *C\_c\_string(C\_word string)]
\item[{[}C function{]} int C\_num\_to\_int(C\_word fixnum\_or\_flonum)]
[C function void *C\_pointer\_address(C\_word pointer)]
These macros and functions can be used to convert Scheme data objects
back to C data.

\item[{[}C variable{]} C\_word **C\_collectibles]
If not \texttt{NULL}, then this variable can be set to a pointer to an
array of locations that contain Scheme values and should be subject to
garbage collection. The last entry in the array should be a \texttt{NULL}
pointer. This facility is similar to \texttt{C\_register\_lf()}, but
allows a more fine-grained control over special GC'able locations.

\item[{[}C macro{]} int C\_header\_size(C\_word x)]
\item[{[}C macro{]} int C\_header\_bits(C\_word x)]
Return the number of elements and the type-bits of the non-immediate
Scheme data object \texttt{x}.

\item[{[}C macro{]} C\_word C\_block\_item(C\_word x, int index)]
This macro can be used to access slots of the non-immediate Scheme data
object \texttt{x}.  \texttt{index} specifies the index of the slot to
be fetched, starting at 0. Pairs have 2 slots, one for the \textbf{car}
and one for the \textbf{cdr}. Vectors have one slot for each element.

\item[{[}C macro{]} void *C\_data\_pointer(C\_word x)]
Returns a pointer to the data-section of a non-immediate Scheme object.

\item[{[}C macro{]} C\_word C\_make\_header(C\_word bits, C\_word size)]
A macro to build a Scheme object header from its bits and size parts.

\item[{[}C function{]} C\_word C\_mutate(C\_word *slot, C\_word val)]
Assign the Scheme value \texttt{val} to the location specified by
\texttt{slot}.  If the value points to data inside the nursery (the first
heap-generation), then the garbage collector will remember to handle the
data appropriately. Assigning nursery-pointers directly will otherwise
result in lost data.

\item[{[}C macro{]} C\_word C\_symbol\_value(C\_word symbol)]
Returns the global value of the variable with the name \texttt{symbol}.

\item[{[}C function{]} void *C\_register\_lf(C\_word *data, int count)]
Registers an array of \emph{root} objects. \texttt{data} is a pointer
to an array of Scheme data, \texttt{count} contains the number of
elements in the array. The registered objects will be subject to
garbage collection. The function returns a pointer identifying the
root array, this pointer can be used to unregister the root data
by calling \texttt{C\_unregister\_lf}.  \textbf{Note:} The root data
array should not contain pointers to data allocated in the nursery. Any
assignment of potential nursery data into a root-array should be done
via \texttt{C\_mutate()}.

\item[{[}C function{]} void C\_unregister\_lf(void *handle)]
Unregisters an array of root objects identified by \texttt{handle}.

\end{description}


An example:

\begin{verbatim}
% cat foo.scm
(declare (foreign-declare "extern int callout(int, int, int);"))

(define callout (foreign-callback-lambda int "callout" int int int))

(define-external (callin (scheme-object xyz)) int
  (print "This is 'callin': " xyz)
  123)

(print (callout 1 2 3))

% cat bar.c
#include <stdio.h>
#include "chicken.h"

extern int callout(int, int, int);
extern int callin(C_word x);

int callout(int x, int y, int z)
{
  C_word *ptr = C_alloc(C_SIZEOF_LIST(3));
  C_word lst;

  printf("This is 'callout': %d, %d, %d\n", x, y, z);
  lst = C_list(&ptr, 3, C_fix(x), C_fix(y), C_fix(z));
  return callin(lst);  /* Note: `callin' will have GC'd the data in `ptr' */
}

% chicken foo.scm -quiet
% gcc foo.c bar.c -o foo `chicken-config -cflags -libs`
% foo
This is 'callout': 1, 2, 3
This is 'callin': (1 2 3)
123
\end{verbatim}


\textbf{Notes:}
\begin{itemize}

\item Scheme procedures can call C functions, and C functions can call
Scheme procedures, but for every pending C stack frame, the available
size of the first heap generation (the ``nursery'') will be decreased,
because the C stack is identical to the nursery. On systems with a small
nursery this might result in thrashing, since the C code between the
invocation of C from Scheme and the actuall calling back to Scheme might
build up several stack-frames or allocates large amounts of stack data.
To prevent this it is advisable to increase the default nursery size,
either when compiling the file (using the \texttt{-nursery} option)
or when running the executable (using the \texttt{-:s} runtime option).

\item Calls to Scheme/C may be nested arbitrarily, and Scheme
continuations can be invoked as usual, but keep in mind that C stack
frames will not be recovered, when a Scheme procedure call from C does
not return normally.

\item When multiple threads are running concurrently, and control switches
from one thread to another, then the continuation of the current thread
is captured and saved. Any pending C stack frame still active from a
callback will remain on the stack until the threads is re-activated
again. This means that in a multithreading situation, when C callbacks
are involved, the available nursery space can be smaller than expected.
So doing many nested Scheme-$>$C-$>$Scheme calls can reduce the available
memory up to the point of thrashing. It is advisable to have only a
single thread with pending C stack-frames at any given time.

\item Pointers to Scheme data objects should not be stored in local or
global variables while calling back to Scheme.  Any Scheme object not
passed back to Scheme will be reclaimed or moved by the garbage collector.

\item Calls from C to Scheme are never tail-recursive.

\item Continuations captured via \texttt{call-with-current-continuation}
and passed to C code can be invoked like any other Scheme procedure.

\end{itemize}


\section{Parameters} \label{parameters}


Certain behaviour of the interpreter and compiled programs can be
customized via 'parameters', where a parameter is a procedure of
zero or one arguments. To retrieve the value of a parameter call the
parameter-procedure with zero arguments. To change the setting of the
parameter, call the parameter-procedure with the new value as argument:

\begin{verbatim}
(define foo (make-parameter 123))
(foo)                             ==> 123
(foo 99)
(foo)                             ==> 99
\end{verbatim}

Parameters are fully thread-local, each thread of execution
owns a local copy of a parameters' value.

(See also: \texttt{make-parameter} and \texttt{parameterize})

\begin{description}

\item[{[}parameter{]} case-sensitive]
If true, then \texttt{read} reads symbols and identifiers in
case-sensitive mode and uppercase characters in symbols are printed
escaped.

\item[{[}parameter{]} dynamic-load-librares]
A list of strings containing shared libraries that should be checked
for explicitly loaded library units (this facility is not available on
all platforms). See \texttt{load-library}.

\item[{[}parameter{]} command-line-arguments]
Contains the list of arguments passed to this program, with the name of
the program removed.

\item[{[}parameter{]} exit-handler]
A procedure of a single optional argument. When \texttt{exit} is called,
then this procedure will be invoked with the exit-code as argument. The
default behaviour is to terminate the program.

\item[{[}parameter{]} eval-handler]
A procedure of one or two arguments. When \texttt{eval} is invoked, it
calls the value of this parameter with the same arguments. The default
behaviour is to evaluate the argument expression and to ignore the
second parameter.

\item[{[}parameter{]} force-finalizers]
If true, force and execute all pending finalizers before exiting the
program (either explicitly by \texttt{exit} or implicitly when the last
toplevel expression has been executed). Default is \texttt{\#t}.

\item[{[}parameter{]} implicit-exit-handler]
A procedure of no arguments. When the last toplevel expression of the
program has executed, then the value of this parameter is called. The
default behaviour is to do nothing, or, if one or more entry-points
were defined (see: \ref{entrypoints}) to enter a loop that waits for
callbacks from the host program.

\item[{[}parameter{]} keyword-style]
Enables alternative keyword syntax, where \texttt{STYLE} may be either
\texttt{\#:prefix} (as in Common Lisp) or \texttt{\#:suffix} (as in DSSSL).
Any other value disables the alternative syntaxes.

\item[{[}parameter{]} load-verbose]
A boolean indicating wether loading of source-files, compiled code
(if available) and compiled libraries should display a message.

\item[{[}parameter{]} reset-handler]
A procedure of zero arguments that is called via \texttt{reset}. The
default behaviour in compiled code is to invoke the value of
\texttt{(exit-handler)}. The default behaviour in the interpreter is to
abort the current computation and to restart the read-eval-print loop.

\item[{[}parameter{]} strict-reader]
If true, then most non-standard read syntax is disabled. Defaults to
\texttt{\#f}.

\end{description}


\section{Unit: library}

This unit contains basic Scheme definitions. This unit is used by default, unless the program
is compiled with the \texttt{-explicit-use} option.

\subsection{Arithmetic}
\begin{description}

\item[{[}procedure{]} (add1 N)]
\item[{[}procedure{]} (sub1 N)]
Adds/subtracts 1 from \texttt{N}.

\item[{[}procedure{]} (bitwise-and N1 ...)]
\item[{[}procedure{]} (bitwise-ior N1 ...)]
\item[{[}procedure{]} (bitwise-xor N1 ...)]
\item[{[}procedure{]} (bitwise-not N)]
\item[{[}procedure{]} (arithmetic-shift N1 N2)]
Binary fixnum operations. \texttt{arithmetic-shift} shifts the argument
\texttt{N1} by \texttt{N2} bits to the left. If \texttt{N2} is negative,
than \texttt{N1} is shifted to the right.

\item[{[}procedure{]} (fixnum? X)]
Returns \texttt{\#t} if \texttt{X} is a fixnum, or \texttt{\#f} otherwise.

\item[{[}procedure{]} (fx+ N1 N2)]
\item[{[}procedure{]} (fx- N1 N2)]
\item[{[}procedure{]} (fx* N1 N2)]
\item[{[}procedure{]} (fx/ N1 N2)]
\item[{[}procedure{]} (fxmod N1 N2)]
\item[{[}procedure{]} (fxneg N)]
\item[{[}procedure{]} (fxmin N1 N2)]
\item[{[}procedure{]} (fxmax N1 N2)]
\item[{[}procedure{]} (fx= N1 N2)]
\item[{[}procedure{]} (fx> N1 N2)]
\item[{[}procedure{]} (fx< N1 N2)]
\item[{[}procedure{]} (fx>= N1 N2)]
\item[{[}procedure{]} (fx<= N1 N2)]
Arithmetic fixnum operations. These procedures do not check their
arguments, so non-fixnum parameters will result in incorrect
results. \texttt{fxneg} negates its argument.

\item[{[}procedure{]} (signum N)]
Returns \texttt{1} if \texttt{N} is positive, \texttt{-1} if \texttt{N} 
is negative or \texttt{0} if \texttt{N} is zero.

\end{description}


\subsection{Input/Output}


\begin{description}

\item[{[}procedure{]} (current-error-port {[}PORT{]})]
Returns default error output port. If \texttt{PORT} is given, then that
port is selected as the new current error output port.

\item[{[}procedure{]} (end-of-file)]
Returns the end-of-file object.

\item[{[}procedure{]} (flush-output {[}PORT{]})]
Write buffered output to the given output-port. \texttt{PORT} defaults
to the value of \texttt{(current-output-port)}.

\item[{[}procedure{]} (port-name PORT)]
Fetch filename from \texttt{PORT}. This returns the filename that was
used to open this file.  Returns a special tag string, enclosed into
parantheses for non-file ports.

\item[{[}procedure{]} (port-position PORT)]
Returns the current position of \texttt{PORT} as two values: row and
column number.  If the port does not support such an operation an error
is signaled. This procedure is currently only available for input ports.

\item[{[}procedure{]} (set-port-name! PORT STRING)]
Sets the name of \texttt{PORT} to \texttt{STRING}.

\end{description}


\subsection{Files}


\begin{description}

\item[{[}procedure{]} (delete-file STRING)]
Deletes the file with the pathname \texttt{STRING}. If the file does
not exist, an error is signaled.

\item[{[}procedure{]} (file-exists? STRING)]
Returns \texttt{\#t} if a file with the given pathname exists, or
\texttt{\#f} otherwise.

\item[{[}variable{]} pathname-directory-separator]
Contains the directory-separator character for pathnames on this platform.

\item[{[}variable{]} pathname-extension-separator]
Contains the extension-separator character for pathnames on this platform.

\item[{[}procedure{]} (rename-file OLD NEW)]
Renames the file or directory with the pathname \texttt{OLD} to
\texttt{NEW}. If the operation does not succeed, an error is signaled.

\end{description}

\subsection{String ports}


\begin{description}

\item[{[}procedure{]} (get-output-string PORT)]
Returns accumulated output of a port created with
\texttt{(open-output-string)}.

\item[{[}procedure{]} (open-input-string STRING)]
Returns a port for reading from \texttt{STRING}.

\item[{[}procedure{]} (open-output-string)]
Returns a port for accumulating output in a string.

\end{description}


\subsection{Feature identifiers}


\begin{description}

\item[{[}procedure{]} (features)]
Returns a list of all registered features that will be accepted as valid
feature-identifiers by \texttt{cond-expand}.

\item[{[}procedure{]} (register-feature! FEATURE ...)]
Register one or more features that will be accepted as valid
feature-identifiers by \texttt{cond-expand}. \texttt{FEATURE ...} may
be a keyword, string or symbol.

\item[{[}procedure{]} (unregister-feature! FEATURE ...)]
Unregisters the specified feature-identifiers. \texttt{FEATURE ...}
may be a keyword, string or symbol.

\end{description}


\subsection{Keywords}

Keywords are special symbols prefixed with \texttt{\#:} that evaluate
to themselves.  Procedures can use keywords to accept optional named
parameters in addition to normal required parameters.  Assignment to
and bindings of keyword symbols is not allowed.
The parameter \texttt{keyword-style} and the compiler/interpreter option
\texttt{-keyword-style} can be used to allow an additional keyword
syntax, either compatible to Common LISP, or to DSSSL.

\begin{description}

\item[{[}procedure{]} (get-keyword KEYWORD ARGLIST {[}THUNK{]})]
Returns the argument from \texttt{ARGLIST} specified under the keyword
\texttt{KEYWORD}.  If the keyword is not found, then the zero-argument
procedure \texttt{THUNK} is invoked and the result value is returned. If
\texttt{THUNK} is not given, \texttt{\#f} is returned.

\begin{verbatim}
(define (increase x . args)
  (+ x (get-keyword #:amount args (lambda () 1))) )
(increase 123)                                      ==> 124
(increase 123 #:amount 10)                          ==> 133
\end{verbatim}

\item[{[}procedure{]} (keyword? X)]
Returns \texttt{\#t} if \texttt{X} is a keyword symbol, or \texttt{\#f}
otherwise.

\item[{[}procedure{]} (keyword{\tt->}string KEYWORD)]
Transforms \texttt{KEYWORD} into a string.

\item[{[}procedure{]} (string{\tt->}keyword STRING)]
Returns a keyword with the name \texttt{STRING}.

\end{description}


\subsection{Exceptions}


CHICKEN implements the (currently withdrawn) SRFI-12
exception system. For more information, see the SRFI-12
Document\urlfootnote{http://srfi.schemers.org/srfi-12/srfi-12.html}

\begin{description}

\item[{[}syntax{]} (condition-case EXPRESSION CLAUSE ...)]
Evaluates \texttt{EXPRESSION} and handles any exceptions that are covered by
\texttt{CLAUSE ...}, where \texttt{CLAUSE} should be of the following form:

\begin{verbatim}
CLAUSE = ([VARIABLE] (KIND ...) BODY ...)
\end{verbatim}

If provided, \texttt{VARIABLE} will be bound to the signalled exception
object. \texttt{BODY ...} is executed when the exception is a property-
or composite condiiton with the kinds given \texttt{KIND ...} (unevaluated).
If no clause applies, the exception is re-signalled in the same dynamic
context as the \texttt{condition-case} form.

\begin{verbatim}
(define (check thunk)
  (condition-case (thunk)
    [(exn file) (print "file error")]
    [(exn) (print "other error")]
    [var () (print "something else")] ) )

(check (lambda () (open-input-file "")))   ; -> "file error"
(check (lambda () some-unbound-variable))  ; -> "othererror"
(check (lambda () (signal 99)))            ; -> "something else"

(condition-case some-unbound-variable
  [(exn file) (print "ignored)] )      ; -> signals error

\end{verbatim}

\end{description}

All error-conditions signalled by the system are of kind \texttt{exn}.
The following composite conditions are additionally defined:

\begin{description}

\item[(exn type)]
Signalled on type-mismatch errors, for example when an argument of the wrong
type is passed to a builtin procedure.

\item[(exn arithmetic)]
Signalled on arithmetic errors, like division by zero.

\item[(exn i/o)]
Signalled on input/outout errors.

\item[(exn i/o file)]
Signalled on file-related errors.

\item[(exn i/o net)]
Signalled on network errors.

\item[(exn runtime)]
Signalled on low-level runtime-system error-situations, like running out of memory.

\item[(exn bounds)]
Signalled on errors caused by accessing non-existent elements of a collection.

\end{description}

Notes:
\begin{itemize}
\item All error-exceptions (of the kind \texttt{exn}) are non-continuable.

\item Error-exceptions of the \texttt{exn} kind have additional
\texttt{arguments} and \texttt{location} properties that contain the
arguments passed to the error-handler and the name of the procedure
where the error occurred (if available).

\item When the \texttt{posix} unit is available and used, then a
user-interrupt (\texttt{signal/int}) signals an exception of the kind
\texttt{user-interrupt}. 

\end{itemize}


\subsection{Miscellaneous}

\begin{description}

\item[{[}procedure{]} (argv)]
Return a list of all supplied command-line arguments. The first item in
the list is a string containing the name of the executing program. The
other items are the arguments passed to the application. This list is
freshly created on every invocation of \texttt{(argv)}.  It depends on
the host-shell wether arguments are expanded ('globbed') or not.

\item[{[}procedure{]} (build-platform)]
Returns a symbol specifying the toolset which has been used for
building the executing system, which is one of the following:

\begin{verbatim}
djgpp
cygwin
msvc
mingw32
gnu
metrowerks
unknown
\end{verbatim}

\item[{[}procedure{]} (char-name SYMBOL-OR-CHAR {[}CHAR{]})]
This procedure can be used to inquire about character names or to
define new ones. With a single argument the behaviour is as follows:
If \texttt{SYMBOL-OR-CHAR} is a symbol, then \texttt{char-name} returns
the character with this name, or \texttt{\#f} if no character is defined
under this name.  If \texttt{SYMBOL-OR-CHAR} is a character, then the
name of the character is returned as a symbol, or \texttt{\#f} if the
character has no associated name.

If the optional argument \texttt{CHAR} is provided, then
\texttt{SYMBOL-OR-CHAR} should be a symbol that will be the new name of
the given character.  If multiple names designate the same character,
then the \texttt{write} will use the character name that was defined last.

\begin{verbatim}
(char-name 'space)                  ==> #\space
(char-name #\space)                 ==> space
(char-name 'bell)                   ==> #f
(char-name (integer->char 7))       ==> #f
(char-name 'bell (integer->char 7))
(char-name 'bell)                   ==> #\bell
(char->integer (char-name 'bell))   ==> 7
\end{verbatim}

\item[{[}procedure{]} (chicken-version)]
Returns a string containing the version number of the Chicken runtime
system.

\item[{[}procedure{]} (cpu-time)]
Returns the used CPU time of the current process in milliseconds as
two values: the time spent in user code, and the time spent in system
code. On platforms where user and system time can not be differentiated,
system time will be always be 0.

\item[{[}procedure{]} (current-milliseconds)]
Returns the number of milliseconds since process- or machine startup.

\item[{[}procedure{]} (current-seconds)]
Returns the number of seconds since midnight, Jan. 1, 1970.

\item[{[}procedure{]} (enable-interrupts)]
\item[{[}procedure{]} (disable-interrupts)]
Enables/disables processing of timer-interrupts and interrupts caused
by signals.

\begin{verbatim}(disable-interrupts)
(disable-interrupts)
(enable-interrupts)
; <interupts still disabled - call enable-interrupts once more>
\end{verbatim}

\item[{[}procedure{]} (andmap PROC LIST1 ...)]
Repeatedly calls \texttt{PROC} with arguments taken from \texttt{LIST1
...}.  If any invocation should return \texttt{\#f}, the result of
\texttt{andmap} is \texttt{\#f}. If all invocations return a true result,
then the result of \texttt{andmap} is \texttt{\#t}.

\item[{[}procedure{]} (errno)]
Returns the error code of the last system call.

\item[{[}procedure{]} (error STRING EXP ...)]
Prints error message, writes all extra arguments to the
value of \texttt{(current-error-port)} and invokes the
current value of \texttt{(error-handler)}.  This conforms to
SRFI-23\urlfootnote{http://srfi.schemers.org/srfi-23/srfi-23.html}.

\item[{[}procedure{]} (exit {[}CODE{]})]
Exit the running process and return exit-code, which defaults to 0
(Invokes \texttt{exit-handler}).

\item[{[}procedure{]} (gc {[}FLAG{]})]
Invokes a garbage-collection and returns the number of free bytes
in the heap. The flag specifies wether a minor (\texttt{\#f}) or
major (\texttt{\#t}) GC is to be triggered. If no argument is given,
\texttt{\#t} is assumed. When the argument is \texttt{\#t}, all pending
finalizers are executed.

\item[{[}procedure{]} (gensym {[}STRING-OR-SYMBOL{]})]
Returns a newly created uninterned symbol. If an argument is provided,
the new symbol is prefixed with that argument.

\item[{[}procedure{]} (getenv STRING)]
Returns the value of the environment variable \texttt{STRING} or
\texttt{\#f} if that variable is not defined.

\item[{[}procedure{]} (machine-type)]
Returns a symbol specifying the processor on which this process is
currently running, which is one of the following:

\begin{verbatim}
alpha
mips
hppa
ultrasparc
sparc
ppc
x86
unknown
\end{verbatim}

\item[{[}procedure{]} (make-parameter VALUE {[}GUARD{]})]
Returns a procedure that accepts zero or one argument. Invoking the
procedure with zero arguments returns \texttt{VALUE}. Invoking the
procedure with one argument changes it's value to the value of that
argument (subsequent invocations with zero parameters return the new
value). \texttt{GUARD} should be a procedure of a single argument. Any
new values of the parameter (even the initial value) are passed to this
procedure. The guard procedure should check the value and/or convert it
to an appropriate form.

\item[{[}procedure{]} (ormap PROC LIST1 ...)]
Repeatedly calls \texttt{PROC} with arguments taken from \texttt{LIST1
...}.  If any invocation should return a value different from
\texttt{\#f}, then this value is returned as the  result of
\texttt{ormap}. If all invocations return \textbf{\#f},
then the result of \texttt{ormap} is \texttt{\#f}.

\item[{[}procedure{]} (port? X)]
Returns \texttt{\#t} if \texttt{X} is a port object or \texttt{\#f}
otherwise.

\item[{[}procedure{]} (print EXP1 ...)]
Outputs the arguments \texttt{EXP1, ...} using \texttt{display}
and writes a newline character to the port that is the value of
\texttt{(current-output-port)}.

\item[{[}procedure{]} (print* EXP1 ...)]
Similar to \texttt{print}, but does not output a terminating newline
character.

\item[{[}procedure{]} (reset)]
Reset program (Invokes \texttt{reset-handler}).

\item[{[}procedure{]} (set-finalizer! X PROC)]
Registers a procedure of one argument \texttt{PROC}, that will be
called as soon as the non-immediate data object \texttt{X} is about to
be garbage-collected (with that object as it's argument).  Note that
the finalizer will \textbf{not} be called when interrupts are disabled.

\item[{[}procedure{]} (set-gc-report! FLAG)]
Print statistics after every GC, depending on \texttt{FLAG}. A value of
\texttt{\#t} shows statistics after every major GC. A true value different
from \texttt{\#t} shows statistics after every minor GC. \texttt{\#f}
switches statistics off.

\item[{[}procedure{]} (software-type)]
Returns a symbol specifying the operating system on which this process
is currently running, which is one of the following:

\begin{verbatim}
msdos
windows
unix
macos
unknown
\end{verbatim}

\item[{[}procedure{]} (software-version)]
Returns a symbol specifying the operating system version on which this
process is currently running, which is one of the following:

\begin{verbatim}
linux
freebsd
netbsd
openbsd
macosx
hpux
solaris
sunos
unknown
\end{verbatim}

\item[{[}procedure{]} (string{\tt->}uninterned-symbol STRING)]
Returns a newly created, unique symbol with the name \texttt{STRING}.

\item[{[}procedure{]} (system STRING)]
Execute shell command. The functionality offered by this procedure
depends on the capabilities of the host shell.

\item[{[}procedure{]} (vector-copy! VECTOR1 VECTOR2 {[}COUNT{]})]
Copies contents of \texttt{VECTOR1} into \texttt{VECTOR2}. If the
argument \texttt{COUNT} is given, it specifies the maximal number of
elements to be copied. If not given, the minumum of the lengths of the
argument vectors is copied.

\item[{[}procedure{]} (void)]
Returns an unspecified value.

\end{description}

\section{Unit: eval}

This unit has support for evaluation and macro-handling. This unit is used
by default, unless the program is compiled with the \texttt{-explicit-use}
option.

\subsection{Loading code}

\begin{description}

\item[{[}procedure{]} (load FILE {[}EVALPROC{]})]
Loads and evaluates expressions from the given source file, which may
be either a string or an input port.  Each expression read is passed to
\texttt{EVALPROC} (which defaults to \texttt{eval}).  On platforms that
support it (currently Linux ELF and Solaris), \texttt{load} can be used
to load compiled programs:

\begin{verbatim}
% cat x.scm
(define (hello) (print "Hello!"))
% chicken x.scm -quiet
% gcc x.c -shared -fPIC `chicken-config -cflags -shared -libs` -o x.so
% csi -quiet
>>> (load "x.so")
; loading x.so ...
>>> (hello)
Hello!
>>>
\end{verbatim}

The second argument to \texttt{load} is ignored when loading compiled
code.  The same compiled object file can not be loading more than once.
If source code is loaded from a port, then that port is closed after
all expressions have been read.

\item[{[}procedure{]} (visit FILENAME)]
Reads the source file \texttt{FILENAME}, but performs only macro-expansion.
This is mainly useful to make the macro-/syntax-, constant- and inline-function
-definitions in \texttt{FILENAME} available.

\item[{[}procedure{]} (load-library UNIT {[}LIBRARYFILE{]})]
On platforms that support dynamic loading, \texttt{load-library} loads
the compiled library unit \texttt{UNIT} (which should be a symbol). If the
string \texttt{LIBRARYFILE} is given, then the given shared library will
be loaded and the toplevel code of the contained unit will be executed.
If no \texttt{LIBRARYFILE} argument is given, then the following libraries
are checked for the required unit:

\begin{itemize}

\item a file named ``\texttt{<UNIT>.so}''

\item the files given in the parameter \texttt{dynamic-load-libraries}.

\end{itemize}

If the unit is not found, an error is signaled.  When the library unit
can be successfully loaded, a feature-identifier named \texttt{UNIT}
is registered. If the feature is already registered before loading,
the \texttt{load-library} does nothing.

\item[{[}procedure{]} (load-noisily FILE {[}EVALPROC{]})]
As \texttt{load} but the result(s) of each evaluated toplevel-expression
is written to standard output.

\item[{[}procedure{]} (load-srfi-7-program FILE {[}EVALPROC{]})]
Loads and evaluates expressions that are specified as a SRFI-7
configuration language program.

\item[{[}procedure{]} (require UNIT {[}LIBRARYFILE{]})]
Similar to \texttt{load-library}, but when the loading fails (either
because dynamic loading is not supported, or when the library-unit is not
available), then an attempt is made to load the file \texttt{UNIT.so}
or \texttt{UNIT.scm} (int that order) from the current include path,
wich defaults to the pathnames given in \texttt{CHICKEN\_INCLUDE\_PATH}
and \texttt{CHICKEN\_HOME}.  \texttt{UNIT} may be a symbol, a string or
a list of symbols or strings.

\end{description}

\subsection{Read-eval-print loop}

\begin{description}

\item[{[}procedure{]} (read-eval-print-loop)]
Start a new read-eval-print loop. Sets the \texttt{reset-handler} so that
any invocation of \texttt{reset} restarts the read-eval-print loop. Also
changes the current \texttt{error-handler} to display a message, write
any arguments to the value of \texttt{(current-error-port)} and reset.

\end{description}


\subsection{Macros}


\begin{description}

\item[{[}procedure{]} (get-line-number EXPR)]
If \texttt{EXPR} is a pair with the car being a symbol, and line-number
information is available for this expression, then this procedure returns
the associated line number. If line-number information is not available,
then \texttt{\#f} is returned.  Note that line-number information for
expressions is only available in the compiler.

\item[{[}procedure{]} (macro? SYMBOL)]
Returns \texttt{\#t} if there exists a macro-definition for \texttt{SYMBOL}.

\item[{[}procedure{]} (macroexpand X)]
If \texttt{X} is a macro-form, expand the macro (and repeat expansion
until expression is a non-macro form).  Returns the resulting expression.

\item[{[}procedure{]} (macroexpand-1 X)]
If \texttt{X} is a macro-form, expand the macro.  Returns the resulting
expression.

\item[{[}procedure{]} (undefine-macro! SYMBOL)]
Remove the current macro-definition of the macro named \texttt{SYMBOL}.

\end{description}


\subsection{Extensions}


This functionality is only available on platforms that support dynamic
loading of compiled code. Currently Linux, FreeBSD, Solaris, Windows (Cygwin) 
and HP/UX are supported.

Note: You have to set up the extension-registry before you can use this stuff.
The easiest way is to create a directory called \texttt{.chicken-registry}
in your \texttt{\$HOME} directory and run \texttt{csi -setup}:

\begin{verbatim}
% cd $HOME
% mkdir .chicken-registry
% csi -setup
\end{verbatim}

\begin{description}

\item[{[}procedure{]} (package ID)]
Sets the current \emph{package prefix} to \texttt{ID}. All references
to extension IDs (as in \texttt{provide, provided?} and \texttt{require})
are relative to this prefix.

So
 
\begin{verbatim}
(package 'foo)
(require 'bar)
\end{verbatim}

is identical to

\begin{verbatim} 
(require '(foo bar))
\end{verbatim}

\item[{[}procedure{]} (provide ID ...)]
Registers the extension IDs \texttt{ID ...} as loaded. This is mainly
intended to provide aliases for certain extension identifiers.

\item[{[}procedure{]} (provided? ID ...)]
Returns \texttt{\#t} if the extension with the IDs \texttt{ID \ldots}
are currently loaded, or \texttt{\#f} otherwise.
Works also for feature-ids.

\item[{[}procedure{]} (require ID ...)]
If the extension library \texttt{ID} is not already loaded into the
system, then \texttt{require} will lookup the location of the shared
extension libary and load it. If \texttt{ID} names a library-unit of
the base system, then it is loaded via \texttt{load-library}.  If no
extension library is available for the given ID, then an attempt is
made to load the file \texttt{ID.so} or \texttt{ID.scm} (int that order)
from one of the following locations:

\begin{enumerate}

\item the current directory

\item the current include path, which defaults to the pathnames
given in \texttt{CHICKEN\_INCLUDE\_PATH} and \texttt{CHICKEN\_HOME}.

\end{enumerate}

\texttt{ID} may be a symbol, or a list of symbols.  See also:
\texttt{require-for-syntax}

\end{description}


\subsection{Miscellaneous}


\begin{description}

\item[{[}procedure{]} (define-reader-ctor SYMBOL PROC)]
Define new read-time constructor for \texttt{\#,} read syntax. For further information, see
the documentation for SRFI-10\urlfootnote{http://srfi.schemers.org/srfi-10/srfi-10.html}.

\item[{[}procedure{]} (eval EXP {[}ENVIRONMENT{]})]
Evaluates \texttt{EXP} and returns the result of the evaluation. The second argument is optional
and defaults to the value of \texttt{(interaction-environment)}.

\end{description}


\section{Unit: extras}


This unit contains a collection of useful utility definitions.


\subsection{Lists}


\begin{description}

\item[{[}procedure{]} (butlast LIST)]
Returns a fresh list with all elements but the last of \texttt{LIST}.

\item[{[}procedure{]} (chop LIST N)]
Returns a new list of sublists, where each sublist contains \texttt{N}
elements of \texttt{LIST}. If \texttt{LIST} has a length that is not
a multiple of \texttt{N}, then the last sublist contains the remaining
elements.

\begin{verbatim}
(chop '(1 2 3 4 5 6) 2) ==> ((1 2) (3 4) (5 6))
(chop '(a b c d) 3)     ==> ((a b c) (d))
\end{verbatim}

\item[{[}procedure{]} (compress BLIST LIST)]
Returns a new list with elements taken from \texttt{LIST} with
corresponding true values in the list \texttt{BLIST}.

\begin{verbatim}
(define nums '(99 100 110 401 1234))
(compress (map odd? nums) nums)      ==> (99 401)
\end{verbatim}

\item[{[}procedure{]} (flatten LIST1 ...)]
Returns \texttt{LIST1 \ldots} concatenated together, with nested lists
removed (flattened).

\item[{[}procedure{]} (intersperse LIST X)]
Returns a new list with \texttt{X} placed between each element.

\item[{[}procedure{]} (join LISTOFLISTS {[}LIST{]})]
Concatenates the lists in \texttt{LISTOFLISTS} with \texttt{LIST} placed
between each sublist. \texttt{LIST} defaults to the empty list.

\begin{verbatim}
(join '((a b) (c d) (e)) '(x y)) ==> (a b x y c d x y e)
(join '((p q) () (r (s) t)) '(-))  ==> (p q - - r (s) t)
\end{verbatim}


\texttt{join} could be implemented as follows:

\begin{verbatim}
(define (join lstoflsts . lst)
  (apply append (intersperse lstoflists (:optional lst '()))) )
\end{verbatim}

\item[{[}procedure{]} (tail? X LIST)]
Returns true if \texttt{X} is one of the tails (cdr's) of \texttt{LIST}.

\end{description}


\subsection{String-port extensions}


\begin{description}

\item[{[}procedure{]} (call-with-input-string STRING PROC)]
Calls the procedure \texttt{PROC} with a single argument that is a
string-input-port with the contents of \texttt{STRING}.

\item[{[}procedure{]} (call-with-output-string PROC)]
Calls the procedure \texttt{PROC} with a single argument that is a
string-output-port.  Returns the accumulated output-string.

\item[{[}procedure{]} (with-input-from-string STRING THUNK)]
Call procedure \texttt{THUNK} with the current input-port temporarily
bound to an input-string-port with the contents of \texttt{STRING}.

\item[{[}procedure{]} (with-output-to-string THUNK)]
Call procedure \texttt{THUNK} with the current output-port temporarily
bound to a string-output-port and return the accumulated output string.

\end{description}


\subsection{Formatted output}


\begin{description}

\item[{[}procedure{]} (fprintf PORT FORMATSTRING ARG ...)]
\item[{[}procedure{]} (printf FORMATSTRING ARG)]
\item[{[}procedure{]} (sprintf FORMATSTRING ARG ...)]
Simple formatted output to a given port (\texttt{fprintf}), the
value of \texttt{(current-output-port) } (\texttt{printf}) or a string
(\texttt{sprintf}).  The \texttt{FORMATSTRING} can contain any sequence
of characters. The character '\~{ }' prefixes special formatting directives:

\begin{tabular}{|ll}
\hline
\~{ }\%&   write newline character\\
\~{ }S&    write the next argument\\
\~{ }A&   display the next argument\\
\~{ }{\textbackslash}n&   skip all whitespace in the format-string until the next non-whitespace\\ 
            character
\~{ }B&   write the next argument as a binary number\\
\~{ }O&   write the next argument as an octal number\\
\~{ }X&   write the next argument as a hexadecimal number\\
\~{ }C&   write the next argument as a character\\
\~{ }\~{ } &   display '~'\\
\~{ }!&   flush all pending output\\
\~{ }?&   invoke formatted output routine recursively with the next two arguments\\ as format-string and list of
                parameters\\
\hline \end{tabular}

For more powerful output formatting, see the section about the \texttt{format} unit.

\end{description}


\subsection{Hash tables}


\begin{description}

\item[{[}procedure{]} (clear-hash-table! HASH-TABLE)]
Erases all entries in the hash-table \texttt{HASH-TABLE}.

\item[{[}procedure{]} (get HASH-TABLE KEY PROP)]
Returns the value of property \texttt{PROP} of the item \texttt{KEY}
in \texttt{HASH-TABLE }. This facility can be used as a kind of
``disembodied'' property-list. If no entry named \texttt{KEY} is stored
in the hash-table or if no property \texttt{PROP} for that key exists,
\texttt{\#f} is returned.

\item[{[}procedure{]} (hash-table? X)]
Returns \texttt{\#t} if the argument is a hash-table.

\item[{[}procedure{]} (hash-table{\tt->}list HASH-TABLE)]
Converts \texttt{HASH-TABLE} into an association-list.

\item[{[}procedure{]} (hash-table-count HASH-TABLE)]
Returns the number of entries in the given hash-table.

\item[{[}procedure{]} (hash-table-for-each PROC HASH-TABLE)]
Calls \texttt{PROC} which should expect two arguments. This procedure
is called for each entry in the hash-table with the key and the value
as parameters.

\item[{[}procedure{]} (hash-table-ref HASH-TABLE KEY {[}DEFAULT{]})]
Returns the entry in the given hash-table under \texttt{KEY}. If no
entry is stored in the table, \texttt{\#f} is returned.

\item[{[}procedure{]} (hash-table-remove! HASH-TABLE KEY)]
Removes an entry in the given hash-table.

\item[{[}procedure{]} (hash-table-set! HASH-TABLE KEY VALUE)]
Adds or changes an entry in the given hash-table.

\item[{[}procedure{]} (make-hash-table {[}PRED {[}SIZE{]}{]})]
Creates and returns a hash-table with keys compared via \texttt{PRED},
which defaults to \texttt{eq?}. If \texttt{SIZE} is provided it specifies
the initial size of the hash-table.  If the hash-table fills above a
certain size it is automatically resized to accommodate more entries.

\item[{[}procedure{]} (put! HASH-TABLE KEY PROP VALUE)]
Stores \texttt{VALUE} as property \texttt{PROP} under the item
\texttt{KEY} in the given hash-table. Any previously existing value
is overwritten.

\end{description}


\subsection{Queues}


\begin{description}

\item[{[}procedure{]} (list{\tt->}queue LIST)]
Returns \texttt{LIST} converted into a queue, where the first element
of the list is the same as the first element of the queue. The resulting
queue may share memory with the list and the list should not be modified
after this operation.

\item[{[}procedure{]} (make-queue)]
Returns a newly created queue.

\item[{[}procedure{]} (queue? X)]
Returns \texttt{\#t} if \texttt{X} is a queue, or \texttt{\#f} otherwise.

\item[{[}procedure{]} (queue{\tt->}list QUEUE)]
Returns \texttt{QUEUE} converted into a list, where the first element
of the list is the same as the first element of the queue. The resulting
list may share memory with the queue object and should not be modified.

\item[{[}procedure{]} (queue-add! QUEUE X)]
Adds \texttt{X} to the rear of \texttt{QUEUE}.

\item[{[}procedure{]} (queue-empty? QUEUE)]
Returns \texttt{\#t} if \texttt{QUEUE} is empty, or \texttt{\#f} otherwise.

\item[{[}procedure{]} (queue-first QUEUE)]
Returns the first element of \texttt{QUEUE}. If \texttt{QUEUE} is empty
an error is signaled

\item[{[}procedure{]} (queue-last QUEUE)]
Returns the last element of \texttt{QUEUE}. If \texttt{QUEUE} is empty
an error is signaled

\item[{[}procedure{]} (queue-remove! QUEUE)]
Removes and returns the first element of \texttt{QUEUE}. If \texttt{QUEUE}
is empty an error is signaled

\end{description}


\subsection{Sorting}


\begin{description}

\item[{[}procedure{]} (merge LIST1 LIST2 LESS?)]
\item[{[}procedure{]} (merge! LIST1 LIST2 LESS?)]
Joins two lists in sorted order. \texttt{merge!} is the destructive
version of merge. \texttt{LESS?  } should be a procedure of two arguments,
that returns true if the first argument is to be ordered before the
second argument.

\item[{[}procedure{]} (sort SEQUENCE LESS?)]
\item[{[}procedure{]} (sort! SEQUENCE LESS?)]
Sort \texttt{SEQUENCE}, which should be a list or a vector. \texttt{sort!}
is the destructive version of sort.

\item[{[}procedure{]} (sorted? SEQUENCE LESS?)]
Returns true if the list or vector \texttt{SEQUENCE} is already sorted.

\end{description}


\subsection{Random numbers}


\begin{description}

\item[{[}procedure{]} (random N)]
Returns an exact random integer from 0 to \texttt{N}-1.

\item[{[}procedure{]} (randomize {[}X{]})]
Set random-number seed. If \texttt{X} is not supplied, the current time is used.

\end{description}


\subsection{Input/Output extensions}


\begin{description}

\item[{[}procedure{]} (make-input-port READ READY? CLOSE {[}PEEK{]})]
Returns a custom input port. Common operations on this
port are handled by the given parameters, which should be
procedures of no arguments. \texttt{READ} is called when the
next character is to be read and should return a character or
the value of \texttt{(end-of-file)}. \texttt{READY?} is called
when \texttt{char-ready?} is called on this port and should return
\texttt{\#t} or \texttt{\#f}.  \texttt{CLOSE} is called when the port is
closed. \texttt{PEEK} is called when \texttt{peek-char} is called on this
port and should return a character or the value of \texttt{(end-of-file)}.
if the argument \texttt{PEEK} is not given, then \texttt{READ} is used
instead and the created port object handles peeking automatically (by
calling \texttt{READ} and buffering the character).

\item[{[}procedure{]} (make-output-port WRITE CLOSE [FLUSH])]
Returns a custom output port. Common operations on this port are handled
by the given parameters, which should be procedures.  \texttt{WRITE} is
called when output is sent to the port and receives a single argument,
a string.  \texttt{CLOSE} is called when the port is closed and should
be a procedure of no arguments. \texttt{FLUSH} (if provided) is called
for flushing the output port.

\item[{[}procedure{]} (pretty-print EXP {[}PORT{]})]
Print expression nicely formatted. \texttt{PORT} defaults to the value
of \texttt{(current-output-port)}.

\item[{[}parameter{]} pretty-print-width]
Specifies the maximal line-width for pretty printing, after which line
wrap will occur.

\item[{[}procedure{]} (read-file {[}PORT{]})]
Returns a list containing all toplevel expressions
read from \texttt{PORT}, which defaults to the value of
\texttt{(current-input-port)}.

\item[{[}procedure{]} (read-line [PORT [LIMIT]])]
\item[{[}procedure{]} (write-line STRING [PORT])]
Line-input and -output. \texttt{PORT} defaults to the value of
\texttt{(current-input-port)} and \texttt{(current-output-port)},
respectively. if the optional argument \texttt{LIMIT} is given and
not \texttt{\#f}, then \texttt{read-line} reads at most \texttt{LIMIT}
characters per line.

\item[{[}procedure{]} (read-lines {[}PORT {[}MAX{]}{]})]
Read \texttt{MAX} or fewer lines from \texttt{PORT}. \texttt{PORT}
defaults to the value of \texttt{(current-input-port)}.

\item[{[}procedure{]} (read-string NUM {[}PORT{]})]
Read \texttt{NUM} characters from \texttt{PORT}, which defaults to the
value of \texttt{(current-input-port)}. The characters are returned as
a string of length \texttt{NUM} or less, if the port contains fewer than
\texttt{NUM} characters. If \texttt{NUM} is \texttt{\#f}, then all data
up to the end-of-file is read.

\item[{[}procedure{]} (with-error-output-to-port PORT THUNK)]
Call procedure \texttt{THUNK} with the current error output-port
temporarily bound to \texttt{PORT}.

\item[{[}procedure{]} (with-input-from-port PORT THUNK)]
Call procedure \texttt{THUNK} with the current input-port temporarily
bound to \texttt{PORT}.

\item[{[}procedure{]} (with-output-to-port PORT THUNK)]
Call procedure \texttt{THUNK} with the current output-port temporarily
bound to \texttt{PORT}.

\end{description}

\subsection{Strings}

\begin{description}

\item[{[}procedure{]} ({\tt->}string X)]
Returns a string-representation of \texttt{X}.

\item[{[}procedure{]} (string-intersperse LIST STRING)]
Returns a string that contains all strings in \texttt{LIST} concatenated
together.  \texttt{STRING} is placed between each concatenated string.

\begin{verbatim}
(string-intersperse '("one" "two") "three")
\end{verbatim}

is equivalent to

\begin{verbatim}
(apply string-append (intersperse '("one" "two") "three"))
\end{verbatim}

\item[{[}procedure{]} (string-split STRING {[}DELIMITER-STRING {[}KEEPEMPTY{]}{]})]
Split string into substrings separated by the given delimiters. If
no delimiters are specified, a string comprising the tab, newline and space characters 
is assumed. If the
parameter \texttt{KEEPEMPTY} is given and not \texttt{\#f}, then empty
substrings are retained:

\begin{verbatim}
(string-split "one  two  three") ==> ("one" "two" "three")
(string-split "foo:bar::baz:" ":" #t) ==> ("foo" "bar" "" "baz" "")
\end{verbatim}

\item[{[}procedure{]} (string-translate STRING FROM {[}TO{]})]
Returns a fresh copy of \texttt{STRING} with characters matching
\texttt{FROM} translated to \texttt{TO}.  If \texttt{TO} is omitted, then
matching characters are removed. \texttt{FROM} and \texttt{TO} may be
a character, a string or a list. If both \texttt{FROM} and \texttt{TO}
are strings, then the character at the same position in \texttt{TO}
as the matching character in \texttt{FROM} is substituted.

\item[{[}procedure{]} (substring-index WHICH WHERE [START])]
\item[{[}procedure{]} (substring-index-ci WHICH WHERE [START])]
Searches for first index in string \texttt{WHERE} where string
\texttt{WHICH} occurs.  If the optional argument \texttt{START} is given,
then the search starts at that index.  \texttt{substring-index-ci}
is a case-insensitive version of \texttt{substring-index}.

\end{description}


\subsection{Miscellaneous}


\begin{description}

\item[{[}procedure{]} (binary-search SEQUENCE PROC)]
Performs a binary search in \texttt{SEQUENCE}, which should be a sorted
list or vector.  \texttt{PROC} is called to compare items in the sequence,
should accept a single argument and return an exact integer: zero if the
searched value is equal to the current item, negative if the searched
value is ``less'' than the current item, and positive otherwise.

\item[{[}procedure{]} (constantly X ...)]
Returns a procedure that always returns the values \texttt{X ...} regardless of the number and value of its arguments.

\begin{verbatim}
(constantly X) <=> (lambda args X)
\end{verbatim}

\item[{[}procedure{]} (complement PROC)]
Returns a procedure that returns the boolean inverse of \texttt{PROC}.
\begin{verbatim}
(complement PROC) <=> (lambda (x) (not (PROC x)))
\end{verbatim}

\item[{[}procedure{]} (compose PROC1 PROC2 ...)]
Returns a procedure that represents the composition of the
argument-procedures \texttt{PROC1 PROC2 ...}.

\begin{verbatim}
(compose F G) <=> (lambda args (call-with-values (lambda () (apply G args)) F))
\end{verbatim}

\item[{[}procedure{]} (flip PROC)]
Returns a two-argument procedure that calls \texttt{PROC} with its
arguments swapped:
\begin{verbatim}
(flip PROC) <=> (lambda (x y) (PROC y x))
\end{verbatim}

\item[{[}procedure{]} (list-of PRED)]
Returns a procedure of one argument that returns \texttt{\#t} when
applied to a list of elements that all satisfy the predicate procedure
\texttt{PRED}, or \texttt{\#f} otherwise.

\begin{verbatim}
((list-of even?) '(1 2 3))   ==> #f
((list-of number?) '(1 2 3)) ==> #t
\end{verbatim}

\end{description}

\section{Unit: srfi-1}

List library, see the documentation for
SRFI-1\urlfootnote{http://srfi.schemers.org/srfi-1/srfi-1.html}

\section{Unit: srfi-4} \label{srfi4}

Homogeneous numeric vectors, see the documentation for SRFI-4
\urlfootnote{http://srfi.schemers.org/srfi-4/srfi-4.html}
In addition to that, the following procedures are also provided:

\begin{description}
\item[{[}procedure{]} (u8vector{\tt->}byte-vector U8VECTOR)]
\item[{[}procedure{]} (s8vector{\tt->}byte-vector S8VECTOR)]
\item[{[}procedure{]} (u16vector{\tt->}byte-vector U16VECTOR)]
\item[{[}procedure{]} (s16vector{\tt->}byte-vector S16VECTOR)]
\item[{[}procedure{]} (u32vector{\tt->}byte-vector U32VECTOR)]
\item[{[}procedure{]} (s32vector{\tt->}byte-vector S32VECTOR)]
\item[{[}procedure{]} (f32vector{\tt->}byte-vector F32VECTOR)]
\item[{[}procedure{]} (f64vector{\tt->}byte-vector F64VECTOR)]
Each of these procedures return the contents of the given vector as a
'packed' byte-vector. The byte order in that vector is platform-dependent
(for example little-endian on an \textbf{Intel} processor). The returned
byte-vector shares memory with the contents of the vector.

\item[{[}procedure{]} (byte-vector{\tt->}u8vector BYTE-VECTOR)]
\item[{[}procedure{]} (byte-vector{\tt->}s8vector BYTE-VECTOR)]
\item[{[}procedure{]} (byte-vector{\tt->}u16vector BYTE-VECTOR)]
\item[{[}procedure{]} (byte-vector{\tt->}s16vector BYTE-VECTOR)]
\item[{[}procedure{]} (byte-vector{\tt->}u32vector BYTE-VECTOR)]
\item[{[}procedure{]} (byte-vector{\tt->}s32vector BYTE-VECTOR)]
\item[{[}procedure{]} (byte-vector{\tt->}f32vector BYTE-VECTOR)]
\item[{[}procedure{]} (byte-vector{\tt->}f64vector BYTE-VECTOR)]
Each of these procedures return a vector where the argument
\texttt{BYTE-VECTOR} is taken as a 'packed' representation of the contents
of the vector. The argument-byte-vector shares memory with the contents
of the vector.

\end{description}


\section{Unit: srfi-13} \label{srfi13}


String library, see the documentation for
SRFI-13\urlfootnote{http://srfi.schemers.org/srfi-13/srfi-13.html}

The file \texttt{srfi-13-syntax.scm} contains macro definitions for
\texttt{let-string-start+end}.


On systems that support dynamic loading, the \texttt{srfi-13} unit can
be made available in the interpreter (\texttt{csi}) by entering

\begin{verbatim}
(require 'srfi-13)
\end{verbatim}

\section{Unit: srfi-14}

Character set library, see the documentation for
SRFI-14\urlfootnote{http://srfi.schemers.org/srfi-14/srfi-14.html}

On systems that support dynamic loading, the \texttt{srfi-14} unit can
be made available in the interpreter (\texttt{csi}) by entering

\begin{verbatim}
(require 'srfi-14)
\end{verbatim}

\begin{itemize}
\item This library provides only the Latin-1 character set.
\end{itemize}

\section{Unit: srfi-25}

Multi-dimensional array, see the documentation for
SRFI-25\urlfootnote{http://srfi.schemers.org/srfi-25/srfi-25.html}

On systems that support dynamic loading, the \texttt{srfi-25} unit can
be made available in the interpreter (\texttt{csi}) by entering

\begin{verbatim}
(require 'srfi-25)
\end{verbatim}

\section{Unit: match}

Andrew Wright's pattern matching package. Note that to use the macros in
normal compiled code it is not required to declare this unit as used. Only
if forms containing these macros are to be expanded at runtime, this
is needed.

\begin{description}

\item[{[}syntax{]} (match EXP CLAUSE ...)]
\item[{[}syntax{]} (match-lambda CLAUSE ...)]
\item[{[}syntax{]} (match-lambda* CLAUSE ...)]
\item[{[}syntax{]} (match-let ((PAT EXP) ...) BODY)]
\item[{[}syntax{]} (match-let* ((PAT EXP) ...) BODY)]
\item[{[}syntax{]} (match-letrec ((PAT EXP) ...) BODY)]
\item[{[}syntax{]} (match-define PAT EXP)]
Match expression or procedure arguments with pattern and
execute associated expressions.  A Postscript manual is
available\urlfootnote{http://www.call-with-current-continuation.org/match.ps}.

\item[{[}syntax{]} (define-structure (ID\_0 ID\_1 ... ID\_N))]
\item[{[}syntax{]} (define-structure (ID\_0 ID\_1 ... ID\_N) ((ID\_{N+1} EXP\_1) ... (ID\_{N+M} EXP\_M)))]
\item[{[}syntax{]} (define-const-structure (ID\_0 ARG\_1 ... ARG\_N))]
\item[{[}syntax{]} (define-const-structure (ID\_0 ARG\_1 ... ARG\_N) ((ARG\_{N+1} EXP\_1) ... (ARG\_{N+M} EXP\_M)))]
Macros for defining record structures that can be decomposed by \texttt{match}.

\item[(match-error-control {[}MODE{]})]
Selects a mode that specifies how \texttt{match...} macro forms are to
be expanded.  With no argument this procedure returns the current mode. A
single argument specifies the new mode that decides what should happen
if no match-clause applies.  The following modes are supported:

\begin{description}

\item[\#:error]
Signal an error. This is the default.

\item[\#:match]
Signal an error and output the offending form.

\item[\#:fail]
Omits \texttt{pair?} tests when the consequence is to fail in \texttt{car}
or \texttt{cdr} rather than to signal an error.

\item[\#:unspecified]
Non-matching expressions will either fail in \texttt{car} or \texttt{cdr}
or return an unspecified value.  This mode applies to files compiled
with the \texttt{unsafe} option or declaration.

\end{description}

\end{description}

Note: \texttt{match:structure-control} is not available. Structures
defined by the macros provided in this unit are always implemented
as vectors.  \texttt{match:runtime-structures} is also not available.

To use the pattern matching macros with the highlevel (\texttt{syntax-case})
macro system, load the macro definitions with \texttt{(include "match")}
or \texttt{(require-for-syntax 'match)}.


\section{Unit: regex}


\begin{description}

\item[{[}procedure{]} (grep REGEX LIST)]
Returns all items of \texttt{LIST} that match the regular expression
\texttt{REGEX}.  This procedure could be defined as follows:

\begin{verbatim}
(define (grep regex lst)
  (filter (lambda (x) (string-match regex x)) lst) )
\end{verbatim}

\item[{[}procedure{]} (pattern{\tt->}regexp PATTERN)]
Converts the file-pattern \texttt{PATTERN} into a regular expression.

\begin{verbatim}
(pattern->regexp "foo.*") ==> "foo\..*"
\end{verbatim}

\item[{[}procedure{]} (regexp STRING)]
Returns a precompiled regular expression object for \texttt{string}.

\item[{[}procedure{]} (regexp? X)]
Returns \texttt{\#t} if \texttt{X} is a precompiled regular expression,
or \texttt{\#f} otherwise.

\item[{[}procedure{]} (string-match REGEXP STRING [START])]
\item[{[}procedure{]} (string-match-positions REGEXP STRING [START])]
Matches the regular expression in \texttt{REGEXP} (a string or a precompiled
regular expression) with
\texttt{STRING} and returns either \texttt{\#f} if the match failed,
or a list of matching groups, where the first element is the complete
match. If the optional argument \texttt{START} is supplied, it specifies
the starting position in \texttt{STRING}.  For each matching group the
result-list contains either: \texttt{\#f} for a non-matching but optional
group; a list of start- and end-position of the match in \texttt{STRING}
(in the case of \texttt{string-match-positions}); or the matching
substring (in the case of \texttt{string-match}).

\item[{[}procedure{]} (string-search REGEXP STRING [START [RANGE]])]
\item[{[}procedure{]} (string-search-positions REGEXP STRING [START [RANGE]])]
Searches for the first match of the regular expression in
\texttt{REGEXP} with \texttt{STRING}. The search can be limited to
\texttt{RANGE} characters.  Otherwise the procedures have the same
behaviour as \texttt{string-match} / \texttt{string-match-positions}.

\item[{[}procedure{]} (string-split-fields REGEXP STRING {[}MODE {[}START{]}{]})]
Splits \texttt{STRING} into a list of fields according to \texttt{MODE},
where \texttt{MODE} can be the keyword \texttt{\#:infix} (\texttt{REGEXP}
matches field separator), the keyword \texttt{\#:suffix} (\texttt{REGEXP}
matches field terminator) or \texttt{\#t} (\texttt{REGEXP} matches field),
which is the default.

\item[{[}procedure{]} (string-substitute REGEXP SUBST STRING {[}INDEX{]})]
Searches substrings in \texttt{STRING} that match \texttt{REGEXP}
and substitutes them with the string \texttt{SUBST}. The substitution
can contain references to subexpressions in 
% XXX is \\NUM right?
\texttt{REGEXP} with the \texttt{\\NUM} notation, where \texttt{NUM}
refers to the NUMth parenthesized expression. The optional argument
\texttt{INDEX} defaults to 1 and specifies the number of the match to
be substituted. Any non-numeric index specifies that all matches are to
be substituted.

\begin{verbatim}
(string-substitute "([0-9]+) (eggs|chicks)" "\\2 (\\1)" "99 eggs or 99 chicks" 2)
 ==> "99 eggs or chicks (99)"
\end{verbatim}

\end{description}

\section{Unit: syntax-case}

Hieb's and Dybvig's hygienic macro package. Provides \texttt{syntax-case}
and \texttt{syntax-rules}. A postscript manual can be found here:
Indiana University Computer Science Department, Technical Report \#356
\urlfootnote{http://www.call-with-current-continuation.org/tr356.ps}

\textbf{Notes:}
\begin{itemize}

\item The alternative form
\begin{verbatim}
(define-syntax (keyword var) ...)
\end{verbatim}
is allowed for \texttt{define-syntax}.

\item The module system described in the Chez Scheme Uses Manual is
provided. Note that this module system does not facilitate separate
compilation.

\item To use the macro-system in compiled or interpreted code, just give
the \texttt{-hygienic} option to the compiler or interpreter. The \texttt{syntax-case} unit has
only to be declared as used if compiled code invokes \texttt{macroexpand}
or \texttt{eval} with high-level macro syntax forms.

\item The macros \texttt{define-id-macro, let-macro} and \texttt{let-id-macro} 
and the procedures
\texttt{undefine-macro!} and \texttt{macro?} can currently not be used.

\item \texttt{define-values} is not allowed in internal definitions.

\item \texttt{define-syntax} can not be used inside an \texttt{eval-when} form.

\end{itemize}

\section{Unit: srfi-18}

A simple multithreading package. This threading package follows largely
the specification of SRFI-18. For more information see the documentation
for SRFI-18\urlfootnote{http://srfi.schemers.org/srfi-18/srfi-18.html}

\textbf{Notes:}

\begin{itemize}

\item Blocking I/O will block all threads, except for some socket operations
(see the section about the \texttt{tcp} unit).

\item It is generally not a good idea for one thread to call a
continuation created by another thread, if \texttt{dynamic-wind}
is involved.

\item When more than one thread compete for the current time-slice,
the thread that was waiting first will become the next runnable thread.

\item The dynamic environment of a thread consists of the following state:

 \begin{itemize}

 \item The current input-, output- and error-port

 \item The current exception handler

 \item The values of all current parameters (created by \texttt{make-parameter})

 \item Any pending \texttt{dynamic-wind} thunks.

 \end{itemize}

\end{itemize}

\begin{description}

\item[{[}procedure{]} (thread-quantum THREAD)]
Returns the quantum of \texttt{THREAD}, which is an exact integer
specifying the approximate time-slice of the thread.

\item[{[}procedure{]} (thread-quantum-set! THREAD QUANTUM)]
Sets the quantum of \texttt{THREAD} to \texttt{QUANTUM}.

\end{description}

\section{Unit: format}

\begin{description}

\item[{[}procedure{]} (format DESTINATION FORMAT-STRING . ARGUMENTS)]
An almost complete implementation of Common LISP format description
according to the CL reference book \textbf{Common LISP} from Guy L.
Steele, Digital Press. This code was originally part of SLIB. The author
is Dirk Lutzebaeck.

Returns \texttt{\#t}, \texttt{\#f} or a string; has side effect of
printing according to \texttt{FORMAT-STRING}.  If \texttt{DESTINATION} is
\texttt{\#t}, the output is to the current output port and \texttt{\#t}
is returned.  If \texttt{DESTINATION} is \texttt{\#f}, a formatted
string is returned as the result of the call.  If \texttt{DESTINATION}
is a string, \texttt{DESTINATION} is regarded as the format string;
\texttt{FORMAT-STRING} is then the first argument and the output
is returned as a string. If \texttt{DESTINATION} is a number, the
output is to the value of \texttt{(current-error-port)}.  Otherwise
\texttt{DESTINATION} must be an output port and \texttt{\#t} is returned.

\texttt{FORMAT-STRING} must be a string.  In case of a formatting
error format returns \texttt{\#f} and prints a message on the value
of \texttt{(current-error-port)}.  Characters are output as if the
string were output by the \texttt{display} function with the exception
of those prefixed by a tilde (\~{ }).  For a detailed description of
the \texttt{FORMAT-STRING} syntax please consult a Common LISP format
reference manual. A list of all supported, non-supported and extended
directives can be found in \texttt{format.txt}.

This unit uses definitions from the \texttt{extras} unit.

\texttt{format} implements
SRFI-28\urlfootnote{http//srfi.schemers.org/srfi-28/srfi-28.html}

\end{description}

\section{Unit: posix}

This unit provides services as used on many UNIX-like systems.  Note that
the following definitions are not availabe on non-UNIX systems like
Windows or DOS.

This unit uses the \texttt{regex} and \texttt{extras} units.

\subsection{Directories}

\begin{description}

\item[{[}procedure{]} (change-directory NAME)]
Changes the current working directory to \texttt{NAME}.

\item[{[}procedure{]} (current-directory)]
Returns the name of the current working directory.

\item[{[}procedure{]} (create-directory NAME)]
Creates a directory with the pathname \texttt{NAME}.

\item[{[}procedure{]} (delete-directory NAME)]
Deletes the directory with the pathname \texttt{NAME}. The directory has
to be empty.

\item[{[}procedure{]} (directory PATHNAME)]
Returns a list with all files that are contained in the directory with the name \texttt{PATHNAME}.

\item[{[}procedure{]} (directory? NAME)]
Returns \texttt{\#t} if there exists a file with the name \texttt{NAME}
and if that file is a directory, or \texttt{\#f} otherwise.

\item[{[}procedure{]} (glob PATTERN1 ...)]
Returns a list of the pathnames of all existing files matching
\texttt{PATTERN1 ...}, which should be strings containing the usual
file-patterns (with \texttt{*} matching zero or more characters and
\texttt{?} matching zero or one character).

\end{description}

\subsection{Pipes}

\begin{description}

\item[{[}procedure{]} (call-with-input-pipe CMDLINE PROC [MODE])]
\item[{[}procedure{]} (call-with-output-pipe CMDLINE PROC [MODE])]
Call \texttt{PROC} with a single argument: a input- or output port
for a pipe connected to the subprocess named in \texttt{CMDLINE}. If
\texttt{PROC} returns normally, the pipe is closed and any result values
are returned.

\item[{[}procedure{]} (close-input-pipe PORT)]
\item[{[}procedure{]} (close-output-pipe PORT)]
Closes the pipe given in \texttt{PORT} and waits until the connected
subprocess finishes.

\item[{[}procedure{]} (create-pipe)]
The fundamental pipe-creation operator. Calls the C function
\texttt{pipe()} and returns 2 values: the file-descriptors of the input-
and output-ends of the pipe.

\item[{[}procedure{]} (open-input-pipe CMDLINE {[}MODE{]})]
Spawns a subprocess with the command-line string \texttt{CMDLINE} and
returns a port, from which the output of the process can be read. If
\texttt{MODE} is specified, it should be the keyword \texttt{\#:text}
(the default) or \texttt{\#:binary}.

\item[{[}procedure{]} (open-output-pipe CMDLINE {[}MODE{]})]
Spawns a subprocess with the command-line string \texttt{CMDLINE} and
returns a port. Anything written to that port is treated as the input
for the process.  If \texttt{MODE} is specified, it should be the keyword
\texttt{\#:text} (the default) or \texttt{\#:binary}.

\item[{[}limit{]} pipe/buf]
This variable contains the maximal number of bytes that can be written
atomically into a pipe or FIFO.

\item[{[}procedure{]} (with-input-from-pipe CMDLINE THUNK [MODE])]
\item[{[}procedure{]} (with-output-to-pipe CMDLINE THUNK [MODE])]
Temprorarily set the value of
\texttt{current-input-port/current-output-port} to a port for a
pipe connected to the subprocess named in \texttt{CMDLINE} and call
the procedure \texttt{THUNK} with no arguments. After \texttt{THUNK}
returns normally the pipe is closed and the standard input-/output port
is restored to its previous value and any result values are returned.

\begin{verbatim}
(with-output-to-pipe 
  "gs -dNOPAUSE -sDEVICE=jpeg -dBATCH -sOutputFile=signballs.jpg -g600x600 -q -"
  (lambda ()
    (print #<<EOF
%!IOPSC-1993 %%Creator: HAYAKAWA Takashi<xxxxxxxx@xx.xxxxxx.xx.xx>
/C/neg/d/mul/R/rlineto/E/exp/H{{cvx def}repeat}def/T/dup/g/gt/r/roll/J/ifelse 8
H/A/copy(z&v4QX&93r9AxYQOZomQalxS2w!!O&vMYa43d6r93rMYvx2dca!D&cjSnjSnjjS3o!v&6A
X&55SAxM1CD7AjYxTTd62rmxCnTdSST0g&12wECST!&!J0g&D1!&xM0!J0g!l&544dC2Ac96ra!m&3A
F&&vGoGSnCT0g&wDmlvGoS8wpn6wpS2wTCpS1Sd7ov7Uk7o4Qkdw!&Mvlx1S7oZES3w!J!J!Q&7185d
Z&lx1CS9d9nE4!k&X&MY7!&1!J!x&jdnjdS3odS!N&mmx1C2wEc!G&150Nx4!n&2o!j&43r!U&0777d
]&2AY2A776ddT4oS3oSnMVC00VV0RRR45E42063rNz&v7UX&UOzF!F!J![&44ETCnVn!a&1CDN!Y&0M
V1c&j2AYdjmMdjjd!o&1r!M){( )T 0 4 3 r put T(/)g{T(9)g{cvn}{cvi}J}{($)g{[}{]}J}J
cvx}forall/moveto/p/floor/w/div/S/add 29 H[{[{]setgray fill}for Y}for showpage
EOF
) ) )
\end{verbatim}

\end{description}


\subsection{Fifos}


\begin{description}

\item[{[}procedure{]} (create-fifo FILENAME {[}MODE{]})]
Creates a FIFO with the name \texttt{FILENAME} and the permission bits
\texttt{MODE}, which defaults to

\begin{verbatim}
(+ perm/irwxu perm/irwxg perm/irwxo)
\end{verbatim}

\item[{[}procedure{]} (fifo? FILENAME)]
Returns \texttt{\#t} if the file with the name \texttt{FILENAME} names
a FIFO.

\end{description}


\subsection{File descriptors and low-level I/O}


\begin{description}

\item[{[}procedure{]} (duplicate-fileno OLD {[}NEW{]})]
If \texttt{NEW} is given, then the file-descriptor \texttt{NEW} is opened
to access the file with the file-descriptor \texttt{OLD}. Otherwise a
fresh file-descriptor accessing the same file as \texttt{OLD} is returned.

\item[{[}procedure{]} (file-close FILENO)]
Closes the input/output file with the file-descriptor \texttt{FILENO}.

\item[{[}procedure{]} (file-open FILENAME FLAGS {[}MODE{]})]
Opens the file specified with the string \texttt{FILENAME} and open-flags
\texttt{FLAGS} using the C function \texttt{open()}. On success a
file-descriptor for the opened file is returned.  \texttt{FLAGS}
should be a bitmask containing one or more of the \texttt{open/...}
values \textbf{or}ed together using \texttt{bitwise-ior} (or simply added
together).  The optional \texttt{MODE} should be a bitmask composed of one
or more permission values like \texttt{perm/irusr} and is only relevant
when a new file is created. The default mode is \texttt{perm/irwxu $|$
perm/irgrp $|$ perm/iroth}.

\item[{[}procedure{]} (file-read FILENO SIZE {[}BUFFER{]})]
Reads \texttt{SIZE} bytes from the file with the file-descriptor
\texttt{FILENO}.  If a string or bytevector is passed in the optional
argument \texttt{BUFFER}, then this string will be destructively modified
to contain the read data. This procedure returns a list with two values:
the buffer containing the data and the number of bytes read.

\item[{[}procedure{]} (file-select READFDLIST WRITEFDLIST {[}TIMEOUT{]})]
Waits until any of the file-descriptors given in the lists
\texttt{READFDLIST} and \texttt{WRITEFDLIST} is ready for input or
output, respectively. If the optional argument \texttt{TIMEOUT} is
given and not false, then it should specify the number of seconds after
which the wait is to be aborted. This procedure returns two values:
the lists of file-descriptors ready for input and output, respectively.
\texttt{READFDLIST} and \textbf{WRITEFDLIST} may also by file-descriptors
instead of lists.  In this case the returned values are booleans
indicating wether input/output is ready by \texttt{\#t} or \texttt{\#f}
otherwise.  You can also pass \texttt{\#f} as \texttt{READFDLIST} or
\texttt{WRITEFDLIST} argument, which is equivalent to \texttt{()}.

\item[{[}procedure{]} (file-write FILENO BUFFER {[}SIZE{]})]
Writes the contents of the string or bytevector \texttt{BUFFER} into
the file with the file-descriptor \texttt{FILENO}. If the optional
argument \texttt{SIZE} is given, then only the specified number of bytes
are written.

\item[{[}file descriptor{]} fileno/stdin]
\item[{[}file descriptor{]} fileno/stdout]
\item[{[}file descriptor{]} fileno/stderr]
These variables contain file-descriptors for the standard I/O files.

\item[{[}flag{]} open/rdonly]
\item[{[}flag{]} open/wronly]
\item[{[}flag{]} open/rdwr]
\item[{[}flag{]} open/read] 
\item[{[}flag{]} open/write] 
\item[{[}flag{]} open/creat]
\item[{[}flag{]} open/append] 
\item[{[}flag{]} open/excl]
\item[{[}flag{]} open/noctty] 
\item[{[}flag{]} open/nonblock] 
\item[{[}flag{]} open/trunc]
\item[{[}flag{]} open/sync]
\item[{[}flag{]} open/fsync]
\item[{[}flag{]} open/binary]
\item[{[}flag{]} open/text]
Flags for use with \texttt{file-open}.

\item[{[}procedure{]} (open-input-file* FILENO [OPENMODE])]
\item[{[}procedure{]} (open-output-file* FILENO [OPENMODE])]
Opens file for the file-descriptor \texttt{FILENO} for input or output
and returns a port.  \texttt{FILENO} should be a positive exact integer.
\texttt{OPENMODE} specifies an additional mode for opening the file
(currently only the keyword \texttt{\#:append} is supported, which opens
an output-file for appending).

\item[{[}procedure{]} (port{\tt->}fileno PORT)]
If \texttt{PORT} is a file-port, then a file-descriptor is returned for
this port. Otherwise an error is signaled.

\end{description}


\subsection{Retrieving file attributes}


\begin{description}

\item[{[}procedure{]} (file-modification-time FILE)]
Returns time of last modification of \texttt{FILE}. \texttt{FILE}
may be a filename or a file-descriptor. If the file does not exist,
an error is signaled.

\item[{[}procedure{]} (file-position FILE)]
Returns the current file position of \texttt{FILE}, which should be a
port or a file-descriptor.

\item[{[}procedure{]} (file-size FILENAME)]
Returns the size of the file designated by \texttt{FILE}.  \texttt{FILE}
may be a filename or a file-descriptor.  If the file does not exist,
an error is signaled.

\end{description}


\subsection{Changing file attributes}


\begin{description}

\item[{[}procedure{]} (file-truncate FILE OFFSET)]
Truncates the file \texttt{FILE} to the length \texttt{OFFSET},
which should be an integer. If the file-size is smaller or equal to
\texttt{OFFSET} then nothing is done.  \texttt{FILE} should be a filename
or a file-descriptor.

\item[{[}procedure{]} (set-file-position! FILE POSITION {[}WHENCE{]})]
Sets the current read/write position of \texttt{FILE} to
\texttt{POSITION}, which should be an exact integer. \texttt{FILE}
should be a port or a file-descriptor.  \texttt{WHENCE} specifies
how the position is to interpreted and should be one of the values
\texttt{seek/set, seek/cur} and \texttt{seek/end}. It defaults to
\texttt{seek/set}.

\end{description}


\subsection{Processes}


\begin{description}

\item[{[}procedure{]} (current-process-id)]
Returns the process ID of the current process.

\item[{[}procedure{]} (parent-process-id)]
Returns the process ID of the parent of the current process.

\item[{[}procedure{]} (process-execute PATHNAME {[}LIST{]})]
Creates a new child process and replaces the running process with it
using the UNIX system call \texttt{execv()}. If the optional argument
\texttt{LIST} is given, then it should contain a list of strings which
are passed as arguments to the subprocess.

\item[{[}procedure{]} (process-fork {[}THUNK{]})]
Creates a new child process with the UNIX system call
\texttt{fork()}. Returns either the PID of the child process or 0. If
\texttt{THUNK} is given, then the child process calls it as a procedure
with no arguments and terminates.

\item[{[}procedure{]} (process-run PATHNAME {[}LIST{]})]
Creates a new child process using the UNIX system call \texttt{fork()}
that executes the program given by the string \texttt{PATHNAME} using
the UNIX system call \texttt{execv()}.  The PID of the new process is
returned. If \texttt{LIST} is not specified, then \texttt{PATHNAME}
is passed to a program named by the environment variable \texttt{SHELL}
(or \texttt{/bin/sh}, if the variable is not defined), so usual argument
expansion can take place.

\item[{[}procedure{]} (process-signal PID {[}SIGNAL{]})]
Sends \texttt{SIGNAL} to the process with the id \texttt{PID} using the
UNIX system call \texttt{kill()}. \texttt{SIGNAL} defaults to the value
of the variable \texttt{signal/term}.

\item[{[}procedure{]} (process-wait {[}PID {[}NOHANG{]}{]})]
Suspends the current process until the child process with
the id \texttt{PID} has terminated using the UNIX system call
\texttt{waitpid()}. If \texttt{PID} is not given, then this procedure
waits for any child process. If \texttt{NOHANG} is given and not
\texttt{\#f} then the current process is not suspended.  This procedure
returns three values:

\item \texttt{PID} or 0, if \texttt{NOHANG} is true and the child process
has not terminated yet;

\item \texttt{\#t} if the process exited normally or \texttt{\#f}
otherwise;

\item either the exit status, if the process terminated normally or the
signal number that terminated/stopped the process.

\item[{[}procedure{]} (process COMMANDLINE)]
Passes the string \texttt{COMMANDLINE} to the host-system's shell that
is invoked as a subprocess and returns three values: an input port from
which data written by the sub-process can be read, an output port from
which any data written to will be received as input in the sub-process
and the process-id of the started sub-process.

\item[{[}procedure{]} (sleep SECONDS)]
Puts the process to sleep for \texttt{SECONDS}. Returns either 0 if
the time has completely elapsed, or the number of remaining seconds,
if a signal occurred.

\end{description}

\subsection{Symbolic links}

\begin{description}

\item[{[}procedure{]} (create-symbolic-link OLDNAME NEWNAME)]
Creates a symbolic link with the filename \texttt{NEWNAME} that points
to the file named \texttt{OLDNAME}.

\item[{[}procedure{]} (read-symbolic-link FILENAME)]
Returns the filename to which the symbolic link \texttt{FILENAME} points.

\end{description}


\subsection{Permissions, owners, users and groups}


\begin{description}

\item[{[}procedure{]} (file-owner FILE)]
Returns the user-id of \texttt{FILE}.  \texttt{FILE} may be a filename
or a file-descriptor.

\item[{[}procedure{]} (file-permissions FILE)]
Returns the permission bits for \texttt{FILE}. You can test this value
by performing bitwise operations on the result and the \texttt{perm/\ldots}
values.  \texttt{FILE} may be a filename or a file-descriptor.

\item[{[}procedure{]} (file-read-access? FILENAME)]
\item[{[}procedure{]} (file-write-access? FILENAME)]
\item[{[}procedure{]} (file-execute-access? FILENAME)]
These procedures return \texttt{\#t} if the current user has read,
write or execute permissions on the file named \texttt{FILENAME}.

\item[{[}procedure{]} (change-file-mode FILENAME MODE)]
Changes the current file mode of the file named \texttt{FILENAME}
to \texttt{MODE} using the \texttt{chmod()} system call.  The
\texttt{perm/...} variables contain the various permission bits and can
be combinded with the \texttt{bitwise-ior} procedure.

\item[{[}procedure{]} (change-file-owner FILENAME UID GID)]
Changes the owner information of the file named \texttt{FILENAME} to
the user- and group-ids \texttt{UID} and \texttt{GID} (which should be
exact integers) using the \texttt{chown()} system call.

\item[{[}procedure{]} (current-user-id)]
\item[{[}procedure{]} (current-group-id)]
\item[{[}procedure{]} (current-effective-user-id)]
\item[{[}procedure{]} (current-effective-group-id)]
Return the user- and group-ids of the current process.

\item[{[}permission bits{]} perm/irusr]
\item[{[}permission bits{]} perm/iwusr]
\item[{[}permission bits{]} perm/ixusr]
\item[{[}permission bits{]} perm/irgrp]
\item[{[}permission bits{]} perm/iwgrp]
\item[{[}permission bits{]} perm/ixgrp]
\item[{[}permission bits{]} perm/iroth]
\item[{[}permission bits{]} perm/iwoth]
\item[{[}permission bits{]} perm/ixoth]
\item[{[}permission bits{]} perm/irwxu]
\item[{[}permission bits{]} perm/irwxg]
\item[{[}permission bits{]} perm/irwxo]
\item[{[}permission bits{]} perm/isvtx]
\item[{[}permission bits{]} perm/isuid]
\item[{[}permission bits{]} perm/isgid]
These variables contain permission bits as used in \texttt{change-file-mode}.

\item[{[}procedure{]} (set-user-id! UID)]
Sets the effective user id of the current process to \texttt{UID},
which should be a positive integer.

\end{description}


\subsection{Record locking}


\begin{description}

\item[{[}procedure{]} (file-lock PORT {[}START {[}LEN{]}{]})]
Locks the file associated with \texttt{PORT} for reading or
writing (according to wether \texttt{PORT} is an input- or
output-port). \texttt{START} specifies the starting position in the
file to be locked and defaults to 0. \texttt{LEN} specifies the length
of the portion to be locked and defaults to \texttt{\#t}, which means
the complete file. \texttt{file-lock} returns a ``lock''-object.

\item[{[}procedure{]} (file-test-lock PORT {[}START {[}LEN{]}{]})]
Tests wether the file associated with \texttt{PORT} is locked for reading
or writing (according to wether \texttt{PORT} is an input- or output-port)
and returns either \texttt{\#f} or the process-id of the locking process.

\item[{[}procedure{]} (file-unlock LOCK)]
Unlocks the previously locked portion of a file given in \texttt{LOCK}.

\end{description}


\subsection{Signal handling}


\begin{description}

\item[{[}procedure{]} (set-alarm! SECONDS)]
Sets an internal timer to raise the \texttt{signal/alrm}
after \texttt{SECONDS} are elapsed.  You can use the
\texttt{set-signal-handler!} procedure to write a handler for this signal.

\item[{[}procedure{]} (set-signal-handler! SIGNUM PROC)]
Establishes the procedure of one argument \texttt{PROC} as the handler
for the signal with the code \texttt{SIGNAL}. \texttt{PROC} is called
with the signal number as its sole argument. If the argument \texttt{PROC} is \texttt{\#f}
then this signal will be ignored.

\item[{[}procedure{]} (set-signal-mask! SIGLIST)]
Sets the signal mask of the current process to block all signals given
in the list \texttt{SIGLIST}.  Signals masked in that way will not be
delivered to the current process.

\item[{[}signal code{]} signal/term]
\item[{[}signal code{]} signal/kill]
\item[{[}signal code{]} signal/int]
\item[{[}signal code{]} signal/hup]
\item[{[}signal code{]} signal/fpe]
\item[{[}signal code{]} signal/ill]
\item[{[}signal code{]} signal/segv]
\item[{[}signal code{]} signal/abrt]
\item[{[}signal code{]} signal/trap]
\item[{[}signal code{]} signal/quit]
\item[{[}signal code{]} signal/alrm]
\item[{[}signal code{]} signal/vtalrm]
\item[{[}signal code{]} signal/prof]
\item[{[}signal code{]} signal/io]
\item[{[}signal code{]} signal/urg]
\item[{[}signal code{]} signal/chld]
\item[{[}signal code{]} signal/cont]
\item[{[}signal code{]} signal/stop]
\item[{[}signal code{]} signal/tstp]
\item[{[}signal code{]} signal/pipe]
\item[{[}signal code{]} signal/xcpu]
\item[{[}signal code{]} signal/xfsz]
\item[{[}signal code{]} signal/usr1]
\item[{[}signal code{]} signal/usr2]
\item[{[}signal code{]} signal/winch]
These variables contain signal codes for use with \texttt{process-signal} 
or \texttt{set-signal-handler!}.

\end{description}


\subsection{Environment access}


\begin{description}

\item[{[}procedure{]} (current-environment)]
Returns a association list of the environment variables and their
current values.

\item[{[}procedure{]} (setenv VARIABLE VALUE)]
Sets the environment variable named \texttt{VARIABLE} to
\texttt{VALUE}. Both arguments should be strings. If the variable is
not defined in the environment, a new definition is created.

\item[{[}procedure{]} (unsetenv VARIABLE)]
Removes the definition of the environment variable \texttt{VARIABLE} from
the environment of the current process. If the variable is not defined,
nothing happens.

\end{description}


\subsection{Memory mapped I/O}


\begin{description}

\item[{[}procedure{]} (map-file-to-memory ADDRESS LEN PROTECTION FLAG FILENO {[}OFFSET{]})]
Maps a section of a file to memory using the C function
\texttt{mmap()}.  \texttt{ADDRESS} should be a foreign pointer object
or \texttt{\#f}; \texttt{LEN} specifies the size of the section to
be mapped; \texttt{PROTECTION} should be one or more of the flags
\texttt{prot/read, prot/write, prot/exec} or \texttt{prot/none}
\textbf{bitwise-ior}ed together; \texttt{FLAG} should be one or more of
the flags \texttt{map/fixed, map/shared, map/private, map/anonymous} or
\texttt{map/file}; \texttt{FILENO} should be the file-descriptor of the
mapped file. The optional argument \texttt{OFFSET} gives the offset of
the section of the file to be mapped and defaults to 0. This procedure
returns an object representing the mapped file section.  The procedure
\texttt{move-memory!} can be used to access the mapped memory.

\item[{[}procedure{]} (memory-mapped-file-pointer MMAP)]
Returns a machine pointer to the start of the memory region to which
the file is mapped.

\item[{[}procedure{]} (unmap-file-from-memory MMAP {[}LEN{]})]
Unmaps the section of a file mapped to memory using the C function
\texttt{munmap()}.  \texttt{MMAP} should be a mapped file as returned
by the procedure \texttt{map-file-to-memory}.  The optional argument
\texttt{LEN} specifies the length of the section to be unmapped and
defaults to the complete length given when the file was mapped.

\end{description}

\subsection{Time routines}

\begin{description}

\item[{[}procedure{]} (seconds{\tt->}local-time SECONDS)]
Breaks down the time value represented in \texttt{SECONDS} into a 10
element vector of the form \texttt{\#(seconds minutes hours mday month
year wday yday dstflag timezone)}, in the following format:

\begin{itemize}
\item seconds: the number of seconds after the minute (0 - 59)
\item minutes: the number of minutes after the hour (0 - 59)
\item hours: the number of hours past midnight (0 - 23)
\item mday: the day of the month (1 - 31)
\item month: the number of months since january (0 - 11)
\item year: the number of years since 1900
\item wday: the number of days since Sunday (0 - 6)
\item yday: the number of days since January 1 (0 - 365)
\item dstflag: a flag that is true if Daylight Saving Time is in effect at the time described.
\item timezone: the difference between UTC and the latest local standard
time, in seconds west of UTC.
\end{itemize}

\item[{[}procedure{]} (seconds{\tt->}string SECONDS)]
Converts the local time represented in \texttt{SECONDS} into a string
of the form \texttt{"Tue May 21 13:46:22 1991{\textbackslash}n"}.

\item[{[}procedure{]} (seconds{\tt->}utc-time SECONDS)]
Similar to \texttt{seconds{\tt->}local-time}, but interpretes \texttt{SECONDS}
as local time.

\item[{[}procedure{]} (time{\tt->}string VECTOR)]
Converts the broken down time represented in the 10 element vector
\texttt{VECTOR} into a string of the form \texttt{"Tue May 21 13:46:22
1991{\textbackslash}n"}.

\end{description}

\subsection{Miscellaneous routines}

\begin{description}

\item[{[}procedure{]} (\_exit {[}CODE{]})]
Exits the current process without flushing any buffered output (using
the C function \texttt{\_exit}).  Note that the \texttt{exit-handler}
is not called when this procedure is invoked. The optional return-code
\texttt{CODE} defaults to \texttt{0}.

\item[{[}error code{]} errno/perm]
\item[{[}error code{]} errno/noent]
\item[{[}error code{]} errno/srch]
\item[{[}error code{]} errno/intr]
\item[{[}error code{]} errno/io]
\item[{[}error code{]} errno/noexec]
\item[{[}error code{]} errno/badf]
\item[{[}error code{]} errno/child]
\item[{[}error code{]} errno/nomem]
\item[{[}error code{]} errno/acces]
\item[{[}error code{]} errno/fault]
\item[{[}error code{]} errno/busy]
\item[{[}error code{]} errno/notdir]
\item[{[}error code{]} errno/isdir]
\item[{[}error code{]} errno/inval]
\item[{[}error code{]} errno/mfile]
\item[{[}error code{]} errno/nospc]
\item[{[}error code{]} errno/spipe]
\item[{[}error code{]} errno/pipe]
\item[{[}error code{]} errno/again]
\item[{[}error code{]} errno/rofs]
These variables contain error codes as returned by \texttt{errno}.

\item[{[}procedure{]} (get-host-name)]
Returns the hostname of the machine that this process is running on.

\item[{[}procedure{]} (set-buffering-mode! PORT MODE {[}BUFSIZE{]})]
Sets the buffering-mode for the file associated with \texttt{PORT} to
\texttt{MODE}, which should be one of the keywords \texttt{\#:full,
\#:line} or \texttt{\#:none}. If \texttt{BUFSIZE} is specified it
determines the size of the buffer to be used (if any).

\item[{[}procedure{]} (terminal-name PORT)]
Returns the name of the terminal that is connected to \texttt{PORT}.

\item[{[}procedure{]} (terminal-port? PORT)]
Returns \texttt{\#t} if \texttt{PORT} is connected to a terminal and
\texttt{\#f} otherwise.

\item[{[}procedure{]} (system-information)]
Invokes the UNIX system call \texttt{uname()} and returns 5 values:
system-name, node-name, OS release, OS version and machine.

\item[{[}procedure{]} (user-information USER)]
If \texttt{USER} specifes a valid username (as a string) or user ID, then
the user database is consulted and 7 values are returned: the user-name,
the encrypted password, the user ID, the group ID, a user-specific string,
the home directory and the default shell. If no user with this name or
ID can be found, then \texttt{\#f} is returned.

\item[{[}procedure{]} (find-files DIRECTORY PREDICATE {[}ACTION {[}IDENTITY {[}LIMIT{]}{]}{]})]
Recursively traverses the contents of \texttt{DIRECTORY} (which should
be a string) and invokes the procedure \texttt{ACTION} for all files
for which the procedure \texttt{PREDICATE} is true.  \texttt{PREDICATE}
may me a procedure of one argument or a regular-expression string.
\texttt{ACTION} should be a procedure of two arguments: the currently
encountered file and the result of the previous invocation of
\texttt{ACTION}, or, if this is the first invocation, the value
of \texttt{IDENTITY}. \texttt{ACTION} defaults to \texttt{cons},
\texttt{IDENTITY} defaults to \texttt{()}.  \texttt{LIMIT} should a
procedure of one argument that is called for each nested directory
and which should return true, if that directory is to be traversed
recursively. \texttt{LIMIT} may also be an exact integer that
gives the maximum recursion depth. A depth of \texttt{0} means the
files in the specified directory are traversed but not any nested
directories. \texttt{LIMIT} may also be \texttt{\#f} (the default),
which is equivalent to \texttt{(constantly \#t)}.

Note that \texttt{ACTION} is called with the full pathname of each file,
including the directory prefix.

\end{description}


\subsection{How Scheme procedures relate to UNIX C functions}

% XXX Is there a better way to get rid of the {\tt }?
{\tt
\begin{tabular}{|ll|}
\hline
change-directory             &chdir\\
change-file-mode             &chmod\\
change-file-owner            &chown\\
create-directory             &mkdir\\
create-fifo                  &mkfifo\\
create-pipe                  &pipe\\
create-symbolic-link         &link\\
current-directory            &curdir\\
current-effective-groupd-id  &getegid\\
current-effective-user-id    &geteuid\\
current-group-id             &getgid\\
current-parent-id            &getppid\\
current-process-id           &getpid\\
current-user-id              &getuid\\
delete-directory             &rmdir\\
duplicate-fileno             &dup/dup2\\
\_exit                        &\_exit\\
file-close                   &close\\
file-execute-access?         &access\\
file-open                    &open\\
file-lock                    &fcntl\\
file-position                &ftell/lseek\\
file-read                    &read\\
file-read-access?            &access\\
file-select                  &select\\
file-test-lock               &fcntl\\
file-truncate                &truncate/ftruncate\\
file-unlock                  &fcntl\\
file-write                   &write\\
file-write-access?           &access\\
get-host-name                &gethostname\\
map-file-to-memory           &mmap\\
open-input-file*             &fdopen\\
open-output-file*            &fdopen\\
open-input-pipe              &popen\\
open-output-pipe             &popen\\
port->fileno                 &fileno\\
process-execute              &execvp\\
process-fork                 &fork\\
process-signal               &kill\\
process-wait                 &waitpid\\
close-input-pipe             &pclose\\
close-output-pipe            &pclose\\
read-symbolic-link           &readlink\\
seconds->local-time          &localtime\\
seconds->string              &ctime\\
seconds->utc-time            &gmtime\\
set-alarm!                   &alarm\\
set-buffering-mode!          &setvbuf\\
set-file-position!           &fseek/seek\\
set-signal-mask!             &sigprocmask\\
set-user-id!                 &setuid\\
setenv                       &setenv/putenv\\
sleep                        &sleep\\
system-information           &uname\\
terminal-name                &ttyname\\
terminal-port?               &isatty\\
time->string                 &asctime\\
unsetenv                     &putenv\\
unmap-file-from-memory       &munmap\\
user-information             &getpwnam/getpwuid\\
\hline \end{tabular}}


\section{Unit: script-utils}

This unit contains some utility procedures for Shell scripting and for
some file operations.

This unit uses the \texttt{extras} and \texttt{regex} units.


\subsection{Pathname operations}


\begin{description}

\item[{[}procedure{]} (absolute-pathname? PATHNAME)]
Returns \texttt{\#t} if the string \texttt{PATHNAME} names an absolute
pathname, and returns \texttt{\#f} otherwise.

\item[{[}procedure{]} (decompose-pathname PATHNAME)]
Returns three values: the directory-, filename- and extension-components
of the file named by the string \texttt{PATHNAME}. For any component
that is not contained in \texttt{PATHNAME}, \texttt{\#f} is returned.

\item[{[}procedure{]} (make-pathname DIRECTORY FILENAME [EXTENSION])]
\item[{[}procedure{]} (make-absolute-pathname DIRECTORY FILENAME [EXTENSION]]
Returns a string that names the file with the
components \texttt{DIRECTORY, FILENAME} and (optionally)
\texttt{EXTENSION}. \texttt{DIRECTORY} can be \texttt{\#f} (meaning no
directory component), a string or a list of strings. \texttt{FILENAME}
and \texttt{EXTENSION} should be strings or \texttt{\#f}.
\texttt{make-absolute-pathname} returns always an absolute pathname.

\item[{[}procedure{]} (pathname-directory PATHNAME)]
\item[{[}procedure{]} (pathname-file PATHNAME)]
\item[{[}procedure{]} (pathname-extension PATHNAME)]
Accessors for the components of \texttt{PATHNAME}. If the pathname does
not contain the accessed component, then \texttt{\#f} is returned.

\item[{[}procedure{]} (pathname-replace-directory PATHNAME DIRECTORY)]
\item[{[}procedure{]} (pathname-replace-file PATHNAME FILENAME)]
\item[{[}procedure{]} (pathname-replace-extension PATHNAME EXTENSION)]
Return a new pathname with the specified component of \texttt{PATHNAME}
replaced by a new value.

\item[{[}procedure{]} (pathname-strip-directory PATHNAME)]
\item[{[}procedure{]} (pathname-strip-extension PATHNAME)]
Return a new pathname with the specified component of \texttt{PATHNAME}
stripped.

\end{description}


\subsection{Miscellaneous utilities}


\begin{description}

\item[{[}procedure{]} (create-temporary-file {[}EXTENSION{]})]
Creates an empty temporary file and returns it's pathname. If
\texttt{EXTENSION} is not given, then \texttt{.tmp} is used. If the
environment variable \texttt{TMPDIR, TEMP} or \texttt{TMP} is set,
then the pathname names a file in that directory.

\item[{[}procedure{]} (delete-file* FILENAME)]
If the file \texttt{FILENAME} exists, it is deleted and \texttt{\#t}
is returned.  If the file does not exist, nothing happens and \texttt{\#f}
is returned.

\item[{[}procedure{]} (system* FORMATSTRING ARGUMENT1 ...)]
Similar to \texttt{(system (sprintf FORMATSTRING ARGUMENT1 ...))},
but signals an error if the invoked program should return a nonzero
exit status.

\end{description}


\section{Unit: tcp}

This unit provides basic facilities for communicating over TCP sockets.
The socket interface should be mostly compatible to the one found in
PLT Scheme.

This unit uses the \texttt{extras} unit.

\begin{description}

\item[{[}procedure{]} (tcp-listen TCPPORT [BACKLOG])]
Creates and returns a TCP listener object that listens for connections on \texttt{TCPPORT}, which
should be an exact integer. \texttt{BACKLOG} specifies the number of maximally pending
connections (and defaults to 4).

\item[{[}procedure{]} (tcp-listener? X)]
Returns \texttt{\#t} if \texttt{X} is a TCP listener object, or \texttt{\#f} otherwise.

\item[{[}procedure{]} (tcp-close LISTENER)]
Reclaims any resources associated with \texttt{LISTENER}.

\item[{[}procedure{]} (tcp-accept LISTENER)]
Waits until a connection is established on the port on which \texttt{LISTENER} is listening and
returns two values: an input- and output-port that can be used to communicate with the
remote process. 

Note: this operation and any I/O on the ports returned will not block other running threads.

\item[{[}procedure{]} (tcp-accept-ready? LISTENER)]
Returns \texttt{\#t} if there are any connections pending on \texttt{LISTENER}, or \texttt{\#f}
otherwise.

\item[{[}procedure{]} (tcp-connect HOSTNAME [TCPPORT])]
Establishes a client-side TCP connection to the machine with the name \texttt{HOSTNAME} (a string)
at \texttt{TCPPORT} (an exact integer) and returns two values: an input- and output-port for communicating
with the remote process.

Note: any I/O on the ports returned will not block other running threads.

\item[{[}procedure{]} (tcp-addresses PORT)]
Returns two values for the input- or output-port \texttt{PORT} (which should be a port returned
by either \texttt{tcp-accept} or \texttt{tcp-connect}): the IP address of the local and the remote
machine that are connected over the socket associated with \texttt{PORT}. The returned addresses
are strings in \texttt{XXX.XXX.XXX.XXX} notation.

\item[{[}procedure{]} (tcp-abandon-port PORT)]
Marks the socket port \texttt{PORT} as abandoned. This is mainly useful to close down a port
without breaking the connection.

\end{description}

A very simple example follows. Say we have the two files \texttt{client.scm}
and \texttt{server.scm}:

\begin{verbatim}
; client.scm
(define-values (i o) (tcp-connect "localhost" 4242))
(write-line "Good Bye!" o)
(print (read-line i))
\end{verbatim}

\begin{verbatim}
; server.scm
(define l (tcp-listen 4242))
(define-values (i o) (tcp-accept l))
(write-line "Hello!" o)
(print (read-line i))
(close-input-port i)
(close-output-port o)

% csi -script server.scm &
[1] 1409
% csi -script client.scm
Good Bye!
Hello!
\end{verbatim}


\section{Unit: srfi-37}

A simple and flexible command-line option parsing facility. Options may
be either short one-character options of the form \texttt{-X[ARGUMENT]}
or long multicharacter ones of the form \texttt{--XXX[=ARGUMENT]}. Short
options may be coalesced. An argument of the form \texttt{--} stops
option processing.
For more information take a look at the SRFI-37 documentation
\urlfootnote{http://srfi.schemers.org/srfi-37/srfi-37.html}.

An example:

\begin{verbatim}
#!/usr/local/bin/csi -script
;;;; secho - display command-line arguments

(define nl 1)

(define help 
  (option 
   '(#\h "help") #f #f
   (lambda _ 
     (print "Usage: secho [OPTION] ARG ...
  -h  --help          show this text
  -n  --newline N     add N newline characters (default: 1)\")
     (exit) ) ) )

(define newlines
  (option
   '(#\n "newline") #t #f
   (lambda (o n x vals)
     (set! nl (string->number x))
     vals) ) )

(for-each 
 (lambda (x) (print* x \#\space))
 (reverse
  (args-fold
   (command-line-arguments)
   (list help newlines)
   (lambda (o n x vals)
     (error "unrecognized option" n) )
   cons
   '() ) ) )

(display (make-string nl \#\newline))
\end{verbatim}


\section{Unit: lolevel}


This unit provides a number of handy low-level operations. \textbf{Use
at your own risk.}


This unit uses the \texttt{srfi-4} and \texttt{extras} units.


\subsection{Foreign pointers}


\begin{description}

\item[{[}procedure{]} (address{\tt->}pointer ADDRESS)]
Creates a new foreign pointer object initialized to point to the address
given in the integer \texttt{ADDRESS}.

\item[{[}procedure{]} (allocate BYTES)]
Returns a pointer to a freshly allocated region of static memory.
This procedure could be defined as follows:

\begin{verbatim}
(define allocate (foreign-lambda c-pointer "malloc" integer))
\end{verbatim}

\item[{[}procedure{]} (free POINTER)]
Frees the memory pointed to by \texttt{POINTER}.  This procedure could
be defined as follows:

\begin{verbatim}
(define free (foreign-lambda c-pointer "free" integer))
\end{verbatim}

\item[{[}procedure{]} (null-pointer)]
Another way to say \texttt{(address->pointer 0)}.

\item[{[}procedure{]} (null-pointer? PTR)]
Returns \texttt{\#t} if \texttt{PTR} contains a \texttt{NULL} pointer,
or \texttt{\#f} otherwise.

\item[{[}procedure{]} (object{\tt->}pointer X)]
Returns a pointer pointing to the Scheme object X, which should be a
non-immediate object.  Note that data in the garbage collected heap
moves during garbage collection.

\item[{[}procedure{]} (pointer? X)]
Returns \texttt{\#t} if \texttt{X} is a foreign pointer object, and
\texttt{\#f} otherwise.

\item[{[}procedure{]} (pointer{\tt->}address PTR)]
Returns the address, to which the pointer \texttt{PTR} points.

\item[{[}procedure{]} (pointer{\tt->}object PTR)]
Returns the Scheme object pointed to by the pointer \texttt{PTR}.

\item[{[}procedure{]} (pointer-offset PTR N)]
Returns a new pointer representing the pointer \texttt{PTR} increased
by \texttt[N].

\item[{[}procedure{]} (pointer-u8-ref PTR)]
Returns the unsigned byte at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-s8-ref PTR)]
Returns the signed byte at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-u16-ref PTR)]
Returns the unsigned 16-bit integer at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-s16-ref PTR)]
Returns the signed 16-bit integer at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-u32-ref PTR)]
Returns the unsigned 32-bit integer at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-s32-ref PTR)]
Returns the signed 32-bit integer at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-f32-ref PTR)]
Returns the 32-bit float at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-f64-ref PTR)]
Returns the 64-bit double at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-u8-set! PTR N)]
Stores the unsigned byte \texttt{N} at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-s8-set! PTR N)]
Stores the signed byte \texttt{N} at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-u16-set! PTR N)]
Stores the unsigned 16-bit integer \texttt{N} at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-s16-set! PTR N)]
Stores the signed 16-bit integer \texttt{N} at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-u32-set! PTR N)]
Stores the unsigned 32-bit integer \texttt{N} at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-s32-set! PTR N)]
Stores the unsigned 32-bit integer \texttt{N} at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-f32-set! PTR N)]
Stores the 32-bit floating-point number \texttt{N} at the address designated by \texttt{PTR}.

\item[{[}procedure{]} (pointer-f64-set! PTR N)]
Stores the 64-bit floating-point number \texttt{N} at the address designated by \texttt{PTR}.

\end{description}


\subsection{Extending procedures with data}


\begin{description}

\item[{[}procedure{]} (extend-procedure PROCEDURE X)]
Returns a copy of the procedure \texttt{PROCEDURE} which contains an
additional data slot initialized to \texttt{X}. If \texttt{PROCEDURE}
is already an extended procedure, then it's data slot is changed to
contain \texttt{X} and the same procedure is returned.

\item[{[}procedure{]} (extended-procedure? PROCEDURE)]
Returns \texttt{\#t} if \texttt{PROCEDURE} is an extended procedure,
or \texttt{\#f} otherwise.

\item[{[}procedure{]} (procedure-data PROCEDURE)]
Returns the data object contained in the extended procedure
\texttt{PROCEDURE}.

\item[{[}procedure{]} (set-procedure-data! PROCEDURE X)]
Changes the data object contained in the extended procedure
\texttt{PROCEDURE} to \texttt{X}.

\begin{verbatim}
(define foo
  (letrec ((f (lambda () (procedure-data x)))
           (x #f) )
    (set! x (extend-procedure f 123))
    x) )
(foo)                                         ==> 123
(set-procedure-data! foo 'hello)
(foo)                                         ==> hello
\end{verbatim}

\end{description}


\subsection{Bytevectors}


\begin{description}

\item[{[}procedure{]} (byte-vector FIXNUM ...)]
Returns a freshly allocated byte-vector with \texttt{FIXNUM ...} as its
initial contents.

\item[{[}procedure{]} (byte-vector? X)]
Returns \texttt{\#t} if \texttt{X} is a byte-vector object, or
\texttt{\#f} otherwise.

\item[{[}procedure{]} (byte-vector-fill! BYTE-VECTOR N)]
Sets each element of \texttt{BYTE-VECTOR} to \texttt{N}, which should
be an exact integer.

\item[{[}procedure{]} (byte-vector{\tt->}list BYTE-VECTOR)]
Returns a list with elements taken from \texttt{BYTE-VECTOR}.

\item[{[}procedure{]} (byte-vector{\tt->}string BYTE-VECTOR)]
Returns a string with the contents of \texttt{BYTE-VECTOR}.

\item[{[}procedure{]} (byte-vector-length BYTE-VECTOR)]
Returns the number of elements in \texttt{BYTE-VECTOR}.

\item[{[}procedure{]} (byte-vector-ref BYTE-VECTOR INDEX)]
Returns the byte at the \texttt{INDEX}th position of \texttt{BYTE-VECTOR}.

\item[{[}procedure{]} (byte-vector-set! BYTE-VECTOR INDEX N)]
Sets the byte at the \texttt{INDEX}th position of \texttt{BYTE-VECTOR}
to the value of the exact integer \texttt{n}.

\item[{[}procedure{]} (executable-byte-vector{\tt->}procedure PBYTE-VECTOR)]
Returns a procedure that on invocation will execute the code
in \texttt{PBYTE-VECTOR}, which should have been allocated using
\texttt{make-executable-byte-vector}.  The procedure follows the native C
calling convention, and will be called as if declared with the following
prototype:

\begin{verbatim}
void <procedure>(int argc, C_word closure, C_word k, C_word arg1, ...)
\end{verbatim}

\begin{itemize}
\item \texttt{argc} contains the number of arguments \texttt{arg1, ...}
that are passed plus 2 (including \texttt{closure} and \texttt{k}).

\item \texttt{closure} is the procedure object itself.

\item \texttt{k} is a continuation closure that should be called when
the code is about to return.

\begin{verbatim}
typedef void (*CONTINUATION)(int argc, C_word closure, C_word result);
((CONTINUATION)k[ 1 ])(2, k, result)
\end{verbatim}

(\texttt{k} is a data object with the second word being the actual code
pointer)

\end{itemize}


An example:

\begin{verbatim}
(define x (make-executable-byte-vector 17))
(move-memory! 
 '#u8(#x8b #x44 #x24 #x0c  ; movl 12(%esp), %eax     - `k'
      #x8b #x5c #x24 #x10  ; movl 16(%esp), %ebx     - `arg1'
      #x53                 ; pushl %ebx              - push result
      #x50                 ; pushl %eax              - push k
      #x6a #x02            ; pushl $2                - push argument count
      #x8b #x40 #x04       ; movl 4(%eax), %eax  - fetch code pointer
      #xff #xd0)           ; call *%eax
 x)
(define y (executable-byte-vector->procedure x))
(y 123)                                         ==> 123
\end{verbatim}


The result of calling \texttt{executable-byte-vector->procedure} with
a non-executable statically allocated byte-vector is undefined.

\item[{[}procedure{]} (invoke-executable-byte-vector PBYTE-VECTOR ARG1 ...)]
Invokes the machine code stored in the executable byte-vector
\texttt{PBYTE-VECTOR}. The native C calling conventions are used, but
the invoked code is passed a single argument containing a pointer to an
array of the Scheme objects \texttt{ARG1 ...}.

\begin{verbatim}
(define v (make-executable-byte-vector 7))
(move-memory!
 '#u8(#x8b #x44 #x24 #x04        ; movl 4(%esp), %eax
      #x8b #x00                  ; movl 0(%eax), %eax
      #xc3)                      ; ret
 v)
(invoke-executable-byte-vector v "hello!") ==> "hello!"
\end{verbatim}

\item[{[}procedure{]} (list{\tt->}byte-vector LIST)]
Returns a byte-vector with elements taken from \texttt{LIST}, where the
elements of \texttt{LIST} should be exact integers.

\item[{[}procedure{]} (make-byte-vector SIZE {[}INIT{]})]
Creates a new byte-vector of size \texttt{SIZE}. If \texttt{INIT} is
given, then it should be an exact integer with which every element of
the byte-vector is initialized.

\item[{[}procedure{]} (make-executable-byte-vector SIZE {[}INIT{]})]
As \texttt{make-static-byte-vector}, but the code is suitable for
execution.  \textbf{Note:} this feature is currently only available on
\textbf{x86} platforms.

\item[{[}procedure{]} (make-static-byte-vector SIZE {[}INIT{]})]
As \texttt{make-byte-vector}, but allocates the byte-vector in storage
that is not subject to garbage collection.  To free the allocated memory,
one has to call \texttt{release} explicitly.

\item[{[}procedure{]} (static-byte-vector{\tt->}pointer PBYTE-VECTOR)]
Returns a pointer object pointing to the data in the statically allocated
byte-vector \texttt{PBYTE-VECTOR}.

\item[{[}procedure{]} (string{\tt->}byte-vector STRING)]
Returns a byte-vector with the contents of \texttt{STRING}.

\end{description}


\subsection{Data in unmanaged memory}


\begin{description}

\item[{[}procedure{]} (evict X {[}ALLOCATOR{]})]
Copies the object \texttt{X} recursively into the memory pointed
to by the foreign pointer object returned by \texttt{ALLOCATOR},
which should be a procedure of a single argument (the number of bytes
to allocate). The freshly copied object is returned.  This facility
allows moving arbitrary objects into static memory, but care should be
taken when mutating evicted data: setting slots in evicted vector-like
objects to non-evicted data is not allowed. It \textbf{is} possible to
set characters/bytes in evicted strings or byte-vectors, though.  It is
advisable \textbf{not} to evict ports, because they might be mutated by
certain file-operations.  \texttt{evict} is able to handle circular and
shared structures, but evicted symbols are no longer unique: a fresh
copy of the symbol is created, so

\begin{verbatim}
(define x 'foo)
(define y (evict 'foo))
y                              ==> foo
(eq? x y)                      ==> #f
(define z (evict '(bar bar)))
(eq? (car z) (cadr z))         ==> #t
\end{verbatim}

The \texttt{ALLOCATOR} defaults to \texttt{allocate}.

\item[{[}procedure{]} (evict-to-location X PTR {[}LIMIT{]})]
As \texttt{evict} but moves the object at the address pointed to by
the machine pointer \texttt{PTR}. If the number of copied bytes exceeds
the optional \texttt{LIMIT} then an error is signalled. Two values are
returned: the evicted object and a new pointer pointing to the first
free address after the evicted object.

\item[{[}procedure{]} (evicted? X)]
Returns \texttt{\#t} if \texttt{X} is a non-immediate evicted data object,
or \texttt{\#f} otherwise.

\item[{[}procedure{]} (object-size X)]
Returns the number of bytes that would be needed to evict the data
object \texttt{X}.

\item[{[}procedure{]} (release X {[}RELEASER{]})]
Frees memory occupied by the evicted object \texttt{X} recursively.
\texttt{RELEASER} should be a procedure of a single argument (a foreign
pointer object to the static memory to be freed) and defaults to the
C-library \texttt{free()}.

\item[{[}procedure{]} (unevict X)]
Copies the object \texttt{X} and nested objects back into the normal
Scheme heap.  Symbols are re-interned into the symbol table. Strings
and byte-vectors are \textbf{not} copied.

\end{description}


\subsection{Locatives}


A \emph{locative} is an object that points to an element of a containing object,
much like a ``pointer'' in traditional programming languages. The element can
be accessed and changed indirectly, by performing access or change operations
on the locative. The container object can be computed by calling the
\texttt{location->object} procedure. Even though the locative refers to an element of a container object,
the container can still be reclaimed by garbage collection. 

Locatives may be passed to foreign procedures that expect pointer arguments.
The effect of creating locatives for evicted data (see \texttt{evict}) is undefined.

\begin{description}

\item[{[}procedure{]} (make-locative EXP [INDEX])]
Creates a locative that refers to the element of the non-immediate object \texttt{EXP}
at position \texttt{INDEX}. \texttt{EXP} may be a vector, pair, string, byte-vector,
SRFI-4 number-vector, SRFI-25 array or record. \texttt{INDEX} should be a fixnum,
a slot-name (in case \texttt{EXP} is a SRFI-9 record), or a valid index into
a SRFI-25 array. \texttt{INDEX} defaults to 0.

\item[{[}procedure{]} (locative? X)]
Returns \texttt{\#t} if \texttt{X} is a locative, or \texttt{\#f} otherwise.

\item[{[}procedure{]} (locative-ref LOC)]
Returns the element to which the locative \texttt{LOC} refers. If the containing
object has been reclaimed by garbage collection, an error is signalled.

\item[{[}procedure{]} (locative-set! LOC X)]
Changes the element to which the locative \texttt{LOC} refers to \texttt{X}.
If the containing
object has been reclaimed by garbage collection, an error is signalled.

\item[{[}procedure{]} (locative{\tt->}object LOC)]
Returns the object that contains the element referred to by \texttt{LOC} or
\texttt{\#f} if the container has been reclaimed by garbage collection.

\end{description}


\subsection{Miscellanous routines}


\begin{description}

\item[{[}procedure{]} (align-to-word PTR-OR-INT)]
Accepts either a machine pointer or an integer as argument and returns
a new pointer or integer aligned to the native word size of the host
platform.

\item[{[}procedure{]} (become! ALIST)]
Changes the identity of the value of the car of each pair in
\texttt{ALIST} to the value of the cdr. Both values may not be immediate
(i.e. exact integers, characters, booleans or the empty list).

\begin{verbatim}
(define x "i used to be a string")
(define y '#(and now i am a vector))
(become! (list (cons x y)))
x                                    ==> #(and now i am a vector)
y                                    ==> #(and now i am a vector)
(eq? x y)                            ==> #t
\end{verbatim}

Note: this operation invokes a major garbage collection.

The effect of using \texttt{become!} on evicted data (see \texttt{evict})
is undefined.

\item[{[}procedure{]} (block-ref BLOCK INDEX)]
Returns the contents of the \texttt{INDEX}th slot of the object
\texttt{BLOCK}.  \texttt{BLOCK} may be a vector, record structure,
pair or symbol.

\item[{[}procedure{]} (block-set! BLOCK INDEX X)]
Sets the contents of the \texttt{INDEX}th slot of the object
\texttt{BLOCK} to the value of \texttt{X}.  \texttt{BLOCK} may be a
vector, record structure, pair or symbol.

\item[{[}procedure{]} (copy X)]
Copies \texttt{X} recursively and returns the fresh copy. Objects
allocated in static memory are copied back into garbage collected storage.

\item[{[}procedure{]} (make-record-instance SYMBOL ARG1 ...)]
Returns a new instance of the record type \texttt{SYMBOL}, with it's
slots initialized to \texttt{ARG1 ...}.  To illustrate:

\begin{verbatim}
(define-record point x y)
\end{verbatim}

expands into something quite similar to:

\begin{verbatim}
(begin
  (define (make-point x y)
    (make-record-instance 'point x y) )
  (define (point? x)
    (and (record-instance? x)
         (eq? 'point (block-ref x 0)) ) )
  (define (point-x p) (block-ref p 1))
  (define (point-x-set! p x) (block-set! p 1 x))
  (define (point-y p) (block-ref p 2))
  (define (point-y-set! p y) (block-set! p 1 y)) )
\end{verbatim}

\item[{[}procedure{]} (move-memory! FROM TO {[}BYTES{]})]
Copies \texttt{BYTES} bytes of memory from \texttt{FROM} to \texttt{TO}.
\texttt{FROM} and \texttt{TO} may be strings, primitive byte-vectors,
SRFI-4 byte-vectors (see: \ref{srfi4}), memory mapped files or foreign
pointers (as obtained from a call to \texttt{foreign-lambda}, for
example). if \texttt{BYTES} is not given and the size of the source
or destination operand is known then the maximal number of bytes will
be copied.

\item[{[}procedure{]} (number-of-bytes BLOCK)]
Returns the number of bytes that the object \texttt{BLOCK} contains.
\texttt{BLOCK} may be any non-immediate value.

\item[{[}procedure{]} (number-of-slots BLOCK)]
Returns the number of slots that the object \texttt{BLOCK} contains.
\texttt{BLOCK} may be a vector, record structure, pair or symbol.

\item[{[}procedure{]} (record-instance? X)]
Returns \texttt{\#t} if \texttt{X} is an instance of a record type.
See also: \texttt{make-record-instance}.

\end{description}

\section{Unit: tinyclos}

This unit is a port of Gregor Kiczales \textbf{TinyCLOS} with numerous
modifications.

This unit uses the \texttt{extras} unit.

\subsection{Defining forms}


\begin{description}

\item[{[}syntax{]} (define-class NAME (SUPERCLASS1 ...) (SLOTNAME1 ...) {[}METACLASS{]})]
Sets the variable \texttt{NAME} to a new class (a new instance of
the class \texttt{<class>}). \texttt{SUPERCLASS1 ...} is a list of
superclasses of the newly created class. If no superclasses are given,
then \texttt{<object>} is assumed.  \texttt{SLOTNAME1 ...} are the names
of the direct slots of the class. if \texttt{METACLASS} is provided,
then the new class-instance is an instance of \texttt{METACLASS} instead
of \texttt{<class>}.

\begin{verbatim}
(define-class NAME (SUPER) (SLOT1 SLOT2) META)
\end{verbatim} 

is equivalent to

\begin{verbatim}
(define NAME
  (make META 
    'name 'NAME
    'direct-supers (list SUPER)
    'direct-slots (list 'SLOT1 'SLOT2)) )
\end{verbatim}

Note that slots-names are not required to be symbols, so the following
is perfectly valid:

\begin{verbatim}
(define hidden-slot (list 'hidden))
(define <myclass>
  (make <class>
     'direct-supers (list <object>)
     'direct-slots (list hidden-slot) ) )
(define x1 (make <myclass>)
(slot-set! x1 hidden-slot 99)
\end{verbatim}

\item[{[}syntax{]} (define-generic NAME)]
Sets the variable \texttt{NAME} to contain a fresh generic function
object without associated methods.

\item[{[}syntax{]} (define-method (NAME (VARIABLE1 CLASS1) ... PARAMETERS ...) BODY ...)]
Adds a new method with the code \texttt{BODY ...} to the generic function
that was assigned to the variable \texttt{name}.  \texttt{CLASS1 ...} is
a list if classes that specialize this particular method. The method can
have additional parameters \texttt{PARAMETERS}, which do not specialize
the method any further.  Inside the body of the method the identifier
\texttt{call-next-method} names a procedure of zero arguments that can
be invoked to call the next applicable method with the same arguments.
If no generic function is defined under this name, then a fresh generic
function object is created and assigned to \texttt{NAME}.

\end{description}


\subsection{Base language}


\begin{description}

\item[{[}procedure{]} (add-method GENERIC METHOD)]
Adds the method object \texttt{METHOD} to the list of applicable methods
for the generic function \texttt{GENERIC}.

\item[{[}procedure{]} (instance? X)]
Returns \texttt{\#t} if \texttt{X} is an instance of a non-primitive
class.

\item[{[}procedure{]} (make CLASS INITARG ...)]
Creates a new instance of \texttt{CLASS} and passes \texttt{INITARG ...}
to the \texttt{initialize} method of this class.

\item[{[}procedure{]} (make-class SUPERCLASSES SLOTNAMES)]
Creates a new class object, where \texttt{SUPERCLASSES} should be the
list of direct superclass objects and \texttt{SLOTNAMES} should be a
list of symbols naming the slots of this class.

\item[{[}procedure{]} (make-generic {[}NAME{]})]
Creates a new generic function object. If \texttt{NAME} is specified,
then it should be a string.

\item[{[}procedure{]} (make-method SPECIALIZERS PROC)]
Creates a new method object specialized to the list of classes in
\texttt{SPECIALIZERS}.

\begin{verbatim}
(define-method (foo (<bar> x)) 123)
   <=> (add-method foo (make-method (list <bar>) (lambda (call-next-method x) 123)))
\end{verbatim}

\item[{[}procedure{]} (slot-ref INSTANCE SLOTNAME)]
Returns the value of the slot \texttt{SLOTNAME} of the object
\texttt{INSTANCE}.

\item[{[}procedure{]} (slot-set! INSTANCE SLOTNAME VALUE)]
Sets the value of the slot \texttt{SLOTNAME} of the object
\texttt{INSTANCE} to \texttt{VALUE}.

\end{description}


\subsection{Introspection}


\begin{description}

\item[{[}procedure{]} (class-cpl CLASS)]
Returns the class-precedence-list of \texttt{CLASS} as a list of classes.

\item[{[}procedure{]} (class-direct-slots CLASS)]
Returns the list of direct slots of \texttt{CLASS} as a list of lists,
where each sublist contains the name of the slot.

\item[{[}procedure{]} (class-direct-supers CLASS)]
Returns the list of direct superclasses of \texttt{CLASS}.

\item[{[}procedure{]} (class-of X)]
Returns the class that the object \texttt{X} is an instance of.

\item[{[}procedure{]} (class-name CLASS)]
Returns name of \texttt{CLASS}.

\item[{[}procedure{]} (class-slots CLASS)]
Returns the list of all slots of \texttt{CLASS} and it's superclasses
as a list of lists, where each sublist contains the name of the slot.

\item[{[}procedure{]} (generic-methods GENERIC)]
Returns the list of all methods associated with the generic function
\texttt{GENERIC}.

\item[{[}procedure{]} (method-specializers METHOD)]
Returns the list of classes that specialize \texttt{METHOD}.

\item[{[}procedure{]} (method-procedure METHOD)]
Returns the procedure that contains the body of \texttt{METHOD}.

\item[{[}procedure{]} (subclass? CLASS1 CLASS2)]
Returns \texttt{\#t} is \texttt{CLASS1} is a subclass of \texttt{CLASS2},
or \texttt{\#f} otherwise. Note that the following holds:

\begin{verbatim}
(subclass? X X) ==> #t
\end{verbatim}

\end{description}


\subsection{Intercessory protocol}


\begin{description}

\item[{[}generic{]} (allocate-instance CLASS)]
Allocates storage for an instance of \texttt{CLASS} and returns the
instance.

\item[{[}generic{]} (compute-apply-generic GENERIC)]
\item[{[}generic{]} (compute-apply-methods GENERIC)]
\item[{[}generic{]} (compute-methods GENERIC)]
These are used to compute the actual methods to be called on the
invocation of the generic function \texttt{GENERIC}.

\item[{[}generic{]} (compute-cpl CLASS)]
Computes and returns the class-precedence-list of \texttt{CLASS}.

\item[{[}generic{]} (compute-getter-and-setter CLASS SLOT ALLOCATOR)]
Returns two values, the procedures that get and set the contents of the
slot \texttt{SLOT}.  \texttt{ALLOCATOR} is a procedure of one argument
\emph{(I currently don't know what it does)}.

\item[{[}generic{]} (compute-method-more-specific? GENERIC)]
Returns a procedure of three arguments (two methods and a list of
arguments) that returns \texttt{\#t} if the first method is more specific
than the second one with respect to the list of arguments. Otherwise
the returned predicate returns \texttt{\#f}.

\item[{[}generic{]} (compute-slots CLASS)]
Computes and returns the list of slots of \texttt{CLASS}.

\item[{[}generic{]} (initialize INSTANCE INITARGS)]
Initializes the object \texttt{INSTANCE}. \texttt{INITARGS} is the list of
initialization arguments that were passed to the \texttt{make} procedure.

\end{description}


\subsection{Additional protocol}


\begin{description}

\item[{[}generic{]} (describe-object INSTANCE PORT)]
Writes a description of \texttt{INSTANCE} to \texttt{PORT}.  Execution of
the interpreter command \texttt{,d} will invoke this generic function.

\item[{[}generic{]} (print-object INSTANCE PORT)]
Writes a textual representation of \texttt{INSTANCE} to \texttt{PORT}.
Any output of an instance with \texttt{display, write} and \texttt{print}
will invoke this generic function.

\end{description}


\subsection{Utility procedures}


\begin{description}

\item[{[}procedure{]} (initialize-slots INSTANCE INITARGS)]
This procedure takes a sequence of alternating slot-names and
initialization values in \texttt{INITARGS} and initializes the
corresponding slots in \texttt{INSTANCE}.

\begin{verbatim}
(define-class <pos> () (x y))

(define-method (initialize (<pos> pos) initargs)
  (call-next-method)
  (initialize-slots pos initargs))

(define p1 (make <pos> 'x 1 'y 2))
(define p2 (make <pos> 'x 3 'y 5))
\end{verbatim}

\end{description}


\subsection{Builtin classes}


The class hierarchy of builtin classes looks like this:

\begin{verbatim}
<top>
  <object>
    <class>
      <procedure-class>
        <procedure>
        <entity-class>
          <generic>
      <primitive-class>
  <primitive>
    <void>
    <boolean>
    <symbol>
    <char>
    <vector>
    <pair>
    <number>
      <exact>
      <inexact>
    <string>
    <port>
      <input-port>
      <output-port>
    <pointer>
      <tagged-pointer>
    <locative>
    <byte-vector>
      <u8vector>
      <s8vector>
      <u16vector>
      <s16vector>
      <u32vector>
      <s32vector>
      <f32vector>
      <f64vector>
    <structure>
      <array>
      <char-set>
      <condition>
      <environment>
      <hash-table>
      <lock>
      <mmap>
      <promise>
      <queue>
      <tcp-listener>
      <time>
    <end-of-file>
\end{verbatim}

\begin{description}

\item[{[}class{]} $<$primitive$>$           --$>$ $<$top$>$]
The parent class of the classes of all primitive Scheme objects.

\item[{[}class{]} $<$boolean$>$             --$>$ $<$primitive$>$]
\item[{[}class{]} $<$symbol$>$              --$>$ $<$primitive$>$]
\item[{[}class{]} $<$char$>$                --$>$ $<$primitive$>$]
\item[{[}class{]} $<$vector$>$              --$>$ $<$primitive$>$]
\item[{[}class{]} $<$null$>$                --$>$ $<$primitive$>$]
\item[{[}class{]} $<$pair$>$                --$>$ $<$primitive$>$]
\item[{[}class{]} $<$number$>$              --$>$ $<$primitive$>$]
\item[{[}class{]} $<$exact$>$               --$>$ $<$number$>$]
\item[{[}class{]} $<$inexact$>$             --$>$ $<$number$>$]
\item[{[}class{]} $<$string$>$              --$>$ $<$primitive$>$]
\item[{[}class{]} $<$port$>$                --$>$ $<$primitive$>$]
\item[{[}class{]} $<$environment$>$         --$>$ $<$structure$>$]
\item[{[}class{]} $<$end-of-file$>$         --$>$ $<$primitive$>$]
\item[{[}class{]} $<$input-port$>$          --$>$ $<$port$>$]
\item[{[}class{]} $<$output-port$>$         --$>$ $<$port$>$]
\item[{[}class{]} $<$procedure$>$           --$>$ $<$procedure-class$>$]
The classes of primitive Scheme objects.

\item[{[}class{]} $<$byte-vector$>$          --$>$ $<$primitive$>$]
\item[{[}class{]} $<$structure$>$           --$>$ $<$primitive$>$]
\item[{[}class{]} $<$hash-table$>$          --$>$ $<$structure$>$]
\item[{[}class{]} $<$queue$>$               --$>$ $<$structure$>$]
The classes of extended data types provided by the various library units.

\item[{[}class{]} $<$class$>$               --$>$ $<$object$>$]
The parent class of all class objects.

\item[{[}class{]} $<$entity-class$>$        --$>$ $<$class$>$]
The parent class of objects that can be invoked as a procedure and have slots.

\item[{[}class{]} $<$generic$>$             --$>$ $<$entity-class$>$]
The parent class of generic function objects.

\item[{[}class{]} $<$method$>$              --$>$ $<$class$>$]
The parent class of method objects.

\item[{[}class{]} $<$object$>$              --$>$ $<$class$>$]
The parent class of all objects.

\item[{[}class{]} $<$procedure-class$>$     --$>$ $<$class$>$]
The parent class of objects that can be invoked as a procedure.

\item[{[}class{]} $<$condition$>$           --$>$ $<$structure$>$]
Class of condition objects.

\item[{[}class{]} $<$array$>$               --$>$ $<$structure$>$]
\item[{[}class{]} $<$char-set$>$            --$>$ $<$structure$>$]
\item[{[}class{]} $<$time$>$                --$>$ $<$structure$>$]
\item[{[}class{]} $<$u8vector$>$            --$>$ $<$byte-vector$>$]
\item[{[}class{]} $<$s8vector$>$            --$>$ $<$byte-vector$>$]
\item[{[}class{]} $<$u16vector$>$           --$>$ $<$byte-vector$>$]
\item[{[}class{]} $<$s16vector$>$           --$>$ $<$byte-vector$>$]
\item[{[}class{]} $<$u32vector$>$           --$>$ $<$byte-vector$>$]
\item[{[}class{]} $<$s32vector$>$           --$>$ $<$byte-vector$>$]
\item[{[}class{]} $<$f32vector$>$           --$>$ $<$byte-vector$>$]
\item[{[}class{]} $<$f64vector$>$           --$>$ $<$byte-vector$>$]
The classes of data objects provided by the various supported SRFIs.

\item[{[}class{]} $<$lock$>$                --$>$ $<$structure$>$]
\item[{[}class{]} $<$mmap$>$                --$>$ $<$structure$>$]
Classes of objects used in the \texttt{posix} library unit.

\item[{[}class{]} $<$pointer$>$             --$>$ $<$primitive$>$]
\item[{[}class{]} $<$tagged-pointer$>$      --$>$ $<$pointer$>$]
A machine pointer (untagged, or tagged).

\item[{[}class{]} $<$locative$>$            --$>$ $<$primitive$>$]
A locative.

\item[{[}class{]} $<$promise$>$             --$>$ $<$structure$>$]
The class of objects returned by \texttt{delay}.

\item[{[}class{]} $<$tcp-listener$>$        --$>$ $<$structure$>$]
The class of an object returned by \texttt{tcp-listen}.

\end{description}


\section{Additional files}


In addition to library units the following files are provided. Use them
by including the file in your code with the \texttt{include} special form.

\subsection{\texttt{srfi-13-syntax.scm}}


This file provides the \texttt{let-string-start+end} syntax defined
in SRFI-13.  See: \ref{srfi13}.

\subsection{\texttt{test-infrastructure.scm}}

This file provides a macro based unit testing facility based upon
expectations concerning evaluations of expressions. These functions return
tagged lists which contain the results of the test package, test case,
or expectations evaluated(there are a few other types of results dealing
with the gloss, todo, and skip macros detailed below). These result
lists are wired together during evaluation to form a large heirarchical
tree in memory.  This result tree is then passed to either user defined
functions which traverse the tree manipulating it in any way desired, or
passed to a supplied (read: defined already in test-infrastructure.scm)
function which manipulates it in a simple way usually producing human
readable or html generated output. API functions to deal with the result
types are supplied and the representation of the result is black boxed to
the user. It is a violation of encapsulation to inspect the representation
directly, and it may change unpredictably in the future.

\subsubsection{The Test Package Macro API}

This macro will evaluate in a left to right fashion the clauses inside
it. Clauses can only be certain things, detailed below. All of the clauses
are executed, except of course if you bail out of the test package with
the escape procedure mechanism.  Test packages may nest indefinitely.

\begin{itemize}
\item\texttt{{[}macro{]} (test-package MESSAGE DESTNAME TERMNAME CLAUSES)}
\item\texttt{{[}macro{]} (test-package MESSAGE DESTNAME TERMNAME (BINDINGS) CLAUSES)}
\item\texttt{{[}macro{]} (test-package MESSAGE DESTNAME TERMNAME (warn MESSAGE) CLAUSES)}
\item\texttt{{[}macro{]} (test-package MESSAGE DESTNAME TERMNAME (warn MESSAGE) (BINDINGS) CLAUSES)}
\begin{itemize}
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{DESTNAME} is an unquoted symbol for an automatic destructor 
        object that gets called when the test package completes for any reason. 
        This symbol is bound to a destructor object and is available to you in 
        the CLAUSES section of the test package. See below for the description
        of the destructor object interface.
\item \texttt{TERMNAME} is an unquoted symbol for an escape procedure
        available in the body of the test package, usually, this escape
        procedure is passed to \texttt{(terminate ...)} which calls it
        for you and performs other tasks. It is not recommended to call the escape
        procedure directly.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the test package. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{BINDINGS} are let-style bindings that you may create and exist in
        the lexical scope of the test package.
\item \texttt{CLAUSES} are uses of \texttt{(test-case ...)} macros
        along with \texttt{(gloss ...)}, \texttt{(todo ...)},
        \texttt{(skip ...)}, and \texttt{(terminate ...)} macros. While
        you may use the \texttt{(expect-* ...)} style macros directly in
        a test package, doing so is not recommended. If the expectation
        fails, the test package macro will continue evaluating until
        all clauses are evaluated or the escape procedure mechanism is
        activated. This is different than a test-case macro where upon
        discovery of a failed expectation, evaluation stops immediatly.
\end{itemize}
\end{itemize}

\subsubsection{The Test Case Macro API}

This macro will evaluate in a left to right fashion the clauses inside
it \textbf{stopping at the first failed expectation}. Clauses can only
be certain things as detailed below. You may also stop the execution of
expectations if you bail out of the test case with the escape procedure
mechanism.  Test cases may \textbf{NOT} nest.

\begin{itemize}
\item \texttt{[macro] (test-case MESSAGE DESTNAME TERMNAME CLAUSES)}
\item \texttt{[macro] (test-case MESSAGE DESTNAME TERMNAME (BINDINGS) CLAUSES)}
\item \texttt{[macro] (test-case MESSAGE DESTNAME TERMNAME (warn MESSAGE) CLAUSES)}
\item \texttt{[macro] (test-case MESSAGE DESTNAME TERMNAME (warn MESSAGE) (BINDINGS) CLAUSES)}
\begin{itemize}
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{DESTNAME} is an unquoted symbol for an automatic destructor 
        object that gets called when the test case completes for any reason. 
        This symbol is bound to a destructor object and is available to you in 
        the CLAUSES section of the test package. See below for the description
        of the destructor object interface.
\item \texttt{TERMNAME} is an unquoted symbol for an escape procedure
        available in the body of the test case, usually, this escape
        procedure is passed to \texttt{(terminate ...)} which calls it
        for you and performs other tasks. It is not recommended to call the escape
        procedure directly.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the test case. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{BINDINGS} are let-style bindings that you may create and exist in
        the lexical scope of the test case.
\item \texttt{CLAUSES} are uses of \texttt{(expect-* ...)} macros
        along with \texttt{(gloss ...)}, \texttt{(todo ...)},
        \texttt{(skip ...)}, and \texttt{(terminate ...)} macros. It is
        important to note that upon discovery of a failed expectation,
        the test case stops its evaluation and returns with the previous
        successful, and including the failed, expectations.
\end{itemize}
\end{itemize}


\subsubsection{The Expectation Macro API}

An expectation at its core simply evaluates its arguments and check to
see if it matches the expectation. The positive or negative result is
encapsulated, along with other things such as the unevaluated expressions
being checked and some messages supplied with each expectation into
a particular type of black box object that one can query with the
appropriate API calls(detailed below).

Expectations all have a descriptive message that can be bound to them,
along with an optional warning syntax detailed below. A design decision
was made to supply expectation macros for the usual types of expectations
a user needs because this reduced the abstractness of an expectation
into something more manageable. In a future release however, I will
supply a special expectation macro where you may supply any predicate
you wish along with a ``type tag'' of the predicate.

\begin{itemize}
\item \texttt{[macro] (expect-zero MESSAGE CLAUSE)}
\item \texttt{[macro] (expect-zero MESSAGE (warn MESSAGE) CLAUSE)}
\begin{itemize}
\item This expectation checks to see if the evaluated expression passed to it
is numerically equal to the exact integer zero.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{CLAUSE} is a single expression which should return a exact or
inexact integer.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-nonzero MESSAGE CLAUSE)}
\item \texttt{[macro] (expect-nonzero MESSAGE (warn MESSAGE) CLAUSE)}
\begin{itemize}
\item This expectation checks to see if the evaluated expression passed to it
is numerically not equal to the exact integer zero.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{CLAUSE} is a single expression which should return an exact or
inexact integer.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-true MESSAGE CLAUSE)}
\item \texttt{[macro] (expect-true MESSAGE (warn MESSAGE) CLAUSE)}
\begin{itemize}
\item This expectation checks to see if the evaluated expression passed to it
is the value \#t.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{CLAUSE} is a single expression which should return \#t.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-false MESSAGE CLAUSE)}
\item \texttt{[macro] (expect-false MESSAGE (warn MESSAGE) CLAUSE)}
\begin{itemize}
\item This expectation checks to see if the evaluated expression passed to it
is the value \#f.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{CLAUSE} is a single expression which should return \#t.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-eq?\ MESSAGE EXPECTED CLAUSE)}
\item \texttt{[macro] (expect-eq?\ MESSAGE (warn MESSAGE) EXPECTED CLAUSE)}
\begin{itemize}
\item This expectation checks to see if \textbf{(eq?\ EXPECTED CLAUSE)} is true.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{EXPECTED} is a single expression which is evaluated and represents
the value the \texttt{CLAUSE} \textbf{must} be eq?\ to in order for this
expectation to return a positive resullt.
\item \texttt{CLAUSE} is a single expression which, when evaluated must return
an object where an eq?\ of this result and the \texttt{EXPECTED} expression
is \#t.
\item The result object this macro produce shall contain the unevaluated 
\texttt{CLAUSE} expression as a field, but not an unevaluated \texttt{EXPECTED}
expression.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-eqv?\ MESSAGE EXPECTED CLAUSE)}
\item \texttt{[macro] (expect-eqv?\ MESSAGE (warn MESSAGE) EXPECTED CLAUSE)}
\begin{itemize}
\item This expectation checks to see if \textbf{(eqv?\ EXPECTED CLAUSE)} is 
true.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{EXPECTED} is a single expression which is evaluated and represents
the value the \texttt{CLAUSE} \textbf{must} be eqv?\ to in order for this
expectation to return a positive resullt.
\item \texttt{CLAUSE} is a single expression which, when evaluated must return
an object where an eqv?\ of this result and the \texttt{EXPECTED} expression
is \#t.
\item The result object this macro produce shall contain the unevaluated 
\texttt{CLAUSE} expression as a field, but not an unevaluated \texttt{EXPECTED}
expression.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-equal?\ MESSAGE EXPECTED CLAUSE)}
\item \texttt{[macro] (expect-equal?\ MESSAGE (warn MESSAGE) EXPECTED CLAUSE)}
\begin{itemize}
\item This expectation checks to see if \textbf{(equal?\ EXPECTED CLAUSE)} is 
true.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{EXPECTED} is a single expression which is evaluated and represents
the value the \texttt{CLAUSE} \textbf{must} be equal?\ to in order for this
expectation to return a positive resullt.
\item \texttt{CLAUSE} is a single expression which, when evaluated must return
an object where an equal?\ of this result and the \texttt{EXPECTED} expression
is \#t.
\item The result object this macro produce shall contain the unevaluated 
\texttt{CLAUSE} expression as a field, but not an unevaluated \texttt{EXPECTED}
expression.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-near?\ MESSAGE EXPECTED TOL CLAUSE)}
\item \texttt{[macro] (expect-near?\ MESSAGE (warn MESSAGE) EXPECTED TOL CLAUSE)}
\begin{itemize}
\item This expectation checks to see if 
\textbf{($<$ (abs (- EXPECTED CLAUSE)) TOL)))} is true.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{EXPECTED} is a single expression which is evaluated and represents
the value the \texttt{CLAUSE} \textbf{must} be ``near'' to in order for this
expectation to return a positive resullt.
\item \texttt{CLAUSE} is a single expression which should return an inexact or 
exact number.
\item \texttt{TOL} is a single expression which, when evaluated must return a
tolerance value(usually a small inexact number like .0001).
\item The result object this macro produce shall contain the unevaluated 
\texttt{CLAUSE} expression as a field, but not the unevaluated \texttt{EXPECTED}
or \texttt{TOL} expression.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-positive MESSAGE CLAUSE)}
\item \texttt{[macro] (expect-positive MESSAGE (warn MESSAGE) CLAUSE)}
\begin{itemize}
\item This expectation checks to see if the evaluated expression passed to it
is a positive value greater than zero.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{CLAUSE} is a single expression which should return an inexact or
exact number.
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{[macro] (expect-negative MESSAGE CLAUSE)}
\item \texttt{[macro] (expect-negative MESSAGE (warn MESSAGE) CLAUSE)}
\begin{itemize}
\item This expectation checks to see if the evaluated expression passed to it
is a negative value less than zero.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn MESSAGE)} allows you to specify a warning object, usually
        a string, that gets associated with the expectation. The
        \texttt{warn} function name is actually a syntax reserved word
        in the macro.
\item \texttt{CLAUSE} is a single expression which should return an inexact or
exact number.
\end{itemize}
\end{itemize}

\subsubsection{Result Object API}

Expectations, test cases, test packages, and helper macros(\texttt{gloss,
todo, etc}) all return an object that contains the results and other various
aspects of the action performed which ultimately get wired together to
form the result tree. This collection of functions forming the rest of the
test infrastructure API allows manipulation of these results in an abstracted
way as to allow changing of the representation in the future.

\subsubsection{Test Package Result Object API}

If any of these API functions, except \textbf{test-package-result?},
are passed something that isn't a test package result object, they will
return 'not-a-test-package-result.

\begin{itemize}

\item \texttt{[procedure] (test-package-result? RESULT)} \\
        If \texttt{RESULT} is a result object from the invocation
        of a test package macro, then this function will return
        \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (test-package-result-result-ref RESULT)} \\
        Returns the boolean result associated with the test package \texttt{RESULT}
        object.

\item \texttt{[procedure] (test-package-result-message-ref RESULT)} \\
        Returns the message object associated with the test package \texttt{RESULT}
        object.

\item \texttt{[procedure] (test-package-result-exps-ref RESULT)} \\
        Returns the list of result objects associated with the test package 
        \texttt{RESULT} object.

\item \texttt{[procedure] (test-package-result-warning? RESULT)} \\
        If a warning had been attached to this test package, this function
        will return \#t, otherwise it will be \#f.

\item \texttt{[procedure] (test-package-result-warning-ref RESULT)} \\
        If a warning had been attached to this test package, this function
        will return the warning object supplied by the user, otherwise it 
        shall return \textbf{'()}.

\end{itemize}

\subsubsection{Test Case Result Object API}

If any of these API functions, except \textbf{test-case-result?},
are passed something that isn't a test case result object, they will
return 'not-a-test-case-result.

\begin{itemize}

\item \texttt{[procedure] (test-case-result? RESULT)} \\
        If \texttt{RESULT} is a result object from the invocation
        of a test case macro, then this function will return
        \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (test-case-result-result-ref RESULT)} \\
        Returns the boolean result associated with the test case \texttt{RESULT}
        object.

\item \texttt{[procedure] (test-case-result-message-ref RESULT)} \\
        Returns the message object associated with the test case \texttt{RESULT}
        object.

\item \texttt{[procedure] (test-case-result-expectations-ref RESULT)} \\
        Returns the list of expctation result objects associated with the test
        case \texttt{RESULT} object.

\item \texttt{[procedure] (test-case-result-warning? RESULT)} \\
        If a warning had been attached to this test case, this function
        will return \#t, otherwise it will be \#f.

\item \texttt{[procedure] (test-case-result-warning-ref RESULT)} \\
        If a warning had been attached to this test case, this function
        will return the warning object supplied by the user, otherwise it 
        shall return \textbf{'()}.

\end{itemize}

\subsubsection{Expect Result Object API: Single Clause Style Expectation}

These expectations all take the form of passing a single expression to
them to see if they match some a priori expectation.  If any of these
API functions, except \textbf{expect-result?}, are passed something that
isn't a single clause style expectation result object, they will return
'not-an-expect-result.

\begin{itemize}

\item \texttt{[procedure] (expect-result? RESULT)} \\
        If \texttt{RESULT} is a single clause style result object from
        the invocation of an expectation macro, then this function will
        return \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (expect-result-result-ref RESULT)} \\
        Returns the boolean result associated with the single clause
        style expectation \texttt{RESULT} object.

\item \texttt{[procedure] (expect-result-specific-ref RESULT)} \\
        This retrives the ``specific'' field of a particular single clause
        style expectation.  For example, if you had a result object from
        an invocation of a \textbf{(expect-zero? "foobar" (- 1 1))}
        expectation, then the ``specific'' field of the expectation
        result object will be the string \textbf{"zero"}. Here is a
        table describing what the ``specific'' fields are for each kind
        of single clause style expectation:

        \begin{center}
        \begin{tabular}{|c|c|} \hline
                \multicolumn{1}{|c|}{Single Clause Style Expectation} &
                        \multicolumn{1}{c|}{Associated Specific String} \\ \hline
        expect-zero & "zero" \\
        expect-nonzero & "nonzero" \\
        expect-true & "true" \\
        expect-false & "false" \\
        expect-positive & "positive" \\
        expect-negative & "negative" \\ \hline
        \end{tabular}
        \end{center}

\item \texttt{[procedure] (expect-result-message-ref RESULT)} \\
        Returns the message object associated with the single clause
        style expectation \texttt{RESULT} object.

\item \texttt{[procedure] (expect-result-unevaled-ref RESULT)} \\
        Returns the unevaluated expression supplied to a single clause style
        expectation macro.

\item \texttt{[procedure] (expect-result-evaled-ref RESULT)} \\
        Returns the evaluated expression supplied to a single clause style
        expectation macro.

\item \texttt{[procedure] (expect-result-warning? RESULT)} \\
        If a warning had been attached to this expectation, this function
        will return \#t, otherwise it will be \#f.

\item \texttt{[procedure] (expect-result-warning-ref RESULT)} \\
        If a warning had been attached to this expectation, this function
        will return the warning object supplied by the user, otherwise it 
        shall return \textbf{'()}.

\end{itemize}

\subsubsection{Expect Result Object API: Equivalence Style Expectation}

These expectations all take the form of passing a two expressions,
the ``left hand side'' and the ``right hand side'' to them to see
if they match some a priori equivalence.  The left hand side is that
which you expect the right hand side to be equivalent. If any of these
API functions, except \textbf{expect-equivalence-result?}, are passed
something that isn't a single clause style expectation result object,
they will return 'not-an-expect-equivalence-result.

\begin{itemize}

\item \texttt{[procedure] (expect-equivalence-result? RESULT)} \\
        If \texttt{RESULT} is a comparison style result object from
        the invocation of an expectation macro, then this function will
        return \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (expect-equivalence-result-result-ref RESULT)} \\
        Returns the boolean result associated with the comparison style
        expectation \texttt{RESULT} object.

\item \texttt{[procedure] (expect-equivalence-result-specific-ref RESULT)} \\
        This retrives the ``specific'' field of a particular equivalence
        style expectation. For example, if you had a result object from
        an invocation of a \textbf{(expect-equal? "foobar" 0 (- 1 1))}
        expectation, then the ``specific'' field of the expectation
        result object will be the string \textbf{"equal"}. Here is a
        table describing what the ``specific'' fields are for each kind
        of equivalence style expectation:

        \begin{center}
        \begin{tabular}{|c|c|} \hline
                \multicolumn{1}{|c|}{Equivalence Style Expectation} &
                        \multicolumn{1}{c|}{Associated Specific String} \\ \hline
        expect-eq & "eq" \\
        expect-eqv & "eqv" \\
        expect-equal & "equal" \\ \hline
        \end{tabular}
        \end{center}

\item \texttt{[procedure] (expect-equivalence-result-message-ref RESULT)} \\
        Returns the message object associated with the equivalence
        style expectation \texttt{RESULT} object.

\item \texttt{[procedure] (expect-equivalence-result-lhs-evaled-ref RESULT)} \\
        Returns the evaluated ``left hand side'' expression supplied to 
        an equivalence style expectation.

\item \texttt{[procedure] (expect-equivalence-result-rhs-unevaled-ref RESULT)}\\
        Returns the unevaluated ``right hand side'' expression supplied
        to an equivalence style expectation.

\item \texttt{[procedure] (expect-equivalence-result-rhs-evaled-ref RESULT)} \\
        Returns the evaluated ``right hand side'' expression supplied
        to an equivalence style expectation.

\item \texttt{[procedure] (expect-equivalence-result-warning? RESULT)} \\
        If a warning had been attached to this expectation, this function
        will return \#t, otherwise it will be \#f.

\item \texttt{[procedure] (expect-equivalence-result-warning-ref RESULT)} \\
        If a warning had been attached to this expectation, this function
        will return the warning object supplied by the user, otherwise it 
        shall return \textbf{'()}.

\end{itemize}

\subsubsection{Expect Result Object API: Tolerance Style Expectation}

This is a specialized expectation which accepts three expressions and
checks to see if the ``right hand side'' is within a ``tolerance''
of the ``left hand side''. There is only one expectation in the
tolerance style currently.  If any of these API functions, except
\textbf{expect-tolerance-result?}, are passed something that isn't
a tolerance style expectation result object, they will return
'not-an-expect-tolerance-result.

\begin{itemize}

\item \texttt{[procedure] (expect-tolerance-result? RESULT)} \\
        If \texttt{RESULT} is a tolerance style result object from
        the invocation of an expectation macro, then this function will
        return \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (expect-tolerance-result-result-ref RESULT)} \\
        Returns the boolean result associated with the tolerance style
        expectation \texttt{RESULT} object.

\item \texttt{[procedure] (expect-tolerance-result-specific-ref RESULT)} \\
        This retrives the ``specific'' field of a particular tolerance
        style expectation. For example, if you had a result object from
        an invocation of a \textbf{(expect-near? "foobar" 100 .01 100.001)}
        expectation, then the ``specific'' field of the expectation
        result object will be the string \textbf{"near"}. Here is a
        table describing what the ``specific'' fields are for each kind
        of tolerance style expectation:

        \begin{center}
        \begin{tabular}{|c|c|} \hline
                \multicolumn{1}{|c|}{Tolerance Style Expectation} &
                        \multicolumn{1}{c|}{Associated Specific String} \\ \hline
        expect-near & "near" \\ \hline
        \end{tabular}
        \end{center}

\item \texttt{[procedure] (expect-tolerance-result-message-ref RESULT)} \\
        Returns the message object associated with a tolerance
        style expectation \texttt{RESULT} object.

\item \texttt{[procedure] (expect-tolerance-result-lhs-evaled-ref RESULT)} \\
        Returns the evaluated ``left hand side'' expression supplied to 
        a tolerance style expectation.

\item \texttt{[procedure] (expect-tolerance-result-lhs-tol-evaled-ref RESULT)}\\
        Returns the evaluated ``tolerance'' expression supplied to 
        a tolerance style expectation.

\item \texttt{[procedure] (expect-tolerance-result-rhs-unevaled-ref RESULT)}\\
        Returns the unevaluated ``right hand side'' expression supplied
        to a tolerance style expectation.

\item \texttt{[procedure] (expect-tolerance-result-rhs-evaled-ref RESULT)} \\
        Returns the evaluated ``right hand side'' expression supplied
        to a tolerance style expectation.

\item \texttt{[procedure] (expect-tolerance-result-warning? RESULT)} \\
        If a warning had been attached to this expectation, this function
        will return \#t, otherwise it will be \#f.

\item \texttt{[procedure] (expect-tolerance-result-warning-ref RESULT)} \\
        If a warning had been attached to this expectation, this function
        will return the warning object supplied by the user, otherwise it 
        shall return \textbf{'()}.

\end{itemize}

\subsubsection{Various Helper API}

These upcomming macros and functions allow the author of the test suite to
better control both the execution flow of the test suite and ``decoration''
of the test suite with important information like things yet to do, or just
plain documentation.

\subsubsection{Termination API}

When executing in a test package or a test case, one might discover some
catastrophic failue of such proportions that it is utterly impossible
to continue executing the test case or test package. When that happens
you can use the termination facility to exit the test case or test
package. Of course, no more expressions will be evaluated in the scope of
the termination. It is recommended that you use this method of terminating
the test case or test package evaluation since it wraps some contextual
information up into the termination result so you can figure out what
happened(and where) later when analyzing the result tree.

When using the manipulation API for a terminate result, if you pass a
result to one of these function that is not a terminate result, it will
return 'not-a-terminate-result.

\begin{itemize}
\item \texttt{[procedure] (terminate TERMFUNC MESSAGE)}
\begin{itemize}
\item This is the recommended termination method for a test case or a test
        package.
\item \texttt{TERMFUNC} is the name of the termination procedure that you
        specified in a test case or test package. You may pass any test package
        or test case termination function available to you in the lexical scope
        in which you call this function. The termination will take effect in the
        scope of the created termination function.
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\end{itemize}

\item \texttt{[procedure] (terminate-result? RESULT)} \\
        If \texttt{RESULT} is a termination result object from the
        invocation of a termination function, then this function will
        return \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (terminate-result-result-ref RESULT)} \\
        Returns the boolean result associated with the termination
        function \texttt{RESULT} object. This is currently hard coded to
        be \#f.

\item \texttt{[procedure] (terminate-result-scope-ref RESULT)} \\
        The ``scope'' of the termination result is exactly the \texttt{MESSAGE}
        parameter supplied to the test case or test package associated with the
        \texttt{TERMFUNC}.

\item \texttt{[procedure] (terminate-result-container-ref RESULT)} \\
        The ``container'' of the termination result is going to be
        either 'test-package or 'test-case depending upon which the
        \texttt{TERMFUNC} was associated.

\item \texttt{[procedure] (terminate-result-message-ref RESULT)} \\
        Returns the message object associated with the termination
        \texttt{RESULT} object.

\end{itemize}

\subsubsection{Destructor Object API}
The destructor object allows for you to create helper functions
which clean up for you usually in case of aborting of a test case
or package. For example, suppose you are testing whether or not file
writing to a file works correctly in a test case, so, you'd perform an
expectation to open the file, and then queue a function in the destructor
to remove the file, and then perform the expectation of the write. If
the write(or subsequent) expectation fails, then the test case will
\textbf{automatically} invoke the helper cleanup function specified in
the destructor object that removes the file.

\textbf{NOTE:} This API is still a little experimental in the sense
that eventually he destructor object should return a typed result that
contains the success of the individual destructor calls. But for now,
it is functional for what it does. Also, be \textbf{VERY CAREFUL} that
you specify the arguments to these API calls correctly since due to
lambda functions not being comparable, this API cannot garauntee that
a true destructor object name had been passed to it. So if you call one
of the following API calls incorrectly, the behaviour will be undefined.

\begin{itemize}

\item \texttt{[procedure] (destructor-atexit! DESTNAME FUNC ARGS ...)}\\
        This will insert a promise to calculate the \texttt{FUNC} with the
        supplied \texttt{ARGS ...} into a queue in the \texttt{DESTNAME}
        destructor object. Multiple invocations of this API call will 
        continue to queue up \texttt{(FUNC ARGS ...)} promises indefinitely.
        This function returns a special \textbf{ignore} type that is ignored
        by the test infrastructure system.

\item \texttt{[procedure] (destructor-activate! DESTNAME)}\\
        This function will call, in order of queueing, all the promises
        embeded into this destructor object, and then delete the
        queue. This function is \textbf{ALWAYS} called at the completion
        of a test package or test case; so be careful that the destructor
        object doesn't contain anything harmful.  However, you may call
        it yourself and if you do, it will execute all of the queued
        promises and then \texttt{clear} itself. This function returns
        a special \textbf{ignore} type that is ignored by the test
        infrastructure system.

\item \texttt{[procedure] (destructor-clear! DESTNAME)}\\
        This function completely removes all of the promises associated
        with the destructor object \texttt{DESTNAME}. This function
        returns a special \textbf{ignore} type that is ignored by the
        test infrastructure system.

\item \texttt{[procedure] (destructor-dump DESTNAME)}\\
        This function, mostly used for debugging purposes, prints out
        a simple representation of the queued atexit functions to the
        current port.  This function returns a special \textbf{ignore}
        type that is ignored by the test infrastructure system.

\end{itemize}

\subsubsection{Todo API}

The purpose of the todo API is to allow the author of a test suite the
ability to record into the result tree for later analysis that something
still needs to be done. This way you can count/manipulate this information
at a later date.  Todo macro invocations can occur inside of test cases
or test packages.

\begin{itemize}
\item \texttt{[macro] (todo MESSAGE)}
\item \texttt{[macro] (todo (warn WARNING) MESSAGE)}
\begin{itemize}
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn WARNING)} allows you to specify a warning object, usually
        a string, that gets associated with the todo. The \texttt{warn}
        function name is actually a syntax reserved word in the macro.
\end{itemize}

\item \texttt{[procedure] (todo-result? RESULT)} \\
        If \texttt{RESULT} is a todo result object from the
        invocation of a todo macro, then this function will
        return \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (todo-result-message-ref RESULT)} \\
        Returns the message object associated with the todo
        \texttt{RESULT} object.

\item \texttt{[procedure] (todo-result-warning? RESULT)} \\
        If a warning had been attached to this todo, this function
        will return \#t, otherwise it will be \#f.

\item \texttt{[procedure] (todo-result-warning-ref RESULT)} \\
        If a warning had been attached to this todo, this function
        will return the warning object supplied by the user, otherwise it 
        shall return \textbf{'()}.

\end{itemize}

\subsubsection{Gloss API}

The purpose of the gloss API is to allow the author of a test suite the
ability to record messages into the result tree purely for documentation
purposes.  Gloss macro invocations can occur inside of test cases or
test packages.

\begin{itemize}
\item \texttt{[macro] (gloss MESSAGE)}
\item \texttt{[macro] (gloss (warn WARNING) MESSAGE)}
\begin{itemize}
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn WARNING)} allows you to specify a warning object, usually
        a string, that gets associated with the gloss. The \texttt{warn}
        function name is actually a syntax reserved word in the macro.
\end{itemize}

\item \texttt{[procedure] (gloss-result? RESULT)} \\
        If \texttt{RESULT} is a gloss result object from the
        invocation of the gloss macro, then this function will
        return \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (gloss-result-message-ref RESULT)} \\
        Returns the message object associated with the gloss
        \texttt{RESULT} object.

\item \texttt{[procedure] (gloss-result-warning? RESULT)} \\
        If a warning had been attached to this gloss, this function
        will return \#t, otherwise it will be \#f.

\item \texttt{[procedure] (gloss-result-warning-ref RESULT)} \\
        If a warning had been attached to this gloss, this function
        will return the warning object supplied by the user, otherwise it 
        shall return \textbf{'()}.

\end{itemize}

\subsubsection{Skip API}

The purpose of the skip API is to allow the author of a test suite
to completely skip evaluation of a set of expresssions.  Skip macro
invocations can occur inside of test cases or test packages.

\begin{itemize}
\item \texttt{[macro] (skip MESSAGE CLAUSES)}
\item \texttt{[macro] (skip (warn WARNING) MESSAGE CLAUSES)}
\begin{itemize}
\item \texttt{MESSAGE} can be any scheme object, though usually it is a string.
\item \texttt{(warn WARNING)} allows you to specify a warning object, usually
        a string, that gets associated with the gloss. The \texttt{warn}
        function name is actually a syntax reserved word in the macro.
\item \texttt{CLAUSES} can be more than one expression(as in a lambda form)
        that does \textbf{NOT} get evaluated at any time.
\end{itemize}

\item \texttt{[procedure] (skip-result? RESULT)} \\
        If \texttt{RESULT} is a skip result object from the
        invocation of the skip macro, then this function will
        return \#t. Otherwise, it will return \#f.

\item \texttt{[procedure] (skip-result-message-ref RESULT)} \\
        Returns the message object associated with the skip
        \texttt{RESULT} object. Hopefully, it was stated why this
        set of clauses had been skipped.

\item \texttt{[procedure] (skip-result-warning? RESULT)} \\
        If a warning had been attached to this skip, this function
        will return \#t, otherwise it will be \#f.

\item \texttt{[procedure] (skip-result-warning-ref RESULT)} \\
        If a warning had been attached to this skip, this function
        will return the warning object supplied by the user, otherwise it 
        shall return \textbf{'()}.

\end{itemize}

\subsubsection{Side Effect API}

This section of the API just contains a single macro currently since
it is considered a little experimental for now.  The side effecting
evaluates all of its arguments as in a \textbf{(begin ...)} form, it
returns a result that is completely ignored by the system and unavailable
to the output analysis code.

\begin{itemize}
\item \texttt{[macro] (side-effect CLAUSES)} \\
        This macro expands into a begin form the clauses in order and when it
        finishes evaluating them, returns a result that is silently ignored by 
        the testing infrastructure system. Usually this is used in conjuction with
        \textbf{(set! ...)} or with complicated situations where a lot of setup
        work must happen for an expectation to be performed.
\end{itemize}

\subsubsection{Miscellaneous API}

This section contains a few functions whose purpose is to simplify certain
kinds of manipulations of result objects.

\begin{itemize}
\item \texttt{([procedure] (*-result? RESULTOBJ))} \\
        This function will return \#t of \texttt{RESULTOBJ} is any kind of an
        evaluated result object. Otherwise, it shall return \#f.

\item \texttt{([procedure] (*-result-ref RESULTOBJ))} \\
        This function will return the result of any kind of \texttt{RESULTOBJ}
        passed to it if it is indeed a true result object. Otherwise, it
        shall emit an error to the current port, and return \#f.

\item \texttt{([procedure] (all-testpackage-results-true? RESULTLIST))} \\
        This function takes the result of a call to 
        \textbf{(test-package-result-result-ref PACKAGERESULTOBJ)} and returns
        \#t if every single contained result in that list had been true, or \#f
        otherwise.

\item \texttt{([procedure] (all-testcase-expectations-true? RESULTLIST))} \\
        This function takes the result of a call to 
        \textbf{(test-case-result-result-ref CASERESULTOBJ)} and returns
        \#t if every single contained result in that list had been true, or \#f
        otherwise.


\end{itemize}

\subsubsection{Analysis of the Result Tree}
        
Once a result tree has been evaluated and constructed in memory, what
do you do with it? Well, you can do anything you want with it if you
choose to write the analysis or output generation functions and pass it
the evaluated result tree, and this is, in fact, encouraged. However,
usually you just want to print out the tree in a human readable format so
you can check things before the serious analysis code gets written. So,
to save work for the test suite designer, a tiny API has been written
to produce human readable output given a tree of results rooted in a
single test package. Of course the single test package may have many
other test packages and test cases embedded within it.

\subsubsection{Output Generation API}

\begin{itemize}
\item \texttt{[procedure] (printnl CLAUSES)} \\
        This function will print all of the evaluated \texttt{CLAUSES}
        in order with a newline at the end of it.

\item \texttt{[procedure] (printinl INDENT CLAUSES)} \\
        This function will \texttt{INDENT} a number of spaces and then
        print all of the evaluated \texttt{CLAUSES} in order with a
        newline at the end of it.

\item \texttt{[procedure] (output-style-human RESULTTREE)} \\
        This function will print out a human readable rendering of the
        \texttt{RESULTTREE} and return the toplevel package result.
\end{itemize}

\subsubsection{Example Usages of the Test Suite Infrastructure}

This section contains some simple examples of how to author test suites.

Here is a simple example:

\begin{verbatim}
(let ((result
        ;; output-style-human function requires a single test package
        ;; to encapsulate enverything.
        (test-package "Arithmetic Operators" pd pe

                (test-case "Testing '+'" d e
                        (expect-equal "Adding two positive numbers" 2 (+ 1 1))
                        (expect-equal "Adding two negative numbers" -2 (+ -1 -1))
                        (expect-zero "Adding positive and negative" (+ -1 1)))

                (test-case "Testing '-'" d e
                        (expect-zero "Subtracting two positive numbers" (- 1 1))
                        (expect-zero "Subtracting two negative numbers" (- -1 -1))
                        (expect-equal "Subtracting positive and negative" -2 (- -1 1))))))
        (output-style-human result))
\end{verbatim}

The above example, when evaluated, will produce some human readable output
and the a \#t value as the result of the top level package. The \texttt{result}
variable contains the tree of evaluated expectations, test cases, and the
package arranged in a hierarchy extremely similar to the nesting of the
above macros. If you desire to manipulate the result tree yourself, you
may use the various APIs to manipulate the various results. Please see the
implementation of \textbf{(output-style-human ...)} (it isn't large) in the
test-infrastructure.scm file to see an example of this.

The variables: \texttt{pe, e} are the escape functions you may use with the
\textbf{(teminate ...)} function call if you wish to abort the above code
somewhere.

The variables: \texttt{pd, d} allow use of a "destructor" object which allows
you to run side effecting functions at the "finishing" point of the evaluation
of the test case or test package. These functions are run no matter if the code
succeeded correctly or not, so be careful to manage the destructor object
carefully so you don't perform unwanted side effects. The names of the
destructor objects you supply are lexically scoped in the bodies of the
test case or test package.

Now, here is some example output that \textbf{(output-style-human ...)} might
generate with the above testing code:

\begin{verbatim}
Begin Package: Arithmetic Operators
  Begin Test Case: Testing '+'
    Begin Expectation: Adding two positive numbers
    Expect equal
      Expected Value: 
      2
      Unevaluated: 
      (+ 1 1)
      Evaluated: 
      2
    Result: #t
    End Expectation: Adding two positive numbers

    Begin Expectation: Adding two negative numbers
    Expect equal
      Expected Value: 
      -2
      Unevaluated: 
      (+ -1 -1)
      Evaluated: 
      -2
    Result: #t
    End Expectation: Adding two negative numbers

    Begin Expectation: Adding positive and negative
    Expect zero
      Unevaluated: 
      (+ -1 1)
      Evaluated: 
      0
    Result: #t
    End Expectation: Adding positive and negative

  Result: #t
  End Test Case: Testing '+'

  Begin Test Case: Testing '-'
    Begin Expectation: Subtracting two positive numbers
    Expect zero
      Unevaluated: 
      (- 1 1)
      Evaluated: 
      0
    Result: #t
    End Expectation: Subtracting two positive numbers

    Begin Expectation: Subtracting two negative numbers
    Expect zero
      Unevaluated: 
      (- -1 -1)
      Evaluated: 
      0
    Result: #t
    End Expectation: Subtracting two negative numbers

    Begin Expectation: Subtracting positive and negative
    Expect equal
      Expected Value: 
      -2
      Unevaluated: 
      (- -1 1)
      Evaluated: 
      -2
    Result: #t
    End Expectation: Subtracting positive and negative

  Result: #t
  End Test Case: Testing '-'

Result: #t
End Package: Arithmetic Operators

#t
\end{verbatim}

\section{Data Representation}


There exist two different kinds of data objects in the CHICKEN system:
immediate and non-immediate objects. Immediate objects are represented
by a tagged machine word, which is usually of 32 bits length (64 bits
on 64-bit architectures). The immediate objects come in four different
flavors:

\begin{itemize}

\item \textbf{fixnums}, that is, small exact integers, distinguished by
the lowest order bit in the machine word set to 1. This gives fixnums
a range of 31 bits for the actual numeric value (63 bit on 64 bit
architectures).

\item \textbf{characters}, where the lowest four bits of machine words
containing characters are equal to \texttt{C\_CHARACTER\_BITS}. The
ASCII code of the character is encoded in bits 9 to 16, counting from
1 and starting at the lowest order position.

\item \textbf{booleans}, where the lowest four bits of machine words
containing booleans are equal to \texttt{C\_BOOLEAN\_BITS}. Bit 5
(counting from 0 and starting at the lowest order position) is one if
the boolean designates true, or 0 if it is false.

\item other values: the empty list, void and end-of-file. The lowest
four bits of machine words containing these values are equal to
\texttt{C\_SPECIAL\_BITS}. Bits 5 to 8 contain an identifying
number for this type of object.  The following constants are
defined: \texttt{C\_SCHEME\_END\_OF\_LIST C\_SCHEME\_UNDEFINED
C\_SCHEME\_END\_OF\_FILE}

\end{itemize}

Non-immediate objects are blocks of data represented by a pointer into
the heap. The first word of the data block contains a header, which gives
information about the type of the object. The header has the size of a
machine word, usually 32 bits (64 bits on 64 bit architectures).

\begin{itemize}

\item bits 1 to 24 (starting at the lowest order position) contain the
length of the data object, which is either the number of bytes in a
string (or byte-vector) or the the number of elements for a vector or
for a structure type.

\item bits 25 to 28 contain the type code of the object.

\item bits 29 to 32 contain miscellaneous flags used for garbage
collection or internal data type dispatching.
These flags are:
\begin{description}

\item[C\_GC\_FORWARDING\_BIT]
Flag used for forwarding garbage collected object pointers.

\item[C\_BYTEBLOCK\_BIT]
Flag that specifies wether this data object contains raw bytes (a string
or byte-vector) or pointers to other data objects.

\item[C\_SPECIALBLOCK\_BIT]
Flag that specifies wether this object contains a ``special'' non-object
pointer value in its first slot. An example for this kind of objects
are closures, which are a vector-type object with the code-pointer as
the first item.

\item[C\_8ALIGN\_BIT]
Flag that specifies wether the data area of this block should be aligned
on an 8-byte boundary (floating-points numbers, for example).

\end{description}

\end{itemize}


The actual data follows immediately after the header. Note that
block-addresses are always aligned to the native machine-word
boundary. Scheme data objects map to blocks in the following manner:

\begin{itemize}

\item pairs: vector-like object (type bits \texttt{C\_PAIR\_TYPE}),
where the car and the cdr are contained in the first and second slots,
respectively.

\item vectors: vector object (type bits \texttt{C\_VECTOR\_TYPE}).

\item strings: byte-vector object (type bits \texttt{C\_STRING\_TYPE}).

\item procedures: special vector object (type bits
\texttt{C\_CLOSURE\_TYPE}). The first slot contains a pointer to a
compiled C function.

\item flonum: a byte-vector object (type bits
\texttt{C\_FLONUM\_BITS}). Slots one and two (or a single slot on
64 bit architectures) contain a 64-bit floating-point number, in the
representation used by the host systems C compiler.

\item symbol: a vector object (type bits \texttt{C\_SYMBOL\_TYPE}). Slots
one and two contain the toplevel variable value and the print-name
(a string) of the symbol, respectively.

\item port: a special vector object (type bits
\texttt{C\_PORT\_TYPE}). The first slot contains a pointer to a file-
stream, if this is a file-pointer, or NULL if not. The other slots
contain housekeeping data used for this port.

\item structure: a vector object (type bits
\texttt{C\_STRUCTURE\_TYPE}). The first slot contains a symbol that
specifies the kind of structure this record is an instance of. The other
slots contain the actual record items.

\item pointer: a special vector object (type bits
\texttt{C\_POINTER\_TYPE}). The single slot contains a machine pointer.

\item tagged pointer: similar to a pointer (type bits 
\texttt{C\_TAGGED\_POINTER\_TYPE}), but the object contains an additional
slot with a tag (an arbitrary data object) that identifies the type
of the pointer.

\end{itemize}


Data objects may be allocated outside of the garbage collected heap, as
long as their layout follows the above mentioned scheme. But care has to
be taken not to mutate these objects with heap-data (i.e. non-immediate
objects), because this will confuse the garbage collector.


For more information see the header file \texttt{chicken.h}.


\section{Bugs and limitations}


\begin{itemize}

\item Compiling large files takes too much time.

\item There is no support for rationals, complex numbers or
extended-precision integers (bignums).

\item The (non-standard) macros
\texttt{let-optionals, let-id-macro, define-id-macro, let-macro} 
and \texttt{define-entry-point} currently don't work in
combination with the high-level macro system.

\item The maximal number of arguments that may be passed to a compiled
procedure or macro is 126 (or 1024 on x86 platforms).  A macro-definition
that has a single rest-parameter can have any number of arguments.

\item The maximum number of values that can be passed to continuations
captured using \texttt{call-with-current-continuation} is 126.

\item Some numeric procedures are missing since CHICKEN does not support
the full numeric tower.

\item The compiler and programs generated by it need a fairly large
amount of memory.

\item If a known procedure has unused arguments, but is always called
without those parameters, then the optimizer ``repairs'' the procedure
in certain situations and removes the parameter from the lambda-list.

\item \texttt{eval-when} doesn't allow toplevel definitions inside it's
body in combination with hygienic macros.

\item \texttt{define-values} can not be used in internal definitions
when the hygienic macro system is used.

\item \texttt{port-position} currently works only for input ports.

\item Leaf routine optimization can theoretically result in code that
thrashes, if tight loops perform excessively many mutations.

\item Building CHICKEN on RS/6000 systems under AIX is currently not
possible, due to strange assembler errors during compilation of the
compiler sources.

\item If \texttt{eval} is invoked with \texttt{scheme-report-environment}
or \texttt{null-environment} inside the interpreter, then non-standard
syntax is still visible, unless the interpreter has been started with
the \texttt{-strict} option.

\item A source file to be compiled may not begin with the \texttt{\#}
character if it is not a script-file (beginning with \texttt{\#!}).

\item When the highlevel macro system is used,
line number information is not properly maintained.

\end{itemize}



\section{Acknowledgements}

\begin{itemize}

\item Jonah Beckford added CHICKEN-support to SWIG\footnote{http://www.swig.org} and
provided support for shared libraries and dynamic loading under Windows.

\item Steve Elkins ported CHICKEN to OpenBSD.

\item Tony Garnock-Jones ported CHICKEN to HP-UX and provided countless
fixes and improvements.

\item Sven Hartrumpf helped porting CHICKEN to the UltraSparc, suggested
many improvements and helped fixing numerous bugs.

\item Dale Jordan pointed out several bugs, helped fixing problems on the
Cygwin platform and contributed the \texttt{calendar.scm} example script.

\item Peter Keller translated the manual from HTML into \LaTeX and contributed
the testing infrastructure code.

\item Kirill Lisovsky found a couple of bugs while porting Oleg Kiselyov's
SSAX XML parser to CHICKEN.

\item Dennis Marti ported CHICKEN to Mac OS X.

\item Chris Moline and Bakul Shah helped porting CHICKEN to FreeBSD.

\item Davide Puricelli maintains the Debian package.

\item Doug Quale contributed the configuration scripts for installation
on UNIX-like systems, suggested numerous improvements and was generally
very helpful.

\item Benedikt Rosenau found several bugs and spent a lot of time testing
the system and pointing out improvements.

\item Dorai Sitaram pointed out several improvements in the TeX manual.

\item Mike Thomas ported CHICKEN to the Mingw32 platform.

\item John Tobey ported CHICKEN to MIPS.

\item Panagiotis Vossos ported CHICKEN to Alpha/Linux.

\item J\"{o}rg Wittenberger found and fixed countless bugs in the runtime system.


\item CHICKEN contains code from several people:
\begin{itemize}
\item Eli Barzilay: some performance tweaks used in TinyCLOS.
\item Anthony Carrico: the option parsing facility.
\item Mikael Djurfeldt: topological sort used by compiler.
\item Marc Feeley: pretty-printer.
\item Aubrey Jaffer: implementation of \texttt{dynamic-wind}.
\item R. Kent Dybvig, Oscar Waddel, Robert Hieb \& Carl Bruggeman: \texttt{syntax-case} macro system.
\item Richard Kelsey: reference implementation of SRFI-9.
\item Gregor Kiczales: original implementation of TinyCLOS.
\item Dirk Lutzebaeck: Common LISP \texttt{format}.
\item Richard O'Keefe: sorting routines.
\item Jussi Piitulainen: reference implementation for SRFI-25.
\item Olin Shivers: implementation of \texttt{let-optionals[*]} and
reference implementations of SRFI-1, SRFI-13 and SRFI-14.
\item Dorai Sitaram: the PREGEXP regular expression package and
TeX2page, which was used to generate the HTML documentation.
\item Andrew Wilcox: queues.
\item Andrew Wright: pattern matcher.
\end{itemize}

\end{itemize}


Thanks also to William Annis, Dave Bodenstab, Roy Bryant, Franklin Chen,
James Crippen, Brian Denheyer, Martin Gasbichler, Joey Gibson, Andreas
Gustafsson, Karl M. Hegbloom, William P. Heinemann, Bruce Hoult, Dale
Jordan, Valentin Kamyshenko, Ron Kneusel, Charles Martin, Perry Metzger,
Eric E. Moore, ``o.t.'', David Rush, Oskar Schirmer, Burton Samograd, Ronald Schr\"{o}der,
Jeffrey B. Siegal, Jason Songhurst, Christian Tismer, Vladimir Tsichevsky, 
Sander Vesik, Shawn Wagner, Peter Wang, Matthew Welland and 
Richard Zidlicky for bug-fixes, tips, suggestions and moral support.


\begin{thebibliography}{99}
\bibitem{cotmta}
Henry Baker: {\it CONS Should Not CONS Its Arguments, Part II: Cheney on the M.T.A.}
\texttt{http://home.pipeline.com/~hbaker1/CheneyMTA.html}
\bibitem{r5rs}
Revised\^{}5 Report on the Algorithmic Language Scheme
\texttt{http://www.schemers.org/Documents/Standards/R5RS}
\end{thebibliography}

\end{document}
