\input texinfo
@c %**start of header
@setfilename gambit-c.info
@settitle Gambit-C, a portable implementation of Scheme
@finalout
@c %**end of header

@include version.txi

@iftex
@tableindent=1.3in
@end iftex

@ifinfo
@format
START-INFO-DIR-ENTRY
* Gambit-C: (gambit-c).		A portable implementation of Scheme.
* gsi: (gambit-c) interpreter.	Gambit interpreter.
* gsc: (gambit-c) compiler.	Gambit compiler.
END-INFO-DIR-ENTRY
@end format
@end ifinfo

@c Define new indices for commands, file names, and options.
@defcodeindex cm
@defcodeindex fl
@defcodeindex op

@c Put everything in one index (arbitrarily chosen to be the concept index).
@syncodeindex cm cp
@syncodeindex fl cp
@syncodeindex fn cp
@syncodeindex ky cp
@syncodeindex op cp
@syncodeindex pg cp
@syncodeindex vr cp

@ifinfo
This file documents Gambit-C, a portable implementation of Scheme.

Copyright (C) 1994-2009 Marc Feeley.

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.

@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).

@end ignore
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the copyright holder.
@end ifinfo

@titlepage
@title Gambit-C @value{VERSION}
@subtitle A portable implementation of Scheme
@subtitle Edition @value{EDITION}, @value{UPDATED}
@author Marc Feeley

@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1994-2009 Marc Feeley.

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.

Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the copyright holder.
@end titlepage

@ifnottex

@node Top, , (dir), (dir)
@top Gambit-C
@cindex Gambit-C
@cindex Scheme, implementation of

This manual documents Gambit-C.  It covers release @value{VERSION}.

@menu
* The Gambit-C system::             The Gambit-C system
* Accessing the system files::      Accessing the system files
* GSI::                             The Gambit Scheme interpreter
* GSC::                             The Gambit Scheme compiler
* Runtime options::                 Runtime options
* Debugging::                       Debugging
* Scheme extensions::               Scheme extensions
* Namespaces::                      Namespaces
* Characters and strings::          Characters and strings
* Numbers::                         Numbers
* Homogeneous vectors::             Homogeneous vectors
* Hashing and weak references::     Hashing and weak references
* Records::                         Records
* Threads::                         Threads
* Dynamic environment::             Dynamic environment
* Exceptions::                      Exceptions
* Host environment::                Host environment
* I/O and ports::                   I/O and ports
* Lexical syntax and readtables::   Lexical syntax and readtables
* C-interface::                     C-interface
* System limitations::              System limitations
* Copyright and license::           Copyright and license
* General index::                   General index
@end menu

@end ifnottex

@node The Gambit-C system, GSI, Top, Top
@chapter The Gambit-C system
@cindex Gambit
@cindex Gambit-C
@cindex Scheme

@pindex gsi
@pindex gsc
The Gambit programming system is a full implementation of the Scheme
language which conforms to the R4RS, R5RS and IEEE Scheme standards.  It
consists of two main programs: @code{gsi}, the Gambit Scheme
interpreter, and @code{gsc}, the Gambit Scheme compiler.

Gambit-C is a version of the Gambit programming system in which the
compiler generates portable C code, making the whole Gambit-C system and
the programs compiled with it easily portable to many computer
architectures for which a C compiler is available.  With appropriate
declarations in the source code the executable programs generated by
the compiler run roughly as fast as equivalent C programs.

For the most up to date information on Gambit and add-on packages
please check the Gambit web page at
@uref{http://gambitscheme.org}.  The web page has links to the
Gambit mailing list, the bug reporting system, and the source code
repository.

@menu
* Accessing the system files::      Accessing the system files
@end menu

@node Accessing the system files, , The Gambit-C system, The Gambit-C system
@section Accessing the system files

Files related to Gambit, such as executables, libraries and header files,
are stored in multiple @dfn{Gambit installation directories}.
Gambit may be installed on a system according to two different
installation models.

In the first model there is a single directory where all the Gambit
installation directories are stored.  This @dfn{central installation
directory} is typically @code{/usr/local/Gambit-C} under UNIX,
@code{/Library/Gambit-C} under Mac OS X and @code{C:/Program
Files/Gambit-C} under Microsoft Windows.  This may have been
overridden when the system was built with the command @samp{configure
--prefix=/my/Gambit-C}.  If the system was built with the command
@samp{configure --enable-multiple-versions} then the central
installation directory is @code{@r{@i{prefix}}/@r{@i{version}}}, where
@code{@r{@i{version}}} is the system version string
(e.g. @code{@value{VERSION}} for Gambit @value{VERSION}).  Moreover,
@code{@r{@i{prefix}}/current} will be a symbolic link which points to
the central installation directory.  In this model, the Gambit
installation directory named @var{X} is simply the subdirectory
@var{X} of the central installation directory.

In the second model some or all of the Gambit installation directories
are stored in installation specific directories.  The location of
these directories is assigned when the system is built using the
command @samp{configure --bindir=/my/bin --includedir=/my/include
--libdir=/my/lib}.

The advantage of the first model is that it is easy to have multiple
versions of Gambit coexist and to remove all the files of a given
version.  However, the second model may be necessary to conform to the
package installation conventions of some operating systems.

Executable programs such as the interpreter @code{gsi} and compiler
@code{gsc} can be found in the @code{bin} installation directory.
Adding this directory to the @code{PATH} environment variable allows
these programs to be started by simply entering their name.  This is
done automatically by the Mac OS X and Microsoft Windows installers.

The runtime library is located in the @code{lib} installation
directory.  When the system's runtime library is built as a
shared-library (with the command @samp{configure --enable-shared}) all
programs built with Gambit-C, including the interpreter and compiler,
need to find this library when they are executed and consequently this
directory must be in the path searched by the system for
shared-libraries.  This path is normally specified through an
environment variable which is @code{LD_LIBRARY_PATH} on most versions
of UNIX, @code{LIBPATH} on AIX, @code{SHLIB_PATH} on HPUX,
@code{DYLD_LIBRARY_PATH} on Mac OS X, and @code{PATH} on Microsoft
Windows.  If the shell is @code{sh}, the setting of the path can be
made for a single execution by prefixing the program name with the
environment variable assignment, as in:

@smallexample
@b{}$ @b{LD_LIBRARY_PATH=/usr/local/Gambit-C/lib gsi}
@end smallexample

A similar problem exists with the Gambit header file @code{gambit.h},
located in the @code{include} installation directory.  This header
file is needed for compiling Scheme programs with the Gambit-C
compiler.  When the C compiler is being called explicitly it may be
necessary to use a @code{-I@var{<dir>}} command line option to
indicate where to find header files and a @code{-L@var{<dir>}} command
line option to indicate where to find libraries.

Access to both of these files can be simplified by creating a link to
them in the appropriate system directories (special privileges may
however be required):

@smallexample
@b{}$ @b{ln -s /usr/local/Gambit-C/lib/libgambc.a /usr/lib} @r{@i{# name may vary}}
$ @b{ln -s /usr/local/Gambit-C/include/gambit.h /usr/include}
@end smallexample

Alternatively these files can be copied or linked in the directory
where the C compiler is invoked (this requires no special privileges).

Another approach is to set some environment variables which
are used to tell the C compiler where to find header files
and libraries.  For example, the following settings can be
used for the @code{gcc} C compiler:

@smallexample
@b{}$ @b{export LIBRARY_PATH=/usr/local/Gambit-C/lib}
$ @b{export CPATH=/usr/local/Gambit-C/include}
@end smallexample

Note that this may have been done by the installation process.  In
particular, the Mac OS X and Microsoft Windows prebuilt installers set
up the environment so that the @code{gcc} compiler finds these files
automatically.

@ifinfo

@menu
* GSI::                             The Gambit Scheme interpreter
* GSC::                             The Gambit Scheme compiler
* Runtime options::                 Runtime options
* Debugging::                       Debugging
* Scheme extensions::               Scheme extensions
* Namespaces::                      Namespaces
* Characters and strings::          Characters and strings
* Numbers::                         Numbers
* Homogeneous vectors::             Homogeneous vectors
* Hashing and weak references::     Hashing and weak references
* Records::                         Records
* Threads::                         Threads
* Dynamic environment::             Dynamic environment
* Exceptions::                      Exceptions
* Host environment::                Host environment
* I/O and ports::                   I/O and ports
* Lexical syntax and readtables::   Lexical syntax and readtables
* C-interface::                     C-interface
* System limitations::              System limitations
* Copyright and license::           Copyright and license
@end menu

@end ifinfo

@node GSI, GSC, The Gambit-C system, Top
@chapter The Gambit Scheme interpreter
@cindex interpreter

Synopsis:

@example
@b{}gsi @r{[}-:@r{@var{runtimeoption}},@dots{}@r{]} @r{[}-i@r{]} @r{[}-f@r{]} @r{[}-v@r{]} @r{[}@r{[}-@r{]} @r{[}-e @r{@var{expressions}}@r{]} @r{[}@r{@var{file}}@r{]}@r{]}@dots{}
@end example

@pindex gsi
The interpreter is executed in @dfn{interactive mode} when no file or
@samp{-} or @samp{-e} option is given on the command line.  Otherwise
the interpreter is executed in @dfn{batch mode}.  The @samp{-i} option
is ignored by the interpreter.  The initialization file will be
examined unless the @samp{-f} option is present (@pxref{GSI
customization}).  The @samp{-v} option prints the system version
string, system time stamp, operating system type, and configure script
options on standard output and exits.  Runtime options are explained
in @ref{Runtime options}.

@menu
* GSI interactive mode::            Interactive mode
* GSI batch mode::                  Batch mode
* GSI customization::               Customization
* GSI exit status::                 Process exit status
* Scheme scripts::                  Scheme scripts
@end menu

@node GSI interactive mode, GSI batch mode, GSI, GSI
@section Interactive mode

In interactive mode a read-eval-print loop (REPL) is started for the
user to interact with the interpreter.  At each iteration of this loop
the interpreter displays a prompt, reads a command and executes it.
The commands can be expressions to evaluate (the typical case)
or special commands related to debugging, for example @samp{,q} to
terminate the process (for a complete list of commands see
@ref{Debugging}).  Most commands produce some output, such as the
value or error message resulting from an evaluation.

The input and output of the interaction is done on the
@dfn{interaction channel}.  The interaction channel can be specified
through the runtime options but if none is specified the system uses a
reasonable default that depends on the system's configuration.  When
the system's runtime library was built with support for GUIDE, the
Gambit Universal IDE (with the command @samp{configure
--enable-guide}) the interaction channel corresponds to the
@dfn{console window} of the primordial thread (for details see
@ref{GUIDE}), otherwise the interaction channel is the user's
@dfn{console}, also known as the @dfn{controlling terminal} in the
UNIX world.  When the REPL starts, the ports associated with
@samp{(current-input-port)}, @samp{(current-output-port)} and
@samp{(current-error-port)} all refer to the interaction channel.

Expressions are evaluated in the global @dfn{interaction environment}.
The interpreter adds to this environment any definition entered using
the @code{define} and @code{define-macro}
special forms.  Once the evaluation of an expression is completed, the
value or values resulting from the evaluation are output to the
interaction channel by the pretty printer.  The special ``void''
object is not output.  This object is returned by most procedures and
special forms which the Scheme standard defines as returning an
unspecified value (e.g. @code{write}, @code{set!}, @code{define}).

Here is a sample interaction with @code{gsi}:

@smallexample
$ @b{gsi}
Gambit @value{VERSION}

> @b{(define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))}
> @b{(map fact '(1 2 3 4 5 6))}
(1 2 6 24 120 720)
> @b{(values (fact 10) (fact 40))}
3628800
815915283247897734345611269596115894272000000000
> @b{,q}
@end smallexample

What happens when errors occur is explained in @ref{Debugging}.

@node GSI batch mode, GSI customization, GSI interactive mode, GSI
@section Batch mode

In batch mode the command line arguments denote files to be loaded,
REPL interactions to start (@samp{-} option), and expressions to be
evaluated (@samp{-e} option).  Note that the @samp{-} and @samp{-e}
options can be interspersed with the files on the command line and can
occur multiple times.  The interpreter processes the command line
arguments from left to right, loading files with the @code{load}
procedure and evaluating expressions with the @code{eval} procedure in
the global interaction environment.  After this processing the
interpreter exits.

When the file name has no extension the @code{load} procedure first
attempts to load the file with no extension as a Scheme source file.
If that file doesn't exist it will search for both a source file and
an object file.  The object file's name is obtained by adding to the
file name a @samp{.o@var{n}} extension with the highest consecutive
version number starting with 1.  The source file's name is obtained by
adding to the file name the file extensions @samp{.scm} and
@samp{.six} (the first found is the source file).  If both a source
file and an object file exist, then the one with the latest
modification time is loaded.  Otherwise the file that is found is
loaded.  When the file name has an extension, the @code{load}
procedure will only attempt to load the file with that specific name.

When the extension of the file loaded is @samp{.scm} the content of
the file will be parsed using the normal Scheme prefix syntax.  When
the extension of the file loaded is @samp{.six} the content of the
file will be parsed using the Scheme infix syntax extension (see
@ref{Scheme infix syntax extension}).  Otherwise, @code{gsi} will
parse the file using the normal Scheme prefix syntax.

The ports associated with @samp{(current-input-port)},
@samp{(current-output-port)} and @samp{(current-error-port)} initially
refer respectively to the standard input (@samp{stdin}), standard
output (@samp{stdout}) and the standard error (@samp{stderr}) of the
interpreter.  This is true even in REPLs started with the @samp{-}
option.  The usual interaction channel (console or IDE's console
window) is still used to read expressions and commands and to display
results.  This makes it possible to use REPLs to debug programs which
read the standard input and write to the standard output, even when
these have been redirected.

Here is a sample use of the interpreter in batch mode, under UNIX:

@smallexample
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{cat w.six}
display("world"); newline();
$ @b{gsi h.scm - w.six -e "(pretty-print 1)(pretty-print 2)"}
hello
> @b{(define (display x) (write (reverse (string->list x))))}
> @b{,(c 0)}
(#\d #\l #\r #\o #\w)
1
2
@end smallexample

@node GSI customization, GSI exit status, GSI batch mode, GSI
@section Customization

There are two ways to customize the interpreter.  When the interpreter
starts off it tries to execute a @samp{(load "~~lib/gambcext")} (for an
explanation of how file names are interpreted see @ref{Host environment}).
An error is not signaled when the file does not exist.  Interpreter
extensions and patches that are meant to apply to all users and all
modes should go in that file.

Extensions which are meant to apply to a single user or to a specific
working directory are best placed in the @dfn{initialization file},
which is a file containing Scheme code.  In all modes, the interpreter
first tries to locate the initialization file by searching the following
locations: @file{.gambcini} and @file{~/.gambcini} (with no extension, a
@samp{.scm} extension, and a @samp{.six} extension in that order).  The
first file that is found is examined as though the expression
@code{(include @var{initialization-file})} had been entered at the
read-eval-print loop where @var{initialization-file} is the file that
was found.  Note that by using an @code{include} the macros defined in
the initialization file will be visible from the read-eval-print loop
(this would not have been the case if @code{load} had been used).  The
initialization file is not searched for or examined when the @samp{-f}
option is specified.

@node GSI exit status, Scheme scripts, GSI customization, GSI
@section Process exit status

The status is zero when the interpreter exits normally and is nonzero
when the interpreter exits due to an error.  Here is the meaning of
the exit statuses:

@table @code

@item 0
The execution of the primordial thread (i.e. the main thread) did not
encounter any error.  It is however possible that other threads
terminated abnormally (by default threads other than the primordial
thread terminate silently when they raise an exception that is not
handled).

@item 64
The runtime options or the environment variable @samp{GAMBCOPT}
contained a syntax error or were invalid.

@item 70
This normally indicates that an exception was raised in the primordial
thread and the exception was not handled.

@item 71
There was a problem initializing the runtime system, for example
insufficient memory to allocate critical tables.

@end table

For example, if the shell is @code{sh}:

@smallexample
$ @b{gsi -:d0 -e "(pretty-print (expt 2 100))"}
1267650600228229401496703205376
$ @b{echo $?}
0
$ @b{gsi -:d0,unknown @r{@i{# try to use an unknown runtime option}}}
$ @b{echo $?}
64
$ @b{gsi -:d0 nonexistent.scm @r{@i{# try to load a file that does not exist}}}
$ @b{echo $?}
70
$ @b{gsi nonexistent.scm}
*** ERROR IN ##main -- No such file or directory
(load "nonexistent.scm")
$ @b{echo $?}
70
@end smallexample

@smallexample
@b{}$ @b{gsi -:m4000000 @r{@i{# ask for a 4 gigabyte heap}}}
*** malloc: vm_allocate(size=528384) failed (error code=3)
*** malloc[15068]: error: Can't allocate region
$ @b{echo $?}
71
@end smallexample

Note the use of the runtime option @samp{-:d0} that prevents error
messages from being output, and the runtime option @samp{-:m4000000}
which sets the minimum heap size to 4 gigabytes.

@node Scheme scripts, , GSI exit status, GSI
@section Scheme scripts

The @code{load} procedure treats specially files that begin with the
two characters @samp{#!} and @samp{@@;}.  Such files are called
@dfn{script files} and the first line is called the @dfn{script line}.
In addition to indicating that the file is a script, the script line
provides information about the source code language to be used by the
@code{load} procedure.  After the two characters @samp{#!} and
@samp{@@;} the system will search for the first substring matching one
of the following language specifying tokens:

@table @code

@item scheme-r4rs
@pindex scheme-r4rs
R4RS language with prefix syntax, case-insensitivity, keyword syntax
not supported

@item scheme-r5rs
@pindex scheme-r5rs
R5RS language with prefix syntax, case-insensitivity, keyword syntax
not supported

@item scheme-ieee-1178-1990
@pindex scheme-ieee-1178-1990
IEEE 1178-1990 language with prefix syntax, case-insensitivity, keyword
syntax not supported

@item scheme-srfi-0
@pindex scheme-srfi-0
R5RS language with prefix syntax and SRFI 0 support
(i.e. @code{cond-expand} special form), case-insensitivity, keyword
syntax not supported

@item gsi-script
@pindex gsi-script
Full Gambit Scheme language with prefix syntax, case-sensitivity, keyword
syntax supported

@item gsc-script
@pindex gsc-script
Full Gambit Scheme language with prefix syntax, case-sensitivity, keyword
syntax supported

@item six-script
@pindex six-script
Full Gambit Scheme language with infix syntax, case-sensitivity, keyword
syntax supported

@end table

If a language specifying token is not found, @code{load} will use the
same language as a nonscript file (i.e. it uses the file extension and
runtime system options to determine the language).

After processing the script line, @code{load} will parse the rest of
the file (using the syntax of the language indicated) and then execute
it.  When the file is being loaded because it is an argument on the
interpreter's command line, the interpreter will:

@itemize @bullet{}

@item
@findex command-line
Setup the @code{command-line} procedure so that it returns a list
containing the expanded file name of the script file and the
arguments following the script file on the command line.
This is done before the script is executed.  The expanded file name
of the script file can be used to determine the directory that
contains the script (i.e. @code{(path-directory (car (command-line)))}).

@item
After the script is loaded the procedure @code{main} is called with
the command-line arguments.  The way this is done depends on the
language specifying token.  For @code{scheme-r4rs},
@code{scheme-r5rs}, @code{scheme-ieee-1178-1990}, and
@code{scheme-srfi-0}, the @code{main} procedure is called with the
equivalent of @code{(main (cdr (command-line)))} and @code{main} is
expected to return a process exit status code in the range 0 to 255.
This conforms to the ``Running Scheme Scripts on Unix SRFI'' (SRFI
22).  For @code{gsi-script} and @code{six-script} the @code{main}
procedure is called with the equivalent of @code{(apply main (cdr
(command-line)))} and the process exit status code is 0 (@code{main}'s
result is ignored).  The Gambit-C system has a predefined @code{main}
procedure which accepts any number of arguments and returns 0, so it
is perfectly valid for a script to not define @code{main} and to do
all its processing with top-level expressions (examples are given in
the next section).

@item
When @code{main} returns, the interpreter exits.  The command-line
arguments after a script file are consequently not processed (however
they do appear in the list returned by the @code{command-line}
procedure, after the script file's expanded file name, so it is up to
the script to process them).

@end itemize

@menu
* Scripts under UNIX and Mac OS X:: Scripts under UNIX and Mac OS X
* Scripts under Microsoft Windows:: Scripts under Microsoft Windows
* Compiling scripts::               Compiling scripts
@end menu

@node Scripts under UNIX and Mac OS X, Scripts under Microsoft Windows, Scheme scripts, Scheme scripts
@subsection Scripts under UNIX and Mac OS X

Under UNIX and Mac OS X, the Gambit-C installation process creates the
executable @samp{gsi} and also the executables @samp{six},
@samp{gsi-script}, @samp{six-script}, @samp{scheme-r5rs},
@samp{scheme-srfi-0}, etc as links to @samp{gsi}.  A Scheme script
need only start with the name of the desired Scheme language variant
prefixed with @samp{#!} and the directory where the Gambit-C
executables are stored.  This script should be made executable by
setting the execute permission bits (with a @samp{chmod +x
@var{script}}).  Here is an example of a script which lists on standard
output the files in the current directory:

@smallexample
@b{}#!/usr/local/Gambit-C/bin/gsi-script
(for-each pretty-print (directory-files))
@end smallexample

Here is another UNIX script, using the Scheme infix syntax extension,
which takes a single integer argument and prints on standard output the
numbers from 1 to that integer:

@smallexample
@b{}#!/usr/local/Gambit-C/bin/six-script

void main (obj n_str)
@{
  int n = \string->number(n_str);
  for (int i=1; i<=n; i++)
    \pretty-print(i);
@}
@end smallexample

For maximal portability it is a good idea to start scripts indirectly
through the @samp{/usr/bin/env} program, so that the executable of the
interpreter will be searched in the user's @samp{PATH}.  This is what
SRFI 22 recommends.  For example here is a script that mimics the UNIX
@samp{cat} utility for text files:

@smallexample
@b{}#!/usr/bin/env gsi-script

(define (display-file filename)
  (display (call-with-input-file filename
             (lambda (port)
               (read-line port #f)))))

(for-each display-file (cdr (command-line)))
@end smallexample

@node Scripts under Microsoft Windows, Compiling scripts, Scripts under UNIX and Mac OS X, Scheme scripts
@subsection Scripts under Microsoft Windows

Under Microsoft Windows, the Gambit-C installation process creates the
executable @samp{gsi.exe} and @samp{six.exe} and also the batch files
@samp{gsi-script.bat}, @samp{six-script.bat}, @samp{scheme-r5rs.bat},
@samp{scheme-srfi-0.bat}, etc which simply invoke @samp{gsi.exe} with
the same command line arguments.  A Scheme script need only start with
the name of the desired Scheme language variant prefixed with
@samp{@@;}.  A UNIX script can be converted to a Microsoft Windows
script simply by changing the script line and storing the script in a
file whose name has a @samp{.bat} or @samp{.cmd} extension:

@smallexample
@b{}@@;gsi-script %~f0 %*
(display "files:\n")
(pretty-print (directory-files))
@end smallexample

Note that Microsoft Windows always searches executables in the user's
@samp{PATH}, so there is no need for an indirection such as the UNIX
@samp{/usr/bin/env}.  However the script line must end with @samp{%~f0
%*} to pass the expanded filename of the script and command line
arguments to the interpreter.

@node Compiling scripts, , Scripts under Microsoft Windows, Scheme scripts
@subsection Compiling scripts

A script file can be compiled using the Gambit Scheme compiler
(@pxref{GSC}) into a standalone executable.  The script line will
provide information to the compiler on which language to use.  The
script line also provides information on which runtime options to use
when executing the compiled script.  This is useful to set the default
runtime options of an executable program.

The compiled script will be executed similarly to an interpreted
script (i.e. the list of command line arguments returned by the
@code{command-line} procedure and the invocation of the @code{main}
procedure).

For example:

@smallexample
$ @b{cat square.scm}
#!/usr/local/Gambit-C/bin/gsi-script -:d0
(define (main arg)
  (pretty-print (expt (string->number arg) 2)))
$ @b{gsi square 30        @r{@i{# gsi will load square.scm}}}
900
$ @b{gsc -exe square      @r{@i{# compile the script to a standalone program}}}
$ @b{./square 30}
900
$ @b{./square 1 2 3       @r{@i{# too many arguments to main}}}
$ @b{echo $?}
70
$ @b{./square -:d1 1 2 3  @r{@i{# ask for error message}}}
*** ERROR -- Wrong number of arguments passed to procedure
(main "1" "2" "3")
@end smallexample

@node GSC, Runtime options, GSI, Top
@chapter The Gambit Scheme compiler
@cindex compiler
@cindex interpreter

Synopsis:

@example
@b{}gsc @r{[}-:@r{@var{runtimeoption}},@dots{}@r{]} @r{[}-i@r{]} @r{[}-f@r{]} @r{[}-v@r{]}
    @r{[}-prelude @r{@var{expressions}}@r{]} @r{[}-postlude @r{@var{expressions}}@r{]}
    @r{[}-dynamic@r{]} @r{[}-exe@r{]} @r{[}-obj@r{]} @r{[}-cc-options @r{@var{options}}@r{]}
    @r{[}-ld-options-prelude @r{@var{options}}@r{]} @r{[}-ld-options @r{@var{options}}@r{]}
    @r{[}-warnings@r{]} @r{[}-verbose@r{]} @r{[}-report@r{]} @r{[}-expansion@r{]} @r{[}-gvm@r{]}
    @r{[}-debug@r{]} @r{[}-debug-location@r{]} @r{[}-debug-source@r{]}
    @r{[}-debug-environments@r{]} @r{[}-track-scheme@r{]}
    @r{[}-o @r{@var{output}}@r{]} @r{[}-c@r{]} @r{[}-keep-c@r{]} @r{[}-link@r{]} @r{[}-flat@r{]} @r{[}-l @r{@var{base}}@r{]}
    @r{[}@r{[}-@r{]} @r{[}-e @r{@var{expressions}}@r{]} @r{[}@r{@var{file}}@r{]}@r{]}@dots{}
@end example

@menu
* GSC interactive mode::            Interactive mode
* GSC customization::               Customization
* GSC batch mode::                  Batch mode
* Link files::                      Link files
* Procedures specific to compiler:: Procedures specific to compiler
@end menu

@node GSC interactive mode, GSC customization, GSC, GSC
@section Interactive mode

When no command line argument is present other than options the
compiler behaves like the interpreter in interactive mode.  The only
difference with the interpreter is that the compilation related
procedures listed in this chapter are also available
(i.e. @code{compile-file}, @code{compile-file-to-target}, etc).

@node GSC customization, GSC batch mode, GSC interactive mode, GSC
@section Customization

Like the interpreter, the compiler will examine the initialization
file unless the @samp{-f} option is specified.

@node GSC batch mode, Link files, GSC customization, GSC
@section Batch mode

@pindex gsc
@flindex .scm
@flindex .six
@flindex .c
@flindex @var{file}.scm
@flindex @var{file}.six
@flindex @var{file}.c
In batch mode @code{gsc} takes a set of file names (with either no
extension, or a C file extension, or some other extension) on the
command line and compiles each Scheme file into a C file.
The recognized C file extensions are @samp{.c}, @samp{.C}, @samp{.cc},
@samp{.cp}, @samp{.cpp}, @samp{.CPP}, @samp{.cxx}, @samp{.c++},
@samp{.m}, @samp{.M}, and @samp{.mm}.
The extension can be omitted from @var{file} when the Scheme file has a
@samp{.scm} or @samp{.six} extension.  When the extension of the
Scheme file is @samp{.six} the content of the file will be parsed
using the Scheme infix syntax extension (see @ref{Scheme infix syntax
extension}). Otherwise, @code{gsc} will parse the Scheme file using the
normal Scheme prefix syntax.  Files with a C file extension must
have been previously produced by @code{gsc}, with the @samp{-c} option,
and are used by Gambit's linker.

For each Scheme file a C file @samp{@var{file}.c} will be produced.
The C file's name is the same as the Scheme file, but the extension is
changed to @samp{.c}.  By default the C file is created in the same
directory as the Scheme file.  This default can be overridden with the
compiler's @samp{-o} option.

The C files produced by the compiler serve two purposes.  They will be
processed by a C compiler to generate object files, and they also
contain information to be read by Gambit's linker to generate a
@dfn{link file}.  The link file is a C file that collects various
linking information for a group of modules, such as the set of all
symbols and global variables used by the modules.
@opindex -link
@opindex -exe
The linker is only invoked when the @samp{-link} or @samp{-exe}
options appear on the command line.

Compiler options must be specified before the first file name and
after the @samp{-:} runtime option (@pxref{Runtime options}).  If
present, the @samp{-i}, @samp{-f}, and @samp{-v} compiler options
must come first.  The available options are:

@cindex compiler options
@cindex options, compiler
@table @code
@item -i
Force interpreter mode.
@item -f
Do not examine the initialization file.
@item -v
Print the system version string, system time stamp, operating system
type, and configure script options on standard output and exit.
@item -prelude @var{expressions}
Add expressions to the top of the source code being compiled.
@item -postlude @var{expressions}
Add expressions to the bottom of the source code being compiled.
@item -cc-options @var{options}
Add options to the command that invokes the C compiler.
@item -ld-options-prelude @var{options}
Add options to the command that invokes the C linker.
@item -ld-options @var{options}
Add options to the command that invokes the C linker.
@item -warnings
Display warnings.
@item -verbose
Display a trace of the compiler's activity.
@item -report
Display a global variable usage report.
@item -expansion
Display the source code after expansion.
@item -gvm
Generate a listing of the GVM code.
@item -debug
Include all debugging information in the code generated.
@item -debug-location
Include source code location debugging information in the code generated.
@item -debug-source
Include the source code debugging information in the code generated.
@item -debug-environments
Include environment debugging information in the code generated.
@item -track-scheme
Generate @samp{#line} directives referring back to the Scheme code.
@item -o @var{output}
Set name of output file or directory where output file(s) are written.
@item -dynamic
Compile Scheme source files to dynamically loadable object
files (this is the default).
@item -exe
Compile Scheme source files into an executable program.
@item -obj
Compile Scheme source files to object files.
@item -keep-c
Keep any intermediate @samp{.c} files that are generated.
@item -c
Compile Scheme source files to C without generating link file.
@item -link
Compile Scheme source files to C and generate a link file.
@item -flat
Generate a flat link file instead of the default incremental link file.
@item -l @var{base}
Specify the link file of the base library to use for the link.
@item -
Start REPL interaction.
@item -e @var{expressions}
Evaluate expressions in the interaction environment.
@end table

@opindex -i
The @samp{-i} option forces the compiler to process the remaining
command line arguments like the interpreter.

@opindex -prelude
The @samp{-prelude} option adds the specified expressions to the top of
the source code being compiled.  The main use of this option is to
supply declarations on the command line.  For example the following
invocation of the compiler will compile the file @samp{bench.scm} in
unsafe mode:

@smallexample
$ @b{gsc -prelude "(declare (not safe))" bench.scm}
@end smallexample

@opindex -postlude
The @samp{-postlude} option adds the specified expressions to the bottom
of the source code being compiled.  The main use of this option is to
supply the expression that will start the execution of the program.  For
example:

@smallexample
$ @b{gsc -postlude "(start-bench)" bench.scm}
@end smallexample

@opindex -cc-options
The @samp{-cc-options} option is only meaningful when a dynamically
loadable object file is being generated (neither the @samp{-c} or
@samp{-link} options are used).  The @samp{-cc-options} option adds
the specified options to the command that invokes the C compiler.  The
main use of this option is to specify the include path, some symbols
to define or undefine, the optimization level, or any C compiler
option that is different from the default.  For example:

@smallexample
$ @b{gsc -cc-options "-U___SINGLE_HOST -O2 -I../include" bench.scm}
@end smallexample

@opindex -ld-options-prelude
@opindex -ld-options
The @samp{-ld-options-prelude} and @samp{-ld-options} options are only
meaningful when a dynamically loadable object file is being generated
(neither the @samp{-c} or @samp{-link} options are used).  The
@samp{-ld-options-prelude} and @samp{-ld-options} options add the
specified options to the command that invokes the C linker (the
options in @var{ld-options-prelude} are passed to the C linker before
the input file and the options in @var{ld-options} are passed after).
The main use of this option is to specify additional object files or
libraries that need to be linked, or any C linker option that is
different from the default (such as the library search path and flags
to select between static and dynamic linking).  For example:

@smallexample
$ @b{gsc -ld-options "-L/usr/X11R6/lib -lX11 -dynamic" bench.scm}
@end smallexample

@opindex -warnings
The @samp{-warnings} option displays on standard output all warnings
that the compiler may have.

@opindex -verbose
The @samp{-verbose} option displays on standard output a trace of the
compiler's activity.

@opindex -report
The @samp{-report} option displays on standard output a global
variable usage report.  Each global variable used in the program is
listed with 4 flags that indicate whether the global variable is
defined, referenced, mutated and called.

@opindex -expansion
The @samp{-expansion} option displays on standard output the source code
after expansion and inlining by the front end.

@opindex -gvm
The @samp{-gvm} option generates a listing of the intermediate code
for the ``Gambit Virtual Machine'' (GVM) of each Scheme file on
@samp{@var{file}.gvm}.

@opindex -debug
@opindex debug
The @samp{-debug} option causes all kinds of debugging information to
be saved in the code generated.  See the documentation of the
@samp{debug} declaration for details.

@opindex -debug-location
@opindex debug-location
The @samp{-debug-location} option causes source code location
debugging information to be saved in the code generated.  See the
documentation of the @samp{debug-location} declaration for details.

@opindex -debug-source
@opindex debug-source
The @samp{-debug-source} option causes source code debugging
information to be saved in the code generated.  See the documentation
of the @samp{debug-source} declaration for details.

@opindex -debug-environments
@opindex debug-environments
The @samp{-debug-environments} option causes environment debugging
information to be saved in the code generated.  See the documentation
of the @samp{debug-environments} declaration for details.

@opindex -track-scheme
The @samp{-track-scheme} options causes the generation of @samp{#line}
directives that refer back to the Scheme source code.  This allows the
use of a C debugger or profiler to debug Scheme code.

@opindex -o @var{output}
The @samp{-o} option sets the filename of the output file, or the
directory in which the output file(s) generated by the compiler are
written.

@opindex -c
@opindex -dynamic
@opindex -exe
@opindex -obj
@opindex -link
@opindex -keep-c
@flindex @var{last}_.c
If the @samp{-link} or @samp{-exe} options appear on the command line,
the Gambit linker is invoked to generate the link file from the set of
C files specified on the command line or produced by the Gambit
compiler.  By default the link file is @samp{@var{last}_.c}, where
@samp{@var{last}.c} is the last file in the set of C files.  When the
@samp{-c} option is specified, the Scheme source files are compiled to
C files.  When the @samp{-exe} option is specified, the generated C
files and link file are compiled and linked using the C compiler to
produce an executable program whose name defaults to
@samp{@var{last}.exe}.  When the @samp{-obj} option is specified, the
generated C files are compiled using the C compiler to produce object
files (@samp{.o} or @samp{.obj} extensions).  If neither the
@samp{-link}, @samp{-c}, @samp{-exe}, @samp{-obj} options appear on
the command line, the Scheme source files are compiled to dynamically
loadable object files (@samp{.o@var{n}} extension).  The
@samp{-keep-c} option will prevent the deletion of any intermediate
@samp{.c} file that is generated.  Note that in this case the
intermediate @samp{.c} file will be generated in the same directory as
the Scheme source file even if the @samp{-o} option is used.

@opindex -flat
The @samp{-flat} option is only meaningful when a link file is being
generated (i.e. the @samp{-link} or @samp{-exe} options also appear on
the command line).  The @samp{-flat} option directs the Gambit linker
to generate a flat link file.  By default, the linker generates an
incremental link file (see the next section for a description of the
two types of link files).

@opindex -l @var{base}
The @samp{-l} option is only meaningful when an incremental link file
is being generated (i.e. the @samp{-link} or @samp{-exe} options
appear on the command line and the @samp{-flat} option is absent).
The @samp{-l} option specifies the link file (without the @samp{.c}
extension) of the base library to use for the incremental link.  By
default the link file of the Gambit runtime library is used
(i.e. @samp{~~lib/_gambc.c}).

@opindex -
The @samp{-} option starts a REPL interaction.

@opindex -e
The @samp{-e} option evaluates the specified expressions in the
interaction environment.

@node Link files, Procedures specific to compiler, GSC batch mode, GSC
@section Link files

Gambit can be used to create programs and libraries of Scheme
modules.  This section explains the steps required to do so and the role
played by the link files.

In general, a program is composed of a set of Scheme modules and C
modules.  Some of the modules are part of the Gambit runtime library and
the other modules are supplied by the user.  When the program is
started it must setup various global tables (including the symbol table
and the global variable table) and then sequentially execute the Scheme
modules (more or less as though they were being loaded one after another).
The information required for this is contained in one or more @dfn{link
files} generated by the Gambit linker from the C files produced by the
Gambit compiler.

The order of execution of the Scheme modules corresponds to the order of
the modules on the command line which produced the link file.  The order
is usually important because most modules define variables and
procedures which are used by other modules (for this reason the
program's main computation is normally started by the last module).

When a single link file is used to contain the linking information of
all the Scheme modules it is called a @dfn{flat link file}.  Thus a
program built with a flat link file contains in its link file both
information on the user modules and on the runtime library.  This is
fine if the program is to be statically linked but is wasteful in
a shared-library context because the linking information of the
runtime library can't be shared and will be duplicated in all
programs (this linking information typically takes hundreds of kilobytes).

Flat link files are mainly useful to bundle multiple Scheme modules to
make a runtime library (such as the Gambit runtime library) or to make a
single file that can be loaded with the @code{load} procedure.

An @dfn{incremental link file} contains only the linking information
that is not already contained in a second link file (the ``base'' link
file).  Assuming that a flat link file was produced when the runtime
library was linked, a program can be built by linking the user
modules with the runtime library's link file, producing an incremental
link file.  This allows the creation of a shared-library which
contains the modules of the runtime library and its flat link file.
The program is dynamically linked with this shared-library and
only contains the user modules and the incremental link file.  For
small programs this approach greatly reduces the size of the
program because the incremental link file is small.  A ``hello
world'' program built this way can be as small as 5 Kbytes.  Note that
it is perfectly fine to use an incremental link file for statically
linked programs (there is very little loss compared to a single flat
link file).

Incremental link files may be built from other incremental link files.
This allows the creation of shared-libraries which extend the
functionality of the Gambit runtime library.

@menu
* Building an executable program::  Building an executable program
* Building a loadable library::     Building a loadable library
* Building a shared-library::       Building a shared-library
* Other compilation options::       Other compilation options
@end menu

@node Building an executable program, Building a loadable library, Link files, Link files
@subsection Building an executable program

The simplest way to create an executable program is to invoke
@code{gsc} with the @samp{-exe} option.  The compiler will
transparently perform all the steps necessary, including compiling
Scheme source files to C files, generating the link file, compiling
the C files generated to object files, and creating the final
executable file using the C linker.  The following example shows how
to build the executable program @samp{hello.exe} which contains the
two Scheme modules @samp{h.scm} and @samp{w.six}.

@smallexample
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{cat w.six}
display("world"); newline();
$ @b{gsc -o hello.exe -exe h.scm w.six}
h.scm:
/Users/feeley/gambit/doc/h.c:
w.six:
/Users/feeley/gambit/doc/w.c:
/Users/feeley/gambit/doc/w_.c:
$ @b{./hello.exe}
hello
world
@end smallexample

The detailed steps which are performed can be viewed by setting the
@samp{GAMBC_CC_VERBOSE} environment variable to a nonnull value.  For
example:

@smallexample
$ @b{export GAMBC_CC_VERBOSE=yes}
$ @b{gsc -o hello.exe -exe h.scm w.six}
h.scm:
/Users/feeley/gambit/doc/h.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
 -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
 -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "h.o" h.c
w.six:
/Users/feeley/gambit/doc/w.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
 -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
 -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "w.o" w.c
/Users/feeley/gambit/doc/w_.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
 -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
 -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "w_.o" w_.c
gcc  -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
 -fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
 -fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include"
 -o "hello.exe" h.o w.o w_.o "/usr/local/Gambit-C/lib/libgambc.a"
@end smallexample

Using a single invocation of @code{gsc} with the @samp{-exe} option is
sometimes inappropriate when the build process is more complex, for
example when the program is composed of several seperately compiled
modules.  In such a case it is useful to decompose the build process
into smaller compilation steps.  The @samp{hello.exe} executable
program could have been built by seperating the generation of C files
from the C compilation and linking:

@smallexample
$ @b{gsc -c h.scm}
$ @b{gsc -c w.six}
$ @b{gsc -o hello.exe -exe h.c w.c}
@end smallexample

When even finer control is desired the build process can be decomposed
into smaller steps that invoke the C compiler and linker explicitly.
This is described in the rest of this section.

The @code{gsc} compiler can be invoked to compile each Scheme module
into a C file and to create an incremental link file.  The C files and
the link file must then be compiled with a C compiler and linked (at
the object file level) with the Gambit runtime library and possibly
other libraries (such as the math library and the dynamic loading
library).

Here is for example how a program with three modules (one in C and two
in Scheme) can be built.  The content of the three source files (@samp{m1.c},
@samp{m2.scm} and @samp{m3.scm}) is:

@smallexample
@b{}/* File: "m1.c" */
int power_of_2 (int x) @{ return 1<<x; @}

; File: "m2.scm"
(c-declare "extern int power_of_2 ();")
(define pow2 (c-lambda (int) int "power_of_2"))
(define (twice x) (cons x x))

; File: "m3.scm"
(write (map twice (map pow2 '(1 2 3 4)))) (newline)
@end smallexample

The compilation of the two Scheme source files can be done with
three invocations of @code{gsc}:

@smallexample
$ @b{gsc -c m2.scm        @r{@i{# create m2.c (note: .scm is optional)}}}
$ @b{gsc -c m3.scm        @r{@i{# create m3.c (note: .scm is optional)}}}
$ @b{gsc -link m2.c m3.c  @r{@i{# create the incremental link file m3_.c}}}
@end smallexample

Alternatively, the three invocations of @code{gsc} can be replaced by a
single invocation:

@smallexample
$ @b{gsc -link m2 m3}
m2:
m3:
@end smallexample

At this point there will be 4 C files: @samp{m1.c}, @samp{m2.c},
@samp{m3.c}, and @samp{m3_.c}.  To produce an executable program these
files must be compiled with a C compiler and linked with the Gambit-C
runtime library.  The C compiler options needed will depend on the C
compiler and the operating system (in particular it may be necessary
to add the options @samp{-I/usr/local/Gambit-C/include
-L/usr/local/Gambit-C/lib} to access the @samp{gambit.h} header file
and the Gambit-C runtime library).

Here is an example under Mac OS X:

@smallexample
$ @b{uname -srmp}
Darwin 8.1.0 Power Macintosh powerpc
$ @b{gsc -obj m1.c m2.c m3.c m3_.c}
m1.c:
m2.c:
m3.c:
m3_.c:
$ @b{gcc m1.o m2.o m3.o m3_.o -lgambc}
$ @b{./a.out}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample

Here is an example under Linux:

@smallexample
$ @b{uname -srmp}
Linux 2.6.8-1.521 i686 athlon
$ @b{gsc -obj m1.c m2.c m3.c m3_.c}
m1.c:
m2.c:
m3.c:
m3_.c:
$ @b{gcc m1.o m2.o m3.o m3_.o -lgambc -lm -ldl -lutil}
$ @b{./a.out}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample

@node Building a loadable library, Building a shared-library, Building an executable program, Link files
@subsection Building a loadable library

@opindex -D___DYNAMIC
To bundle multiple modules into a single object file that can be
dynamically loaded with the @code{load} procedure, a flat link file is
needed.  The compiler's @samp{-o} option must be used to name the C
file generated as follows.  If the dynamically loadable object file is
to be named @samp{@var{myfile}.o@var{n}} then the @samp{-o} option
must set the name of the link file generated to
@samp{@var{myfile}.o@var{n}.c} (note that the @samp{.c} extension
could also be @samp{.cc}, @samp{.cpp} or whatever extension is
appropriate for C/C++ source files).  The three modules of the
previous example can be bundled by generating a link file in this way:

@smallexample
$ @b{gsc -link -flat -o foo.o1.c m2 m3}
m2:
m3:
*** WARNING -- "cons" is not defined,
***            referenced in: ("m2.c")
*** WARNING -- "map" is not defined,
***            referenced in: ("m3.c")
*** WARNING -- "newline" is not defined,
***            referenced in: ("m3.c")
*** WARNING -- "write" is not defined,
***            referenced in: ("m3.c")
@end smallexample

The warnings indicate that there are no definitions (@code{define}s or
@code{set!}s) of the variables @code{cons}, @code{map}, @code{newline}
and @code{write} in the set of modules being linked.  Before
@samp{foo.o1} is loaded, these variables will have to be bound; either
implicitly (by the runtime library) or explicitly.

When compiling the C files and link file generated, the flag
@samp{-D___DYNAMIC} must be passed to the C compiler and the C
compiler and linker must be told to generate a dynamically loadable
shared library.

Here is an example under Mac OS X:

@smallexample
$ @b{uname -srmp}
Darwin 10.5.0 i386 i386
$ @b{gsc -link -flat -o foo.o1.c m2 m3 > /dev/null}
m2:
m3:
$ @b{gsc -cc-options "-D___DYNAMIC" -obj m1.c m2.c m3.c foo.o1.c}
m1.c:
m2.c:
m3.c:
foo.o1.c:
$ @b{gcc -bundle m1.o m2.o m3.o foo.o1.o -o foo.o1}
$ @b{gsi foo.o1}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample

Here is an example under Linux:

@smallexample
$ @b{uname -srmp}
Linux 2.6.8-1.521 i686 athlon
$ @b{gsc -link -flat -o foo.o1.c m2 m3 > /dev/null}
m2:
m3:
$ @b{gsc -cc-options "-D___DYNAMIC" -obj m1.c m2.c m3.c foo.o1.c}
m1.c:
m2.c:
m3.c:
foo.o1.c:
$ @b{gcc -shared m1.o m2.o m3.o foo.o1.o -o foo.o1}
$ @b{gsi foo.o1}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample

Here is a more complex example, under Solaris, which shows how to build
a loadable library @samp{mymod.o1} composed of the files @samp{m4.scm},
@samp{m5.scm} and @samp{x.c} that links to system shared libraries (for
X-windows):

@smallexample
$ @b{uname -srmp}
SunOS ungava 5.6 Generic_105181-05 sun4m sparc SUNW,SPARCstation-20
$ @b{gsc -link -flat -o mymod.o1.c m4 m5}
m4:
m5:
*** WARNING -- "*" is not defined,
***            referenced in: ("m4.c")
*** WARNING -- "+" is not defined,
***            referenced in: ("m5.c")
*** WARNING -- "display" is not defined,
***            referenced in: ("m5.c" "m4.c")
*** WARNING -- "newline" is not defined,
***            referenced in: ("m5.c" "m4.c")
*** WARNING -- "write" is not defined,
***            referenced in: ("m5.c")
$ @b{gsc -cc-options "-D___DYNAMIC" -obj m4.c m5.c x.c mymod.o1.c}
m4.c:
m5.c:
x.c:
mymod.o1.c:
$ @b{/usr/ccs/bin/ld -G -o mymod.o1 mymod.o1.o m4.o m5.o x.o -lX11 -lsocket}
$ @b{gsi mymod.o1}
hello from m4
hello from m5
(f1 10) = 22
$ @b{cat m4.scm}
(define (f1 x) (* 2 (f2 x)))
(display "hello from m4")
(newline)

(c-declare #<<c-declare-end
#include "x.h"
c-declare-end
)
(define x-initialize (c-lambda (char-string) bool "x_initialize"))
(define x-display-name (c-lambda () char-string "x_display_name"))
(define x-bell (c-lambda (int) void "x_bell"))
$ @b{cat m5.scm}
(define (f2 x) (+ x 1))
(display "hello from m5")
(newline)

(display "(f1 10) = ")
(write (f1 10))
(newline)

(x-initialize (x-display-name))
(x-bell 50) ; sound the bell at 50%
$ @b{cat x.c}
#include <X11/Xlib.h>

static Display *display;

int x_initialize (char *display_name)
@{
  display = XOpenDisplay (display_name);
  return display != NULL;
@}

char *x_display_name (void)
@{
  return XDisplayName (NULL);
@}

void x_bell (int volume)
@{
  XBell (display, volume);
  XFlush (display);
@}
$ @b{cat x.h}
int x_initialize (char *display_name);
char *x_display_name (void);
void x_bell (int);
@end smallexample

@node Building a shared-library, Other compilation options, Building a loadable library, Link files
@subsection Building a shared-library

@opindex -D___PRIMAL
@opindex -D___LIBRARY
@opindex -D___SHARED
A shared-library can be built using an incremental link file or a flat
link file.  An incremental link file is normally used when the Gambit
runtime library (or some other library) is to be extended with new
procedures.  A flat link file is mainly useful when building a
``primal'' runtime library, which is a library (such as the Gambit
runtime library) that does not extend another library.  When compiling
the C files and link file generated, the flags @samp{-D___LIBRARY} and
@samp{-D___SHARED} must be passed to the C compiler.  The flag
@samp{-D___PRIMAL} must also be passed to the C compiler when a primal
library is being built.

A shared-library @samp{mylib.so} containing the two first modules of
the previous example can be built this way:

@smallexample
$ @b{uname -srmp}
Linux bailey 1.2.13 #2 Wed Aug 28 16:29:41 GMT 1996 i586
$ @b{gsc -link -o mylib.c m2}
$ @b{gsc -obj -cc-options "-D___SHARED" m1.c m2.c mylib.c}
m1.c:
m2.c:
mylib.c:
$ @b{gcc -shared  m1.o m2.o mylib.o -o mylib.so}
@end smallexample

Note that this shared-library is built using an incremental link file
(it extends the Gambit runtime library with the procedures @code{pow2}
and @code{twice}).  This shared-library can in turn be used to build
an executable program from the third module of the previous example:

@smallexample
$ @b{gsc -link -l mylib m3}
$ @b{gsc -obj m3.c m3_.c}
m3.c:
m3_.c:
$ @b{gcc m3.o m3_.o mylib.so -lgambc}
$ @b{LD_LIBRARY_PATH=.:/usr/local/lib ./a.out}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample

@node Other compilation options, , Building a shared-library, Link files
@subsection Other compilation options

@opindex -D___SINGLE_HOST
@opindex -O
The performance of the code can be increased by passing the
@samp{-D___SINGLE_HOST} flag to the C compiler.  This will merge all
the procedures of a module into a single C procedure, which reduces
the cost of intra-module procedure calls.  In addition the @samp{-O}
option can be passed to the C compiler.  For large modules, it will
not be practical to specify both @samp{-O} and @samp{-D___SINGLE_HOST}
for typical C compilers because the compile time will be high and the
C compiler might even fail to compile the program for lack of memory.
It has been observed that lower levels of optimization (e.g. @samp{-O1})
often give faster compilation and also generate faster code.  It is
a good idea to experiment.

@opindex -I/usr/local/Gambit-C/include
@opindex -L/usr/local/Gambit-C/lib
Normally C compilers will not automatically search
@samp{/usr/local/Gambit-C/include} for header files so the flag
@samp{-I/usr/local/Gambit-C/include} should be passed to the C
compiler.  Similarly, C compilers/linkers will not automatically
search @samp{/usr/local/Gambit-C/lib} for libraries so the flag
@samp{-L/usr/local/Gambit-C/lib} should be passed to the C
compiler/linker.  Alternatives are given in @ref{Accessing the system
files}.

@opindex -shared
@opindex -call_shared
@opindex -rdynamic
@opindex -fpic
@opindex -fPIC
@opindex -Kpic
@opindex -KPIC
@opindex -pic
@opindex +z
@opindex -G
A variety of flags are needed by some C compilers when compiling a
shared-library or a dynamically loadable library.  Some of these flags
are: @samp{-shared}, @samp{-call_shared}, @samp{-rdynamic},
@samp{-fpic}, @samp{-fPIC}, @samp{-Kpic}, @samp{-KPIC}, @samp{-pic},
@samp{+z}, @samp{-G}.  Check your compiler's documentation to see
which flag you need.

@node Procedures specific to compiler, , Link files, GSC
@section Procedures specific to compiler

The Gambit Scheme compiler features the following procedures that
are not available in the Gambit Scheme interpreter.

@deffn procedure compile-file-to-target @var{file} @r{[}@code{options:} @var{options}@r{]} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{module-name:} @var{module-name}@r{]}
@pindex gsc

The @var{file} parameter must be a string naming an existing file
containing Scheme source code.  The extension can be omitted from
@var{file} when the Scheme file has a @samp{.scm} or @samp{.six}
extension.  This procedure compiles the source file into a file
containing C code.  By default, this file is named after @var{file}
with the extension replaced with @samp{.c}.  The name of the generated
file can be specified with the @var{output} parameter.  If
@var{output} is a string naming a directory then the C file is created
in that directory.  Otherwise the name of the C file is @var{output}.
The name of the generated module can be specified with the
@var{module-name} parameter.  If @var{module-name} is @code{#f} or is
not specified, then the name of the module is derived from the name of
the C file generated, without the extension.

Compilation options are specified through the @var{options} parameter
which must be a list of symbols.  Any combination of the following
options can be used: @samp{verbose}, @samp{report}, @samp{expansion},
@samp{gvm}, and @samp{debug}.

When the compilation is successful, @code{compile-file-to-target} returns
the name of the C file generated.  When there is a compilation error,
@code{#f} is returned.

@smallexample
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{gsc}
Gambit @value{VERSION}

> @b{(compile-file-to-target "h")}
"/Users/feeley/gambit/doc/h.c"
@end smallexample
@end deffn

@deffn procedure compile-file @var{file} @r{[}@code{options:} @var{options}@r{]} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{cc-options:} @var{cc-options}@r{]} @r{[}@code{ld-options-prelude:} @var{ld-options-prelude}@r{]} @r{[}@code{ld-options:} @var{ld-options}@r{]}
@pindex gsc
@findex load
@cindex object file

The @var{file}, @var{options}, and @var{output} parameters have the
same meaning as for the @code{compile-file-to-target} procedure, except that
@var{file} may be a Scheme source file or a
C file possibly generated by the Gambit Scheme compiler (for example
with the @code{compile-file-to-target} procedure).  The
@var{cc-options} parameter is a string containing the options to pass
to the C compiler and the @var{ld-options-prelude} and
@var{ld-options} parameters are strings containing the options to pass
to the C linker (the options in @var{ld-options-prelude} are passed to
the C linker before the input file and the options in @var{ld-options}
are passed after).

The @code{compile-file} procedure compiles the source file @var{file}
into an object file, which is either a file dynamically loadable using
the @code{load} procedure, or a C linkable object file destined to be
linked with the C linker (for example to create a standalone
executable program).  The presence of the
@code{obj} option in @var{options} will cause the creation of a C
linkable object file and therefore the options
@var{ld-options-prelude} and @var{ld-options} are ignored, otherwise a
dynamically loadable file is created.  In both cases, if @var{file} is
a Scheme source file, the compiler first compiles @var{file} to a C
file which is created in the same directory as @var{file} regardless
of the @var{output} parameter.  Then the C file is compiled with the C
compiler.

When the compilation is successful, @code{compile-file} returns the
name of the object file generated.  When there is a compilation error,
@code{#f} is returned.

The name of the object file can be specified with the @var{output}
parameter.  If @var{output} is a string naming a directory then the
object file is created in that directory.  Otherwise the name of the
object file is @var{output}.

In the case of a dynamically loadable object file, by default the
object file is named after @var{file} with the extension replaced with
@samp{.o@var{n}}, where @var{n} is a positive integer that acts as a
version number.  The next available version number is generated
automatically by @code{compile-file}.

When dynamically loaded object files are loaded using the @code{load}
procedure, the @samp{.o@var{n}} extension can be specified (to select
a particular version) or omitted (to load the file with a
@samp{.o@var{n}} extension with the highest @var{n} consecutively from
1).  When the @samp{.o@var{n}} extension is not specified and older
versions are no longer needed, all versions must be deleted and the
compilation must be repeated (this is necessary because the file name,
including the extension, is used to name some of the exported symbols
of the object file).

Note that dynamically loadable object files can only be generated on
host operating systems that support dynamic loading.

@smallexample
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{gsc}
Gambit @value{VERSION}

> @b{(compile-file "h")}
"/Users/feeley/gambit/doc/h.o1"
> @b{(load "h")}
hello
"/Users/feeley/gambit/doc/h.o1"
> @b{(compile-file-to-target "h" output: "h.o99.c")}
"/Users/feeley/gambit/doc/h.o99.c"
> @b{(compile-file "h.o99.c")}
"/Users/feeley/gambit/doc/h.o99"
> @b{(load "h.o99")}
hello
"/Users/feeley/gambit/doc/h.o99"
> @b{(compile-file-to-target "h")}
"/Users/feeley/gambit/doc/h.c"
> @b{(compile-file "h.c" options: '(obj))}
"/Users/feeley/gambit/doc/h.o"
@end smallexample

@end deffn

@deffn procedure link-incremental @var{module-list} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{base:} @var{base}@r{]} @r{[}@code{warnings?:} @var{warnings?}@r{]}
@pindex gsc

The first parameter must be a non empty list of strings naming Scheme
modules to link (the file extension may be omitted).  An incremental link
file is generated for the modules specified in @var{module-list}.  By
default the link file generated is named @samp{@var{last}_.c}, where
@var{last} is the name of the last module, without the file extension.
The name of the generated
link file can be specified with the @var{output} parameter.  If
@var{output} is a string naming a directory then the link file is
created in that directory.  Otherwise the name of the link file is
@var{output}.

The base link file is specified by the @var{base} parameter, which
must be a string.  By default the base link file is the Gambit runtime
library link file @samp{~~lib/_gambc.c}.  However, when @var{base} is
supplied it is the name of the base link file (the file extension
may be omitted).

The @var{warnings?} parameter controls whether warnings are
generated for undefined references.

The following example shows how to build the executable program
@samp{hello} which contains the two Scheme modules @samp{h.scm} and
@samp{w.six}.

@smallexample
$ @b{uname -srmp}
Darwin 8.1.0 Power Macintosh powerpc
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{cat w.six}
display("world"); newline();
$ @b{gsc}
Gambit @value{VERSION}

> @b{(compile-file-to-target "h")}
"/Users/feeley/gambit/doc/h.c"
> @b{(compile-file-to-target "w")}
"/Users/feeley/gambit/doc/w.c"
> @b{(link-incremental '("h" "w") output: "hello.c")}
"/Users/feeley/gambit/doc/hello_.c"
> @b{,q}
$ @b{gsc -obj h.c w.c hello.c}
h.c:
w.c:
hello.c:
$ @b{gcc h.o w.o hello.o -lgambc -o hello}
$ @b{./hello}
hello
world
@end smallexample

@end deffn

@deffn procedure link-flat @var{module-list} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{warnings?:} @var{warnings?}@r{]}
@pindex gsc

The first parameter must be a non empty list of strings naming Scheme
modules to link (the file extension may be omitted).  The first string
must be the name of a Scheme module
or the name of a link file and the remaining strings must name Scheme
modules.  A flat link file
is generated for the modules specified in @var{module-list}.  By
default the link file generated is named @samp{@var{last}_.c}, where
@var{last} is the name of the last module.  The name of the generated
link file can be specified with the @var{output} parameter.  If
@var{output} is a string naming a directory then the link file is
created in that directory.  Otherwise the name of the link file is
@var{output}.  If a dynamically loadable object file is produced from
the link file @samp{@var{output}}, then the name of the dynamically
loadable object file must be @samp{@var{output}} stripped of its file
extension.

The @var{warnings?} parameter controls whether warnings are
generated for undefined references.

The following example shows how to build the dynamically loadable object
file @samp{lib.o1} which contains the two Scheme modules
@samp{m6.scm} and @samp{m7.scm}.

@smallexample
$ @b{uname -srmp}
Darwin 8.1.0 Power Macintosh powerpc
$ @b{cat m6.scm}
(define (f x) (g (* x x)))
$ @b{cat m7.scm}
(define (g y) (+ n y))
$ @b{gsc}
Gambit @value{VERSION}

> @b{(compile-file-to-target "m6")}
"/Users/feeley/gambit/doc/m6.c"
> @b{(compile-file-to-target "m7")}
"/Users/feeley/gambit/doc/m7.c"
> @b{(link-flat '("m6" "m7") output: "lib.o1.c")}
*** WARNING -- "*" is not defined,
***            referenced in: ("m6.c")
*** WARNING -- "+" is not defined,
***            referenced in: ("m7.c")
*** WARNING -- "n" is not defined,
***            referenced in: ("m7.c")
"/Users/feeley/gambit/doc/lib.o1.c"
> @b{,q}
$ @b{gcc -bundle -D___DYNAMIC m6.c m7.c lib.o1.c -o lib.o1}
$ @b{gsc}
Gambit @value{VERSION}

> @b{(load "lib")}
*** WARNING -- Variable "n" used in module "m7" is undefined
"/Users/feeley/gambit/doc/lib.o1"
> @b{(define n 10)}
> @b{(f 5)}
35
> @b{,q}
@end smallexample

The warnings indicate that there are no definitions (@code{define}s or
@code{set!}s) of the variables @code{*}, @code{+} and @code{n} in the
modules contained in the library.  Before the library is used, these
variables will have to be bound; either implicitly (by the runtime
library) or explicitly.

@end deffn

@node Runtime options, Debugging, GSC, Top
@chapter Runtime options
@cindex runtime options
@cindex options, runtime

@pindex gsc
@pindex gsi
Both @code{gsi} and @code{gsc} as well as executable programs compiled
and linked using @code{gsc} take a @samp{-:} option which supplies
parameters to the runtime system.  This option must appear first on
the command line.  The colon is followed by a comma separated list of
options with no intervening spaces.  The available options are:

@table @code
@item m@var{HEAPSIZE}
Set minimum heap size in kilobytes.
@item h@var{HEAPSIZE}
Set maximum heap size in kilobytes.
@item l@var{LIVEPERCENT}
Set heap occupation after garbage collection.
@item s
Select standard Scheme mode.
@item S
Select Gambit Scheme mode.
@item d@r{[}@var{OPT}...@r{]}
Set debugging options.
@item @@@r{[}@var{INTF}@r{]}@r{[}:@var{PORT}@r{]}
Override the configuration of the main RPC server.
@item =@var{DIRECTORY}
Override the central installation directory.
@item ~~@var{DIR}=@var{DIRECTORY}
Override the @var{DIR} installation directory.
@item +@var{ARGUMENT}
Add @var{ARGUMENT} to the command line before other arguments.
@item f@r{[}@var{OPT}...@r{]}
Set file options.
@item t@r{[}@var{OPT}...@r{]}
Set terminal options.
@item -@r{[}@var{OPT}...@r{]}
Set standard input and output options.
@end table

@opindex -:m
The @samp{m} option specifies the minimum size of the heap.  The
@samp{m} is immediately followed by an integer indicating the number
of kilobytes of memory.  The heap will not shrink lower than this
size.  By default, the minimum size is 0.

@opindex -:h
The @samp{h} option specifies the maximum size of the heap.  The
@samp{h} is immediately followed by an integer indicating the number
of kilobytes of memory.  The heap will not grow larger than this size.
By default, there is no limit (i.e.  the heap will grow until the
virtual memory is exhausted).

@opindex -:l
The @samp{l} option specifies the percentage of the heap that will be
occupied with live objects after the heap is resized at the end of a
garbage collection.  The @samp{l} is immediately followed by an
integer between 1 and 100 inclusively indicating the desired
percentage.  The garbage collector resizes the heap to reach this
percentage occupation.  By default, the percentage is 50.

@opindex -:s
@opindex -:S
The @samp{s} option selects standard Scheme mode.  In this mode the
reader is case-insensitive and keywords are not recognized.  The
@samp{S} option selects Gambit Scheme mode (the reader is case-sensitive
and recognizes keywords which end with a colon).  By default Gambit
Scheme mode is used.

@opindex -:d
The @samp{d} option sets various debugging options.  The letter
@samp{d} is followed by a sequence of letters indicating suboptions.

@table @code

@item p
@opindex -:dp
Uncaught exceptions will be treated as ``errors'' in the primordial thread
only.

@item a
@opindex -:da
Uncaught exceptions will be treated as ``errors'' in all threads.

@item r
@opindex -:dr
When an ``error'' occurs a new REPL will be started.

@item s
@opindex -:ds
When an ``error'' occurs a new REPL will be started.
Moreover the program starts in single-stepping mode.

@item q
@opindex -:dq
When an ``error'' occurs the program will terminate with a nonzero
exit status.

@item R
@opindex -:dR
@kindex ^C
When a user interrupt occurs a new REPL will be started.  User
interrupts are typically obtained by typing @key{^C}.  Note that with
some system configurations @key{^C} abruptly terminates the process.
For example, under Microsoft Windows, @key{^C} works fine with the
standard console but with the MSYS terminal window it terminates the
process.

@item D
@opindex -:dD
When a user interrupt occurs it will be deferred until the parameter
@code{current-user-interrupt-handler} is bound.

@item Q
@opindex -:dQ
When a user interrupt occurs the program will terminate with a nonzero
exit status.

@item @var{LEVEL}
@opindex -:d@var{LEVEL}
The verbosity level is set to @var{LEVEL} (a digit from 0 to 9).
At level 0 the runtime system will not display error messages
and warnings.

@item i
@opindex -:di
The REPL interaction channel will be the IDE REPL window (if the IDE
is available).

@item c
@opindex -:dc
The REPL interaction channel will be the console.

@item -
@opindex -:d-
The REPL interaction channel will be standard input and standard output.

@item @@@r{[}@var{HOST}@r{]}@r{[}:@var{PORT}@r{]}
@opindex -:d@@@r{[}@var{HOST}@r{]}@r{[}:@var{PORT}@r{]}
The REPL interaction channel will be connected to the remote debugger
at address @var{HOST}:@var{PORT} (if there is a remote debugger at
that address).  The default @var{HOST} is 127.0.0.1 and the default
@var{PORT} is 44555.
THIS OPTION IS NOT YET IMPLEMENTED!

@end table

The default debugging options are equivalent to @code{-:dpqQ1i}
(i.e. an uncaught exception in the primordial thread terminates the
program after displaying an error message).  When the letter @samp{d}
is not followed by suboptions, it is equivalent to @code{-:dprR1i}
(i.e. a new REPL is started only when an uncaught exception occurs in
the primordial thread).  When @code{gsi} and @code{gsc} are running
the main REPL, the debugging options are changed to cause errors in
the primordial thread and user interrupts to start a nested REPL.

@opindex -:@
The @samp{@@@r{[}@var{INTF}@r{]}@r{[}:@var{PORT}@r{]}} option
overrides the configuration of the main RPC server.  The default
@var{INTF} is 127.0.0.1 and the default @var{PORT} is 44556.
THIS OPTION IS NOT YET IMPLEMENTED!

@opindex -:=
The @samp{=@var{DIRECTORY}} option overrides the setting of the
central installation directory.

@opindex -:~~
The @samp{~~@var{DIR}=@var{DIRECTORY}} option overrides the setting of
the @var{DIR} installation directory.

@opindex -:+
The @samp{+} option adds the text that follows to the command line
before other arguments.

@opindex -:f
@opindex -:t
@opindex -:-
The @samp{f}, @samp{t} and @samp{-} options specify the default
settings of the ports created for files, terminals and standard input
and output respectively.  The default character encoding, end-of-line
encoding and buffering can be set.  Moreover, for terminals the
line-editing feature can be enabled or disabled.  The @samp{f},
@samp{t} and @samp{-} must be followed by a sequence of these options:

@table @code
@item A
ASCII character encoding.
@item 1
ISO-8859-1 character encoding.
@item 2
UCS-2 character encoding.
@item 4
UCS-4 character encoding.
@item 6
UTF-16 character encoding.
@item 8
UTF-8 character encoding.
@item U
UTF character encoding with fallback to UTF-8 on input if no BOM is present.
@item UA
UTF character encoding with fallback to ASCII on input if no BOM is present.
@item U1
UTF character encoding with fallback to ISO-8859-1 on input if no BOM is present.
@item U6
UTF character encoding with fallback to UTF-16 on input if no BOM is present.
@item U8
UTF character encoding with fallback to UTF-8 on input if no BOM is present.
@item c
End-of-line is encoded as CR (carriage-return).
@item l
End-of-line is encoded as LF (linefeed)
@item cl
End-of-line is encoded as CR-LF.
@item u
Unbuffered I/O.
@item n
Line buffered I/O (@samp{n} for ``at newline'').
@item f
Fully buffered I/O.
@item r
Illegal character encoding is treated as an error (exception raised).
@item R
Silently replace illegal character encodings with Unicode character #xfffd
(replacement character).
@item e
Enable line-editing (applies to terminals only).
@item E
Disable line-editing (applies to terminals only).
@end table

@opindex -::
@cindex GAMBCOPT, environment variable
When a program's execution starts, the runtime system obtains the
runtime options by processing in turn various sources of runtime options:
the defaults, the environment variable @samp{GAMBCOPT}, the script
line of the source code, and, unless the program is an interpreted
script, the first command line argument of the
program.  Any runtime option can be overriden by a subsequent source
of runtime options.  It is sometimes useful to prevent overriding
the runtime options of the script line.  This can be achieved by
starting the script line runtime options with @samp{-::}.  In
this case the environment variable @samp{GAMBCOPT} is ignored,
and the first command line argument of the program is
not used for runtime options (it is treated like a normal
command line argument even if it starts with @samp{-:}).

For example:

@smallexample
$ @b{GAMBCOPT=d0,=~/my-gambit2}
$ @b{export GAMBCOPT}
$ @b{gsi -e '(pretty-print (path-expand "~~")) (/ 1 0)'}
"/Users/feeley/my-gambit2/"
$ @b{echo $?}
70
$ @b{gsi -:d1 -e '(pretty-print (path-expand "~~")) (/ 1 0)'}
"/Users/feeley/my-gambit2/"
*** ERROR IN (string)@@1.3 -- Divide by zero
(/ 1 0)
@end smallexample

@node Debugging, Scheme extensions, Runtime options, Top
@chapter Debugging

@menu
* Debugging model::                 Debugging model
* Debugging commands::              Debugging commands
* Debugging example::               Debugging example
* Procedures related to debugging:: Procedures related to debugging
* Console line-editing::            Console line-editing
* Emacs interface::                 Emacs interface
* GUIDE::                           GUIDE
@end menu

@node Debugging model, Debugging commands, Debugging, Debugging
@section Debugging model

The evaluation of an expression may stop before it is completed for the
following reasons:

@enumerate a
@item An evaluation error has occured, such as attempting to
divide by zero.

@kindex ^C
@item The user has interrupted the evaluation (usually by typing @key{^C}).

@item A breakpoint has been reached or @code{(step)} was evaluated.

@item Single-stepping mode is enabled.

@end enumerate

When an evaluation stops, a message is displayed indicating the reason
and location where the evaluation was stopped.  The location
information includes, if known, the name of the procedure where the
evaluation was stopped and the source code location in the format
@samp{@var{stream}@@@var{line}.@var{column}}, where @var{stream} is
either a string naming a file or a symbol within parentheses, such as
@samp{(console)}.

A @dfn{nested REPL} is then initiated in the context of the point of
execution where the evaluation was stopped.  The nested REPL's
continuation and evaluation environment are the same as the point where
the evaluation was stopped.  For example when evaluating the expression
@samp{(let ((y (- 1 1))) (* (/ x y) 2))}, a ``divide by zero'' error is
reported and the nested REPL's continuation is the one that takes the
result and multiplies it by two.  The REPL's lexical environment
includes the lexical variable @samp{y}.  This allows the inspection of
the evaluation context (i.e. the lexical and dynamic environments and
continuation), which is particularly useful to determine the exact
location and cause of an error.

@kindex ^D
The prompt of nested REPLs includes the nesting level; @samp{1>} is the
prompt at the first nesting level, @samp{2>} at the second nesting
level, and so on.  An end of file (usually @key{^D}) will cause the
current REPL to be terminated and the enclosing REPL (one nesting level
less) to be resumed.

At any time the user can examine the frames in the REPL's
continuation, which is useful to determine which chain of procedure
calls lead to an error.  A backtrace that lists the chain of active
continuation frames in the REPL's continuation can be obtained with
the @samp{,b} command.  The frames are numbered from 0, that is frame
0 is the most recent frame of the continuation where execution
stopped, frame 1 is the parent frame of frame 0, and so on.  It is
also possible to move the REPL to a specific parent continuation
(i.e. a specific frame of the continuation where execution stopped)
with the @samp{,@var{N}}, @samp{,@var{N}+}, @samp{,@var{N}-},
@samp{,+}, @samp{,-}, @samp{,++}, and @samp{,--} commands.  When the
frame number of the frame being examined is not zero, it is shown in
the prompt after the nesting level, for example @samp{1\5>} is the
prompt when the REPL nesting level is 1 and the frame number is 5.

Expressions entered at a nested REPL are evaluated in the environment
(both lexical and dynamic) of the continuation frame currently being
examined if that frame was created by interpreted Scheme code.  If the
frame was created by compiled Scheme code then expressions get evaluated
in the global interaction environment.  This feature may be used in
interpreted code to fetch the value of a variable in the current frame
or to change its value with @code{set!}.  Note that some special forms
(@code{define} in particular) can only be evaluated in the global
interaction environment.

@node Debugging commands, Debugging example, Debugging model, Debugging
@section Debugging commands

In addition to expressions, the REPL accepts the following special
``comma'' commands:

@table @code
@item ,?
@cmindex ,?
Give a summary of the REPL commands.

@item ,(h @var{subject})
@cmindex ,(h @var{subject})
This command will show the section of the Gambit manual with the
definition of the procedure or special form @var{subject}, which must
be a symbol.  For example @samp{,(h time)} will show the section
documenting the @code{time} special form.  Please see the @code{help}
procedure for additional information.

@item ,h
@cmindex ,h
This command will show the section of the Gambit manual with the
definition of the procedure which raised the exception for which this
REPL was started.

@item ,q
@cmindex ,q
Terminate the process with exit status 0.  This is equivalent to
calling @code{(exit 0)}.

@item ,qt
@cmindex ,qt
Terminate the current thread (note that terminating the primordial
thread terminates the process).

@item ,t
@cmindex ,t
Return to the outermost REPL, also known as the ``top-level REPL''.

@item ,d
@cmindex ,d
Leave the current REPL and resume the enclosing REPL.  This command does
nothing in the top-level REPL.

@item ,(c @var{expr})
@cmindex ,(c @var{expr})
Leave the current REPL and continue the computation that initiated the
REPL with a specific value.  This command can only be used to continue
a computation that signaled an error.  The expression @var{expr} is
evaluated in the current context and the resulting value is returned
as the value of the expression which signaled the error.  For example,
if the evaluation of the expression @samp{(* (/ x y) 2)} signaled an
error because @samp{y} is zero, then in the nested REPL a @samp{,(c (+
4 y))} will resume the computation of @samp{(* (/ x y) 2)} as though
the value of @samp{(/ x y)} was 4.  This command must be used
carefully because the context where the error occured may rely on the
result being of a particular type.  For instance a @samp{,(c #f)} in
the previous example will cause @samp{*} to signal a type error (this
problem is the most troublesome when debugging Scheme code that was
compiled with type checking turned off so be careful).

@item ,c
@cmindex ,c
Leave the current REPL and continue the computation that initiated the
REPL.  This command can only be used to continue a computation that was
stopped due to a user interrupt, breakpoint or a single-step.

@item ,s
@cmindex ,s
Leave the current REPL and continue the computation that initiated the
REPL in single-stepping mode.  The computation will perform an
evaluation step (as defined by @code{step-level-set!}) and then stop,
causing a nested REPL to be entered.  Just before the evaluation step is
performed, a line is displayed (in the same format as @code{trace})
which indicates the expression that is being evaluated.  If the
evaluation step produces a result, the result is also displayed on
another line.  A nested REPL is then entered after displaying a message
which describes the next step of the computation.  This command can
only be used to continue a computation that was stopped due to a user
interrupt, breakpoint or a single-step.

@item ,l
@cmindex ,l
This command is similar to @samp{,s} except that it ``leaps'' over
procedure calls, that is procedure calls are treated like a single step.
Single-stepping mode will resume when the procedure call returns, or if
and when the execution of the called procedure encounters a breakpoint.

@item ,@var{N}
@cmindex ,@var{N}
Move to frame number @var{N} of the continuation.  After changing the
current frame, a one-line summary of the frame is displayed as if the
@samp{,y} command was entered.

@item ,@var{N}+
@cmindex ,@var{N}+
Move forward by @var{N} frames in the chain of continuation frames
(i.e.  towards older continuation frames).  After changing the current
frame, a one-line summary of the frame is displayed as if the
@samp{,y} command was entered.

@item ,@var{N}-
@cmindex ,@var{N}-
Move backward by @var{N} frames in the chain of continuation frames
(i.e.  towards more recent continuation frames).  After changing the
current frame, a one-line summary of the frame is displayed as if the
@samp{,y} command was entered.

@item ,+
@cmindex ,+
Equivalent to @samp{,1+}.

@item ,-
@cmindex ,-
Equivalent to @samp{,1-}.

@item ,++
@cmindex ,++
Equivalent to @samp{,@var{N}+} where @var{N} is the number of
continuation frames displayed at the head of a backtrace.

@item ,--
@cmindex ,--
Equivalent to @samp{,@var{N}-} where @var{N} is the number of
continuation frames displayed at the head of a backtrace.

@item ,y
@cmindex ,y
Display a one-line summary of the current frame.  The information is
displayed in four fields.  The first field is the frame number.  The
second field is the procedure that created the frame or
@samp{(interaction)} if the frame was created by an expression entered
at the REPL.  The remaining fields describe the subproblem associated
with the frame, that is the expression whose value is being computed.
The third field is the location of the subproblem's source code and
the fourth field is a reproduction of the source code, possibly
truncated to fit on the line.  The last two fields may be missing if
that information is not available.  In particular, the third field is
missing when the frame was created by a user call to the @samp{eval}
procedure or by a compiled procedure not compiled with the declaration
@samp{debug-location}, and the last field is missing when the frame
was created by a compiled procedure not compiled with the declaration
@samp{debug-source}.

@item ,b
@cmindex ,b
Display a backtrace summarizing each frame in the chain of continuation
frames starting with the current frame.  For each frame, the same
information as for the @samp{,y} command is displayed (except that
location information is displayed in the format
@samp{@var{stream}@@@var{line}:@var{column}}).  If there are more than 15
frames in the chain of continuation frames, some of the middle frames
will be omitted.

@item ,be
@cmindex ,be
Like the @samp{,b} command but also display the environment.

@item ,bed
@cmindex ,bed
Like the @samp{,be} command but also display the dynamic environment.

@item ,(b @var{expr})
@cmindex ,(b @var{expr})
Display the backtrace of @var{expr}'s value, @var{X}, which is
obtained by evaluating @var{expr} in the current frame.  @var{X} must
be a continuation or a thread.  When @var{X} is a continuation, the
frames in that continuation are displayed.  When @var{X} is a thread,
the backtrace of the current continuation of that thread is displayed.

@item ,(be @var{expr})
@cmindex ,(be @var{expr})
Like the @samp{,(b @var{expr})} command but also display the
environment.

@item ,(bed @var{expr})
@cmindex ,(bed @var{expr})
Like the @samp{,(be @var{expr})} command but also display the dynamic
environment.

@item ,i
@cmindex ,i
Pretty print the procedure that created the current frame or
@samp{(interaction)} if the frame was created by an expression entered
at the REPL.  Compiled procedures will only be pretty printed when
they are compiled with the declaration @samp{debug-source}.

@item ,e
@cmindex ,e
Display the environment which is accessible from the current frame.
The lexical environment is displayed, followed by the dynamic
environment if the parameter object
@code{repl-display-dynamic-environment?} is not false.  Global lexical
variables are not displayed.  Moreover the frame must have been
created by interpreted code or code compiled with the declaration
@samp{debug-environments}.  Due to space safety
considerations and compiler optimizations, some of the lexical
variable bindings may be missing.  Lexical variable bindings are
displayed using the format @samp{@var{variable} = @var{expression}}
(when @var{variable} is mutable) or @samp{@var{variable} == @var{expression}}
(when @var{variable} is immutable, which may happen in compiled code
due to compiler optimization)
and dynamically-bound parameter bindings are displayed using the
format @samp{(@var{parameter}) = @var{expression}}.  Note that
@var{expression} can be a self-evaluating expression (number, string,
boolean, character, ...), a quoted expression, a lambda expression or
a global variable (the last two cases, which are only used when the
value of the variable or parameter is a procedure, simplifies the
debugging of higher-order procedures).  A @var{parameter} can be a
quoted expression or a global variable.  Lexical bindings are
displayed in inverse binding order (most deeply nested first) and
shadowed variables are included in the list.

@item ,ed
@cmindex ,ed
Like the @samp{,e} command but the dynamic environment is always
displayed.

@item ,(e @var{expr})
@cmindex ,(e @var{expr})
Display the environment of @var{expr}'s value, @var{X}, which is
obtained by evaluating @var{expr} in the current frame.  @var{X} must
be a continuation, a thread, a procedure, or a nonnegative integer.
When @var{X} is a continuation, the environment at that point in the
code is displayed.  When @var{X} is a thread, the environment of the
current continuation of that thread is displayed. When @var{X} is a
procedure, the lexical environment where @var{X} was created is
combined with the current continuation and this combined environment
is displayed.  When @var{X} is an integer, the environment at frame
number @var{X} of the continuation is displayed.

@item ,(ed @var{expr})
@cmindex ,(ed @var{expr})
Like the @samp{,(e @var{expr})} command but the dynamic environment is
always displayed.

@item ,st
@cmindex ,st
Display the state of the threads in the current thread's thread group.
A thread can be: uninitialized, initialized, active, and
terminated (normally or abnormally).  Active threads can be
running, sleeping and waiting on a synchronization object
(mutex, condition variable or port) possibly with a timeout.

@item ,(st @var{expr})
@cmindex ,(st @var{expr})
Display the state of a specific thread or thread group.
The value of @var{expr} must be a thread or thread group.

@item ,(v @var{expr})
@cmindex ,(v @var{expr})
Start a new REPL visiting @var{expr}'s value, @var{X}, which is
obtained by evaluating @var{expr} in the current frame.  @var{X} must
be a continuation, a thread, a procedure, or a nonnegative integer.
When @var{X} is a continuation, the new REPL's continuation is @var{X}
and evaluations are done in the environment at that point in the code.
When @var{X} is a thread, the thread is interrupted and the new REPL's
continuation is the point where the thread was interrupted.  When
@var{X} is a procedure, the lexical environment where @var{X} was
created is combined with the current continuation and evaluations are
done in this combined environment.  When @var{X} is an integer, the
REPL is started in frame number @var{X} of the continuation.

@end table

@node Debugging example, Procedures related to debugging, Debugging commands, Debugging
@section Debugging example

Here is a sample interaction with @code{gsi}:

@smallexample
$ @b{gsi}
Gambit @value{VERSION}

> @b{(define (invsqr x) (/ 1 (expt x 2)))}
> @b{(define (mymap fn lst)
    (define (mm in)
      (if (null? in)
          '()
          (cons (fn (car in)) (mm (cdr in)))))
    (mm lst))}
> @b{(mymap invsqr '(5 2 hello 9 1))}
*** ERROR IN invsqr, (console)@@1.25 -- (Argument 1) NUMBER expected
(expt 'hello 2)
1> @b{,i}
#<procedure #2 invsqr> =
(lambda (x) (/ 1 (expt x 2)))
1> @b{,e}
x = 'hello
1> @b{,b}
0  invsqr                    (console)@@1:25          (expt x 2)
1  #<procedure #4>           (console)@@6:17          (fn (car in))
2  #<procedure #4>           (console)@@6:31          (mm (cdr in))
3  #<procedure #4>           (console)@@6:31          (mm (cdr in))
4  (interaction)             (console)@@8:1           (mymap invsqr '(5 2 hel...
1> @b{,+}
1  #<procedure #4>           (console)@@6.17          (fn (car in))
1\1> @b{(pp #4)}
(lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
1\1> @b{,e}
in = '(hello 9 1)
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\1> @b{,(e mm)}
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\1> @b{fn}
#<procedure #2 invsqr>
1\1> @b{(pp fn)}
(lambda (x) (/ 1 (expt x 2)))
1\1> @b{,+}
2  #<procedure #4>           (console)@@6.31          (mm (cdr in))
1\2> @b{,e}
in = '(2 hello 9 1)
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\2> @b{,(c (list 3 4 5))}
(1/25 1/4 3 4 5)
> @b{,q}
@end smallexample

@node Procedures related to debugging, Console line-editing, Debugging example, Debugging
@section Procedures related to debugging

@deffn procedure help @var{subject}
@deffnx procedure help-browser @r{[}@var{new-value}@r{]}

The @code{help} procedure displays the section of the Gambit manual
with the definition of the procedure or special form @var{subject},
which must be a procedure or symbol.  For example the call @code{(help
gensym)} will show the section documenting the @code{gensym} procedure
and the call @code{(help 'time)} will show the section documenting the
@code{time} special form.  The @code{help} procedure returns the void
object.

The parameter object @code{help-browser} is bound to a string naming
the external program that is used by the @code{help} procedure to view
the documentation.  Initially it is bound to the empty string.  In
normal circumstances when @code{help-browser} is bound to an empty
string the @code{help} procedure runs the script
@code{~~bin/gambc-doc.bat} which searches for a suitable web browser
to open the documentation in HTML format.  Unless the system was built
with the command @samp{configure --enable-help-browser=...}, the
text-only browser @samp{lynx} (see @uref{http://lynx.isc.org/}) will
be used by default if it is available.  We highly recommend that you
install this browser if you are interested in viewing the
documentation within the console in which the REPL is running.  You
can exit @samp{lynx} conveniently by typing an end of file (usually
@key{^D}).

For example:

@smallexample
> @b{(help-browser "firefox")} @r{@i{; use firefox instead of lynx}}
> @b{(help 'gensym)}
> @b{(help gensym)} @r{@i{; OK because gensym is a procedure}}
> @b{(help 'time)}
> @b{(help time)} @r{@i{; not OK because time is a special form}}
*** ERROR IN (console)@@5.7 -- Macro name can't be used as a variable: time
> 
@end smallexample

@end deffn

@deffn procedure repl-result-history-ref @var{i}
@deffnx procedure repl-result-history-max-length-set! @var{n}

@cindex #
@cindex ##
The REPL keeps a history of the last few results printed by the
REPL. The call @code{(repl-result-history-ref @var{i})} returns the
@var{i}th previous result (the last for @var{i}=0, the next to last
for @var{i}=1, etc).  By default the REPL result history remembers up
to 3 results.  The maximal length of the history can be set to @var{n}
between 0 and 10 by a call to
@code{(repl-result-history-max-length-set! @var{n})}.

For convenience the reader defines an abbreviation for calling
@code{repl-result-history-ref}.  Tokens formed by a sequence of one or
more hash signs, such as @samp{@code{#}}, @samp{@code{##}}, etc, are
expanded by the reader into the list @code{(repl-result-history-ref
@var{i})}, where @var{i} is the number of hash signs minus 1.  In
other words, @samp{@code{#}} will return the last result printed by
the REPL, @samp{@code{##}} will return the next to last, etc.

For example:

@smallexample
> @b{(map (lambda (x) (* x x)) '(1 2 3))}
(1 4 9)
> @b{(reverse #)}
(9 4 1)
> @b{(append # ##)}
(9 4 1 1 4 9)
> @b{1}
1
> @b{1}
1
> @b{(+ # ##)}
2
> @b{(+ # ##)}
3
> @b{(+ # ##)}
5
> @b{####}
*** ERROR IN (console)@@9.1 -- (Argument 1) Out of range
(repl-result-history-ref 3)
1> 
@end smallexample

@end deffn

@deffn procedure trace @var{proc}@dots{}
@deffnx procedure untrace @var{proc}@dots{}

The @code{trace} procedure starts tracing calls to the specified
procedures.  When a traced procedure is called, a line containing the
procedure and its arguments is displayed (using the procedure call
expression syntax).  The line is indented with a sequence of vertical
bars which indicate the nesting depth of the procedure's continuation.
After the vertical bars is a greater-than sign which indicates that
the evaluation of the call is starting.

When a traced procedure returns a result, it is displayed with the same
indentation as the call but without the greater-than sign.  This makes
it easy to match calls and results (the result of a given call is the
value at the same indentation as the greater-than sign).  If a traced
procedure P1 performs a tail call to a traced procedure P2, then P2 will
use the same indentation as P1.  This makes it easy to spot tail calls.
The special handling for tail calls is needed to preserve the space
complexity of the program (i.e. tail calls are implemented as required
by Scheme even when they involve traced procedures).

The @code{untrace} procedure stops tracing calls to the specified
procedures.  When no argument is passed to the @code{trace}
procedure, the list of procedures currently being traced is returned.
The void object is returned by the @code{trace} procedure when it is
passed one or more arguments.  When no argument is passed to the
@code{untrace} procedure stops all tracing and returns the void
object.  A compiled procedure may be traced but only if it is bound to
a global variable.

For example:

@smallexample
> @b{(define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))}
> @b{(trace fact)}
> @b{(fact 5)}
| > (fact 5)
| | > (fact 4)
| | | > (fact 3)
| | | | > (fact 2)
| | | | | > (fact 1)
| | | | | 1
| | | | 2
| | | 6
| | 24
| 120
120
> @b{(trace -)}
*** WARNING -- Rebinding global variable "-" to an interpreted procedure
> @b{(define (fact-iter n r) (if (< n 2) r (fact-iter (- n 1) (* n r))))}
> @b{(trace fact-iter)}
> @b{(fact-iter 5 1)}
| > (fact-iter 5 1)
| | > (- 5 1)
| | 4
| > (fact-iter 4 5)
| | > (- 4 1)
| | 3
| > (fact-iter 3 20)
| | > (- 3 1)
| | 2
| > (fact-iter 2 60)
| | > (- 2 1)
| | 1
| > (fact-iter 1 120)
| 120
120
> @b{(trace)}
(#<procedure #2 fact-iter> #<procedure #3 -> #<procedure #4 fact>)
> @b{(untrace)}
> @b{(fact 5)}
120
@end smallexample

@end deffn

@deffn procedure step
@deffnx procedure step-level-set! @var{level}

The @code{step} procedure enables single-stepping mode.  After the call
to @code{step} the computation will stop just before the interpreter
executes the next evaluation step (as defined by
@code{step-level-set!}).  A nested REPL is then started.  Note that
because single-stepping is stopped by the REPL whenever the prompt is
displayed it is pointless to enter @code{(step)} by itself.  On the
other hand entering @code{(begin (step) @var{expr})} will evaluate
@var{expr} in single-stepping mode.

The procedure @code{step-level-set!} sets the stepping level which
determines the granularity of the evaluation steps when single-stepping
is enabled.  The stepping level @var{level} must be an exact integer in
the range 0 to 7.  At a level of 0, the interpreter ignores
single-stepping mode.  At higher levels the interpreter stops the
computation just before it performs the following operations, depending
on the stepping level:

@enumerate

@item
procedure call

@c @item
@c @code{future} special form and operations at lower levels

@item
@code{delay} special form and operations at lower levels

@item
@code{lambda} special form and operations at lower levels

@item
@code{define} special form and operations at lower levels

@item
@code{set!} special form and operations at lower levels

@item
variable reference and operations at lower levels

@item
constant reference and operations at lower levels

@end enumerate

The default stepping level is 7.

For example:

@smallexample
> @b{(define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))}
> @b{(step-level-set! 1)}
> @b{(begin (step) (fact 5))}
*** STOPPED IN (console)@@3.15
1> @b{,s}
| > (fact 5)
*** STOPPED IN fact, (console)@@1.22
1> @b{,s}
| | > (< n 2)
| | #f
*** STOPPED IN fact, (console)@@1.43
1> @b{,s}
| | > (- n 1)
| | 4
*** STOPPED IN fact, (console)@@1.37
1> @b{,s}
| | > (fact (- n 1))
*** STOPPED IN fact, (console)@@1.22
1> @b{,s}
| | | > (< n 2)
| | | #f
*** STOPPED IN fact, (console)@@1.43
1> @b{,s}
| | | > (- n 1)
| | | 3
*** STOPPED IN fact, (console)@@1.37
1> @b{,l}
| | | > (fact (- n 1))
*** STOPPED IN fact, (console)@@1.22
1> @b{,l}
| | > (* n (fact (- n 1)))
| | 24
*** STOPPED IN fact, (console)@@1.32
1> @b{,l}
| > (* n (fact (- n 1)))
| 120
120
@end smallexample

@end deffn

@deffn procedure break @var{proc}@dots{}
@deffnx procedure unbreak @var{proc}@dots{}

The @code{break} procedure places a breakpoint on each of the
specified procedures.  When a procedure is called that has a
breakpoint, the interpreter will enable single-stepping mode (as if
@code{step} had been called).  This typically causes the computation
to stop soon inside the procedure if the stepping level is high
enough.

The @code{unbreak} procedure removes the breakpoints on the specified
procedures.  With no argument, @code{break} returns the list of
procedures currently containing breakpoints.  The void object is
returned by @code{break} if it is passed one or more arguments.  With
no argument @code{unbreak} removes all the breakpoints and returns the
void object.  A breakpoint can be placed on a compiled procedure but
only if it is bound to a global variable.

For example:

@smallexample
> @b{(define (double x) (+ x x))}
> @b{(define (triple y) (- (double (double y)) y))}
> @b{(define (f z) (* (triple z) 10))}
> @b{(break double)}
> @b{(break -)}
*** WARNING -- Rebinding global variable "-" to an interpreted procedure
> @b{(f 5)}
*** STOPPED IN double, (console)@@1.21
1> @b{,b}
0  double                    (console)@@1:21          +
1  triple                    (console)@@2:31          (double y)
2  f                         (console)@@3:18          (triple z)
3  (interaction)             (console)@@6:1           (f 5)
1> @b{,e}
x = 5
1> @b{,c}
*** STOPPED IN double, (console)@@1.21
1> @b{,c}
*** STOPPED IN f, (console)@@3.29
1> @b{,c}
150
> @b{(break)}
(#<procedure #3 -> #<procedure #4 double>)
> @b{(unbreak)}
> @b{(f 5)}
150
@end smallexample

@end deffn

@deffn procedure generate-proper-tail-calls @r{[}@var{new-value}@r{]}

@cindex proper tail-calls
@cindex tail-calls

[Note: this procedure is DEPRECATED and will be removed
in a future version of Gambit.  Use the @samp{proper-tail-calls}
declaration instead.]

The parameter object @code{generate-proper-tail-calls} is bound to a
boolean value controlling how the interpreter handles tail calls.
When it is bound to @code{#f} the interpreter will treat tail calls
like nontail calls, that is a new continuation will be created for the
call.  This setting is useful for debugging, because when a primitive
signals an error the location information will point to the call site
of the primitive even if this primitive was called with a tail call.
The initial value of this parameter object is @code{#t}, which means
that a tail call will reuse the continuation of the calling function.

This parameter object only affects code that is subsequently processed
by @code{load} or @code{eval}, or entered at the REPL.

For example:

@smallexample
> @b{(generate-proper-tail-calls)}
#t
> @b{(let loop ((i 1)) (if (< i 10) (loop (* i 2)) oops))}
*** ERROR IN #<procedure #2>, (console)@@2.47 -- Unbound variable: oops
1> @b{,b}
0  #<procedure #2>           (console)@@2:47          oops
1  (interaction)             (console)@@2:1           ((letrec ((loop (lambda...
1> @b{,t}
> @b{(generate-proper-tail-calls #f)}
> @b{(let loop ((i 1)) (if (< i 10) (loop (* i 2)) oops))}
*** ERROR IN #<procedure #3>, (console)@@6.47 -- Unbound variable: oops
1> @b{,b}
0  #<procedure #3>           (console)@@6:47          oops
1  #<procedure #3>           (console)@@6:32          (loop (* i 2))
2  #<procedure #3>           (console)@@6:32          (loop (* i 2))
3  #<procedure #3>           (console)@@6:32          (loop (* i 2))
4  #<procedure #3>           (console)@@6:32          (loop (* i 2))
5  (interaction)             (console)@@6:1           ((letrec ((loop (lambda...

@end smallexample

@end deffn

@deffn procedure display-environment-set! @var{display?}

[Note: this procedure is DEPRECATED and will be removed
in a future version of Gambit.  Use the parameter object
@code{repl-display-environment?} instead.]

This procedure sets a flag that controls the automatic display of the
environment by the REPL.  If @var{display?} is true, the environment
is displayed by the REPL before the prompt.  The default setting is
not to display the environment.

@end deffn

@deffn procedure repl-display-environment? @var{display?}

The parameter object @code{repl-display-environment?} is bound to a
boolean value that controls the automatic display of the environment
by the REPL.  If @var{display?} is true, the environment is displayed
by the REPL before the prompt.  This is particularly useful in
single-stepping mode.  The default setting is not to display the
environment.

@end deffn

@deffn procedure display-dynamic-environment? @var{display?}

The parameter object @code{display-dynamic-environment?} is bound to a
boolean value that controls wether the dynamic environment is
displayed when the environment is displayed.  The default setting is
not to display the dynamic environment.

@end deffn

@deffn procedure pretty-print @var{obj} @r{[}@var{port}@r{]}

This procedure pretty-prints @var{obj} on the port @var{port}.  If it
is not specified, @var{port} defaults to the current output-port.

For example:

@smallexample
> @b{(pretty-print
    (let* ((x '(1 2 3 4)) (y (list x x x))) (list y y y)))}
(((1 2 3 4) (1 2 3 4) (1 2 3 4))
 ((1 2 3 4) (1 2 3 4) (1 2 3 4))
 ((1 2 3 4) (1 2 3 4) (1 2 3 4)))
@end smallexample

@end deffn

@deffn procedure pp @var{obj} @r{[}@var{port}@r{]}

This procedure pretty-prints @var{obj} on the port @var{port}.  When
@var{obj} is a procedure created by the interpreter or a procedure
created by code compiled with the declaration
@samp{debug-source}, the procedure's source code is
displayed.  If it is not specified, @var{port} defaults to the
interaction channel (i.e. the output will appear at the REPL).

For example:

@smallexample
> @b{(define (f g) (+ (time (g 100)) (time (g 1000))))}
> @b{(pp f)}
(lambda (g)
  (+ (##time (lambda () (g 100)) '(g 100))
     (##time (lambda () (g 1000)) '(g 1000))))
@end smallexample

@end deffn

@deffn procedure gc-report-set! @var{report?}
@cindex GC

This procedure controls the generation of reports during garbage
collections.  If the argument is true, a brief report of memory usage
is generated after every garbage collection.  It contains: the time
taken for this garbage collection, the amount of memory allocated in
megabytes since the program was started, the size of the heap in
megabytes, the heap memory in megabytes occupied by live data, the
proportion of the heap occupied by live data, and the number of bytes
occupied by movable and nonmovable objects.

@end deffn

@node Console line-editing, Emacs interface, Procedures related to debugging, Debugging
@section Console line-editing

The console implements a simple Scheme-friendly line-editing
user-interface that is enabled by default.  It offers parentheses
balancing, a history of previous commands, symbol completion, and
several emacs-compatible keyboard commands.  The user's input is
displayed in a bold font and the output produced by the system is in a
plain font.  The history of previous commands is saved in the file
@file{~/.gambc_history}.  It is restored when a REPL is started.

Symbol completion is triggered with the tab key.  When the cursor is
after a sequence of characters that can form a symbol, typing the tab
key will search the symbol table for the first symbol (in alphabetical
order) that begins with that sequence and insert that symbol.  Typing
the tab key in succession will cycle through all symbols with that
prefix.  When all possible symbols have been shown or there are no
possible completions, the text reverts to the uncompleted symbol and
the bell is rung.

Here are the keyboard commands available (where the @samp{@code{M-}}
prefix means the escape key is typed and the @samp{@code{C-}} prefix
means the control key is pressed):

@table @code

@item C-d
Generate an end-of-file when the line is empty, otherwise delete
character at cursor.

@item delete @r{or backspace}
Delete character before cursor.

@item M-C-d
Delete word forward and keep a copy of this text on the clipboard.

@item M-delete
Delete word backward and keep a copy of this text on the clipboard.

@item M-backspace
Delete S-expression backward and keep a copy of this text on the clipboard.

@item C-a
Move cursor to beginning of line.

@item C-e
Move cursor to end of line.

@item C-b @r{or @i{left-arrow}}
Move cursor left one character.

@item M-b
Move cursor left one word.

@item M-C-b @r{or @code{M-}@i{left-arrow}}
Move cursor left one S-expression.

@item C-f @r{or @i{right-arrow}}
Move cursor right one character.

@item M-f
Move cursor right one word.

@item M-C-f @r{or @code{M-}@i{right-arrow}}
Move cursor right one S-expression.

@item C-p @r{or @code{M-p} or @i{up-arrow}}
Move to previous line in history.

@item C-n @r{or @code{M-n} or @i{down-arrow}}
Move to next line in history.

@item C-t
Transpose character at cursor with previous character.

@item M-t
Transpose word after cursor with previous word.

@item M-C-t
Transpose S-expression after cursor with previous S-expression.

@item C-l
Clear console and redraw line being edited.

@item C-@i{nul}
Set the mark to the cursor.

@item C-w
Delete the text between the cursor and the mark and keep a copy
of this text on the clipboard.

@item C-k
Delete the text from the cursor to the end of the line and keep a copy
of this text on the clipboard.

@item C-y
Paste the text that is on the clipboard.

@item F8
Same as typing @samp{#||#,c;} (REPL command to continue the computation).

@item F9
Same as typing @samp{#||#,-;} (REPL command to move to newer frame).

@item F10
Same as typing @samp{#||#,+;} (REPL command to move to older frame).

@item F11
Same as typing @samp{#||#,s;} (REPL command to step the computation).

@item F12
Same as typing @samp{#||#,l;} (REPL command to leap the computation).

@end table

On Mac OS X, depending on your configuration, you may have to press
the @code{fn} key to access the function key @code{F12} and the
@code{option} key to access the other function keys.

On Microsoft Windows the clipboard is the system clipboard.  This
allows text to be copied and pasted between the program and other
applications.  On other operating systems the clipboard is internal to
the program (it is not integrated with the operating system).

@node Emacs interface, GUIDE, Console line-editing, Debugging
@section Emacs interface
@cindex Emacs
@cindex gambit.el

Gambit comes with the Emacs package @samp{gambit.el} which provides a
nice environment for running Gambit from within the Emacs editor.
This package filters the standard output of the Gambit process and
when it intercepts a location information (in the format
@samp{@var{stream}@@@var{line}.@var{column}} where @var{stream} is
either @samp{(stdin)} when the expression was obtained from standard
input, @samp{(console)} when the expression was obtained from the
console, or a string naming a file) it opens a window to highlight the
corresponding expression.

To use this package, make sure the file @samp{gambit.el} is accessible
from your load-path and that the following lines are in your
@samp{.emacs} file:

@smallexample
@b{}(autoload 'gambit-inferior-mode "gambit" "Hook Gambit mode into cmuscheme.")
(autoload 'gambit-mode "gambit" "Hook Gambit mode into scheme.")
(add-hook 'inferior-scheme-mode-hook (function gambit-inferior-mode))
(add-hook 'scheme-mode-hook (function gambit-mode))
(setq scheme-program-name "gsi -:d-")
@end smallexample

Alternatively, if you don't mind always loading this package,
you can simply add this line to your @samp{.emacs} file:

@smallexample
@b{}(require 'gambit)
@end smallexample

You can then start an inferior Gambit process by typing @samp{M-x
run-scheme}.  The commands provided in @samp{cmuscheme} mode will be
available in the Gambit interaction buffer (i.e. @samp{*scheme*}) and in
buffers attached to Scheme source files.  Here is a list of the most
useful commands (for a complete list type @samp{C-h m} in the Gambit
interaction buffer):
@table @code
@item C-x C-e
Evaluate the expression which is before the cursor (the expression will
be copied to the Gambit interaction buffer).
@item C-c C-z
Switch to Gambit interaction buffer.
@item C-c C-l
Load a file (file attached to current buffer is default) using
@code{(load @var{file})}.
@item C-c C-k
Compile a file (file attached to current buffer is default) using
@code{(compile-file @var{file})}.
@end table

The file @samp{gambit.el} provides these additional commands:

@table @code
@item F8 @r{@i{or}} C-c c
Continue the computation (same as typing @samp{#||#,c;} to the REPL).
@item F9 @r{@i{or}} C-c ]
Move to newer frame (same as typing @samp{#||#,-;} to the REPL).
@item F10 @r{@i{or}} C-c [
Move to older frame (same as typing @samp{#||#,+;} to the REPL).
@item F11 @r{@i{or}} C-c s
Step the computation (same as typing @samp{#||#,s;} to the REPL).
@item F12 @r{@i{or}} C-c l
Leap the computation (same as typing @samp{#||#,l;} to the REPL).
@item C-c _
Removes the last window that was opened to highlight an expression.
@end table

The two keystroke version of these commands can be shortened to
@samp{M-c}, @samp{M-[}, @samp{M-]}, @samp{M-s}, @samp{M-l}, and
@samp{M-_} respectively by adding this line to your @samp{.emacs}
file:

@smallexample
@b{}(setq gambit-repl-command-prefix "\e")
@end smallexample

This is more convenient to type than the two keystroke @samp{C-c} based
sequences but the purist may not like this because it does not follow
normal Emacs conventions.

Here is what a typical @samp{.emacs} file will look like:

@smallexample
@b{}(setq load-path ; add directory containing gambit.el
  (cons "/usr/local/Gambit-C/share/emacs/site-lisp"
        load-path))
(setq scheme-program-name "/tmp/gsi -:d-") ; if gsi not in executable path
(setq gambit-highlight-color "gray") ; if you don't like the default
(setq gambit-repl-command-prefix "\e") ; if you want M-c, M-s, etc
(require 'gambit)
@end smallexample

@node GUIDE, , Emacs interface, Debugging
@section GUIDE

The implementation and documentation for GUIDE, the Gambit Universal
IDE, are not yet complete.

@node Scheme extensions, Namespaces, Debugging, Top
@chapter Scheme extensions

@menu
* Extensions to standard procedures::    Extensions to standard procedures
* Extensions to standard special forms:: Extensions to standard special forms
* Miscellaneous extensions::             Miscellaneous extensions
* Undocumented extensions::              Undocumented extensions
@end menu

@node Extensions to standard procedures, Extensions to standard special forms, Scheme extensions, Scheme extensions
@section Extensions to standard procedures

@deffn procedure transcript-on @var{file}
@deffnx procedure transcript-off

These procedures do nothing.

@end deffn

@deffn procedure call-with-current-continuation @var{proc}
@deffnx procedure call/cc @var{proc}

The procedure @code{call-with-current-continuation} is bound to the
global variables @code{call-with-current-continuation} and
@code{call/cc}.

@end deffn

@node Extensions to standard special forms, Miscellaneous extensions, Extensions to standard procedures, Scheme extensions
@section Extensions to standard special forms

@deffn {special form} lambda @r{@i{lambda-formals}} @r{@i{body}}
@deffnx {special form} define (@r{@i{variable}} @r{@i{define-formals}}) @r{@i{body}}

@itemize @var{ }
@item
@i{lambda-formals} = @code{(} @i{formal-argument-list} @code{)} | @i{r4rs-lambda-formals}
@item
@i{define-formals} = @i{formal-argument-list} | @i{r4rs-define-formals}
@item
@i{formal-argument-list} = @i{dsssl-formal-argument-list} | @i{rest-at-end-formal-argument-list}
@item
@i{dsssl-formal-argument-list} = @i{reqs} @i{opts} @i{rest} @i{keys}
@item
@i{rest-at-end-formal-argument-list} = @i{reqs} @i{opts} @i{keys} @i{rest} | @i{reqs} @i{opts} @i{keys} @code{.} @i{rest-formal-argument}
@item
@i{reqs} = @i{required-formal-argument}*
@item
@i{required-formal-argument} = @i{variable}
@item
@i{opts} = @code{#!optional} @i{optional-formal-argument}* | @i{empty}
@item
@i{optional-formal-argument} = @i{variable} | @code{(} @i{variable} @i{initializer} @code{)}
@item
@i{rest} = @code{#!rest} @i{rest-formal-argument} | @i{empty}
@item
@i{rest-formal-argument} = @i{variable}
@item
@i{keys} = @code{#!key} @i{keyword-formal-argument}* | @i{empty}
@item
@i{keyword-formal-argument} = @i{variable} | @code{(} @i{variable} @i{initializer} @code{)}
@item
@i{initializer} = @i{expression}
@item
@i{r4rs-lambda-formals} = @code{(} @i{variable}* @code{)} |
@code{(} @i{variable}+ @code{.} @i{variable} @code{)} |
@i{variable}
@item
@i{r4rs-define-formals} = @i{variable}* | @i{variable}* @code{.} @i{variable}
@end itemize

These forms are extended versions of the @code{lambda} and @code{define}
special forms of standard Scheme.  They allow the use of optional formal
arguments, either positional or named, and support the syntax and semantics
of the DSSSL standard.

When the procedure introduced by a @code{lambda} (or @code{define}) is
applied to a list of actual arguments, the formal and actual arguments
are processed as specified in the R4RS if the @i{lambda-formals} (or
@i{define-formals}) is a @i{r4rs-lambda-formals} (or
@i{r4rs-define-formals}).

If the @i{formal-argument-list} matches
@i{dsssl-formal-argument-list} or @i{extended-formal-argument-list}
they are processed as follows:

@enumerate a
@item
@i{Variable}s in @i{required-formal-argument}s are bound to
successive actual arguments starting with the first actual argument.  It
shall be an error if there are fewer actual arguments than
@i{required-formal-argument}s.

@item
Next @i{variable}s in @i{optional-formal-argument}s are bound to
remaining actual arguments.  If there are fewer remaining actual
arguments than @i{optional-formal-argument}s, then the variables are
bound to the result of evaluating @i{initializer}, if one was
specified, and otherwise to @code{#f}.  The @i{initializer} is
evaluated in an environment in which all previous formal arguments have
been bound.

@item
If @code{#!key} does not appear in the @i{formal-argument-list}
and there is no @i{rest-formal-argument} then it shall be an error
if there are any remaining actual arguments.

@item
If @code{#!key} does not appear in the @i{formal-argument-list}
and there is a @i{rest-formal-argument} then the
@i{rest-formal-argument} is bound to a list of all remaining actual
arguments.

@item
If @code{#!key} appears in the @i{formal-argument-list} and there is
no @i{rest-formal-argument} then there shall be an even number of
remaining actual arguments.  These are interpreted as a series of
pairs, where the first member of each pair is a keyword specifying the
argument name, and the second is the corresponding value.  It shall be
an error if the first member of a pair is not a keyword.  It shall be
an error if the argument name is not the same as a variable in a
@i{keyword-formal-argument}.  If the same argument name occurs more
than once in the list of actual arguments, then the first value is
used.  If there is no actual argument for a particular
@i{keyword-formal-argument}, then the variable is bound to the
result of evaluating @i{initializer} if one was specified, and
otherwise to @code{#f}.  The @i{initializer} is evaluated in an
environment in which all previous formal arguments have been bound.

@item
If @code{#!key} appears in the @i{formal-argument-list} and there is
a @i{rest-formal-argument} @b{before} the @code{#!key} then there
may be an even or odd number of remaining actual arguments and the
@i{rest-formal-argument} is bound to a list of all remaining actual
arguments.  Then, these remaining actual arguments are scanned from
left to right in pairs, stopping at the first pair whose first element
is not a keyword.  Each pair whose first element is a keyword matching
the name of a @i{keyword-formal-argument} gives the value (i.e. the
second element of the pair) of the corresponding formal argument.  If
the same argument name occurs more than once in the list of actual
arguments, then the first value is used.  If there is no actual
argument for a particular @i{keyword-formal-argument}, then the
variable is bound to the result of evaluating @i{initializer} if one
was specified, and otherwise to @code{#f}.  The @i{initializer} is
evaluated in an environment in which all previous formal arguments
have been bound.

@item
If @code{#!key} appears in the @i{formal-argument-list} and there is
a @i{rest-formal-argument} @b{after} the @code{#!key} then there may
be an even or odd number of remaining actual arguments.  The remaining
actual arguments are scanned from left to right in pairs, stopping at
the first pair whose first element is not a keyword.  Each pair shall
have as its first element a keyword matching the name of a
@i{keyword-formal-argument}; the second element gives the value of
the corresponding formal argument.  If the same argument name occurs
more than once in the list of actual arguments, then the first value
is used.  If there is no actual argument for a particular
@i{keyword-formal-argument}, then the variable is bound to the
result of evaluating @i{initializer} if one was specified, and
otherwise to @code{#f}.  The @i{initializer} is evaluated in an
environment in which all previous formal arguments have been bound.
Finally, the @i{rest-formal-argument} is bound to the list of the
actual arguments that were not scanned (i.e. after the last
keyword/value pair).
@end enumerate

In all cases it is an error for a @i{variable} to appear more than
once in a @i{formal-argument-list}.

Note that this specification is compatible with the DSSSL language
standard (i.e. a correct DSSSL program will have the same semantics
when run with Gambit).

It is unspecified whether variables receive their value by binding or by
assignment.  Currently the compiler and interpreter use different
methods, which can lead to different semantics if
@code{call-with-current-continuation} is used in an @i{initializer}.
Note that this is irrelevant for DSSSL programs because
@code{call-with-current-continuation} does not exist in DSSSL.

For example:

@smallexample
> @b{((lambda (#!rest x) x) 1 2 3)}
(1 2 3)
> @b{(define (f a #!optional b) (list a b))}
> @b{(define (g a #!optional (b a) #!key (k (* a b))) (list a b k))}
> @b{(define (h1 a #!rest r #!key k) (list a k r))}
> @b{(define (h2 a #!key k #!rest r) (list a k r))}
> @b{(f 1)}
(1 #f)
> @b{(f 1 2)}
(1 2)
> @b{(g 3)}
(3 3 9)
> @b{(g 3 4)}
(3 4 12)
> @b{(g 3 4 k: 5)}
(3 4 5)
> @b{(g 3 4 k: 5 k: 6)}
(3 4 5)
> @b{(h1 7)}
(7 #f ())
> @b{(h1 7 k: 8 9)}
(7 8 (k: 8 9))
> @b{(h1 7 k: 8 z: 9)}
(7 8 (k: 8 z: 9))
> @b{(h2 7)}
(7 #f ())
> @b{(h2 7 k: 8 9)}
(7 8 (9))
> @b{(h2 7 k: 8 z: 9)}
*** ERROR IN (console)@@17.1 -- Unknown keyword argument passed to procedure
(h2 7 k: 8 z: 9)
@end smallexample

@end deffn

@node Miscellaneous extensions, Undocumented extensions, Extensions to standard special forms, Scheme extensions
@section Miscellaneous extensions

@deffn procedure vector-copy @var{vector}

This procedure returns a newly allocated vector with the same content
as the vector @var{vector}.  Note that the elements are not
recursively copied.

For example:

@smallexample
> @b{(define v1 '#(1 2 3))}
> @b{(define v2 (vector-copy v1))}
> @b{v2}
#(1 2 3)
> @b{(eq? v1 v2)}
#f
@end smallexample

@end deffn

@deffn procedure subvector @var{vector} @var{start} @var{end}

This procedure is the vector analog of the @code{substring}
procedure.  It returns a newly allocated vector formed from the
elements of the vector @var{vector} beginning with index @var{start}
(inclusive) and ending with index @var{end} (exclusive).

For example:

@smallexample
> @b{(subvector '#(a b c d e f) 3 5)}
#(d e)
@end smallexample

@end deffn

@deffn procedure vector-append @var{vector}@dots{}

This procedure is the vector analog of the @code{string-append}
procedure.  It returns a newly allocated vector whose elements
form the concatenation of the given vectors.

For example:

@smallexample
> @b{(define v '#(1 2 3))}
> @b{(vector-append v v v)}
#(1 2 3 1 2 3 1 2 3)
@end smallexample

@end deffn

@deffn procedure append-vectors @var{lst}

This procedure returns a newly allocated vector whose elements form
the concatenation of all the vectors in the list @var{lst}. It is
equivalent to @code{(apply vector-append @r{@var{lst}})}.

For example:

@smallexample
> @b{(define v '#(1 2 3))}
> @b{(append-vectors (list v v v))}
#(1 2 3 1 2 3 1 2 3)
@end smallexample

@end deffn

@deffn procedure subvector-fill! @var{vector} @var{start} @var{end} @var{fill}

This procedure is like @code{vector-fill!}, but fills a selected part
of the given vector. It sets the elements of the vector @var{vector},
beginning with index @var{start} (inclusive) and ending with index
@var{end} (exclusive) to @var{fill}.  The value returned is
unspecified.

For example:

@smallexample
> @b{(define v (vector 'a 'b 'c 'd 'e 'f))}
> @b{(subvector-fill! v 3 5 'x)}
> @b{v}
#(a b c x x f)
@end smallexample

@end deffn

@deffn procedure subvector-move! @var{src-vector} @var{src-start} @var{src-end} @var{dst-vector} @var{dst-start}

This procedure replaces part of the contents of vector
@var{dst-vector} with part of the contents of vector
@var{src-vector}. It copies elements from @var{src-vector}, beginning
with index @var{src-start} (inclusive) and ending with index
@var{src-end} (exclusive) to @var{dst-vector} beginning with index
@var{dst-start} (inclusive).  The value returned is unspecified.

For example:

@smallexample
> @b{(define v1 '#(1 2 3 4 5 6))}
> @b{(define v2 (vector 'a 'b 'c 'd 'e 'f))}
> @b{(subvector-move! v1 3 5 v2 1)}
> @b{v2}
#(a 4 5 d e f)
@end smallexample

@end deffn

@deffn procedure vector-shrink! @var{vector} @var{k}

This procedure shortens the vector @var{vector} so that its new size
is @var{k}.  The value returned is unspecified.

For example:

@smallexample
> @b{(define v (vector 'a 'b 'c 'd 'e 'f))}
> @b{v}
#(a b c d e f)
> @b{(vector-shrink! v 3)}
> @b{v}
#(a b c)
@end smallexample

@end deffn

@deffn procedure append-strings @var{lst}

This procedure returns a newly allocated string whose elements form
the concatenation of all the strings in the list @var{lst}. It is
equivalent to @code{(apply string-append @r{@var{lst}})}.

For example:

@smallexample
> @b{(define s "abc")}
> @b{(append-strings (list s s s))}
"abcabcabc"
@end smallexample

@end deffn

@deffn procedure substring-fill! @var{string} @var{start} @var{end} @var{fill}

This procedure is like @code{string-fill!}, but fills a selected part
of the given string. It sets the elements of the string @var{string},
beginning with index @var{start} (inclusive) and ending with index
@var{end} (exclusive) to @var{fill}.  The value returned is
unspecified.

For example:

@smallexample
> @b{(define s (string #\a #\b #\c #\d #\e #\f))}
> @b{(substring-fill! s 3 5 #\x)}
> @b{s}
"abcxxf"
@end smallexample

@end deffn

@deffn procedure substring-move! @var{src-string} @var{src-start} @var{src-end} @var{dst-string} @var{dst-start}

This procedure replaces part of the contents of string
@var{dst-string} with part of the contents of string
@var{src-string}. It copies elements from @var{src-string}, beginning
with index @var{src-start} (inclusive) and ending with index
@var{src-end} (exclusive) to @var{dst-string} beginning with index
@var{dst-start} (inclusive).  The value returned is unspecified.

For example:

@smallexample
> @b{(define s1 "123456")}
> @b{(define s2 (string #\a #\b #\c #\d #\e #\f))}
> @b{(substring-move! s1 3 5 s2 1)}
> @b{s2}
"a45def"
@end smallexample

@end deffn

@deffn procedure string-shrink! @var{string} @var{k}

This procedure shortens the string @var{string} so that its new size
is @var{k}.  The value returned is unspecified.

For example:

@smallexample
> @b{(define s (string #\a #\b #\c #\d #\e #\f))}
> @b{s}
"abcdef"
> @b{(string-shrink! s 3)}
> @b{s}
"abc"
@end smallexample

@end deffn

@deffn procedure box @var{obj}
@deffnx procedure box? @var{obj}
@deffnx procedure unbox @var{box}
@deffnx procedure set-box! @var{box} @var{obj}
@cindex boxes

These procedures implement the @dfn{box} data type.  A box is a
cell containing a single mutable field.  The lexical syntax
of a box containing the object @var{obj} is @code{#&@var{obj}}
(@pxref{Box syntax}).

The procedure @code{box} returns a new box object whose content is
initialized to @var{obj}.  The procedure @code{box?} returns @code{#t}
if @var{obj} is a box, and otherwise returns @code{#f}.  The procedure
@code{unbox} returns the content of the box @var{box}.  The procedure
@code{set-box!} changes the content of the box @var{box} to @var{obj}.
The procedure @code{set-box!} returns an unspecified value.

For example:

@smallexample
> @b{(define b (box 0))}
> @b{b}
#&0
> @b{(define (inc!) (set-box! b (+ (unbox b) 1)))}
> @b{(inc!)}
> @b{b}
#&1
> @b{(unbox b)}
1
@end smallexample

@end deffn

@deffn procedure keyword? @var{obj}
@deffnx procedure keyword->string @var{keyword}
@deffnx procedure string->keyword @var{string}
@cindex keywords

These procedures implement the @dfn{keyword} data type.  Keywords are
similar to symbols but are self evaluating and distinct from the
symbol data type.  The lexical syntax of keywords is specified in
@ref{Keyword syntax}.

The procedure @code{keyword?} returns @code{#t} if @var{obj} is a
keyword, and otherwise returns @code{#f}.  The procedure
@code{keyword->string} returns the name of @var{keyword} as a string.
The procedure @code{string->keyword} returns the keyword whose name is
@var{string}.

For example:

@smallexample
> @b{(keyword? 'color)}
#f
> @b{(keyword? color:)}
#t
> @b{(keyword->string color:)}
"color"
> @b{(string->keyword "color")}
color:
@end smallexample

@end deffn

@deffn procedure gensym @r{[}@var{prefix}@r{]}

This procedure returns a new @dfn{uninterned symbol}.  Uninterned symbols
are guaranteed to be distinct from the symbols generated by the
procedures @code{read} and @code{string->symbol}.  The symbol
@var{prefix} is the prefix used to generate the new symbol's name.  If
it is not specified, the prefix defaults to @samp{g}.

For example:

@smallexample
> @b{(gensym)}
#:g0
> @b{(gensym)}
#:g1
> @b{(gensym 'star-trek-)}
#:star-trek-2
@end smallexample

@end deffn

@deffn procedure string->uninterned-symbol @var{name} @r{[}@var{hash}@r{]}
@deffnx procedure uninterned-symbol? @var{obj}

The procedure @code{string->uninterned-symbol} returns a new uninterned
symbol whose name is @var{name} and hash is @var{hash}.  The name must
be a string and the hash must be a nonnegative fixnum.

The procedure @code{uninterned-symbol?} returns @code{#t} when
@var{obj} is a symbol that is uninterned and @code{#f} otherwise.

For example:

@smallexample
> @b{(uninterned-symbol? (gensym))}
#t
> @b{(string->uninterned-symbol "foo")}
#:foo:
> @b{(uninterned-symbol? (string->uninterned-symbol "foo"))}
#t
> @b{(uninterned-symbol? 'hello)}
#f
> @b{(uninterned-symbol? 123)}
#f
@end smallexample

@end deffn

@deffn procedure string->uninterned-keyword @var{name} @r{[}@var{hash}@r{]}
@deffnx procedure uninterned-keyword? @var{obj}

The procedure @code{string->uninterned-keyword} returns a new uninterned
keyword whose name is @var{name} and hash is @var{hash}.  The name must
be a string and the hash must be a nonnegative fixnum.

The procedure @code{uninterned-keyword?} returns @code{#t} when
@var{obj} is a keyword that is uninterned and @code{#f} otherwise.

For example:

@smallexample
> @b{(string->uninterned-keyword "foo")}
#:foo:
> @b{(uninterned-keyword? (string->uninterned-keyword "foo"))}
#t
> @b{(uninterned-keyword? hello:)}
#f
> @b{(uninterned-keyword? 123)}
#f
@end smallexample

@end deffn

@deffn procedure void

This procedure returns the void object.  The read-eval-print loop
prints nothing when the result is the void object.

@end deffn

@deffn procedure eval @var{expr} @r{[}@var{env}@r{]}

The first parameter is a datum representing an expression.  The
@code{eval} procedure evaluates this expression in the global
interaction environment and returns the result.  If present, the
second parameter is ignored (it is provided for compatibility with
R5RS).

For example:

@smallexample
> @b{(eval '(+ 1 2))}
3
> @b{((eval 'car) '(1 2))}
1
> @b{(eval '(define x 5))}
> @b{x}
5
@end smallexample

@end deffn

@deffn {special form} include @r{@i{file}}

The @i{file} parameter must be a string naming an existing file
containing Scheme source code.  The @code{include} special form
splices the content of the specified source file.  This form can only
appear where a @code{define} form is acceptable.

For example:

@smallexample
@b{}(include "macros.scm")

(define (f lst)
  (include "sort.scm")
  (map sqrt (sort lst)))
@end smallexample

@end deffn

@deffn {special form} define-macro (@r{@i{name}} @r{@i{define-formals}}) @r{@i{body}}
@findex include

Define @i{name} as a macro special form which expands into @i{body}.
This form can only appear where a @code{define} form is acceptable.
Macros are lexically scoped.  The scope of a local macro definition
extends from the definition to the end of the body of the surrounding
binding construct.  Macros defined at the top level of a Scheme module
are only visible in that module.  To have access to the macro
definitions contained in a file, that file must be included using the
@code{include} special form.  Macros which are visible from the REPL are
also visible during the compilation of Scheme source files.

For example:

@smallexample
@b{}(define-macro (unless test . body)
  `(if ,test #f (begin ,@@body)))

(define-macro (push var #!optional val)
  `(set! ,var (cons ,val ,var)))
@end smallexample

To examine the code into which a macro expands you can use the
compiler's @samp{-expansion} option or the @code{pp} procedure.
For example:

@smallexample
> @b{(define-macro (push var #!optional val)
    `(set! ,var (cons ,val ,var)))}
> @b{(pp (lambda () (push stack 1) (push stack) (push stack 3)))}
(lambda ()
  (set! stack (cons 1 stack))
  (set! stack (cons #f stack))
  (set! stack (cons 3 stack)))
@end smallexample

@end deffn

@deffn {special form} define-syntax @r{@i{name}} @r{@i{expander}}
@findex define-syntax
@findex syntax-rules
@findex syntax-case
@opindex -:s

Define @i{name} as a macro special form whose expansion is specified
by @i{expander}.  This form is available only when the runtime option
@samp{-:s} is used.  This option causes the loading of the
@code{~~lib/syntax-case} support library, which is the Hieb and Dybvig
portable @code{syntax-case} implementation which has been ported to
the Gambit interpreter and compiler.  Note that this implementation of
@code{syntax-case} does not support special forms that are specific to
Gambit.

For example:

@smallexample
$ @b{gsi -:s}
Gambit @value{VERSION}

> @b{(define-syntax unless
    (syntax-rules ()
      ((unless test body ...)
       (if test #f (begin body ...)))))}
> @b{(let ((test 111)) (unless (= 1 2) (list test test)))}
(111 111)
> @b{(pp (lambda () (let ((test 111)) (unless (= 1 2) (list test test)))))}
(lambda () ((lambda (%%test14) (if (= 1 2) #f (list %%test14 %%test14))) 111))
> @b{(unless #f (pp xxx))}
*** ERROR IN (console)@@7.16 -- Unbound variable: xxx
@end smallexample

@end deffn

@deffn {special form} declare @r{@i{declaration}}@dots{}

This form introduces declarations to be used by the compiler
(currently the interpreter ignores the declarations).  This form can
only appear where a @code{define} form is acceptable.  Declarations
are lexically scoped in the same way as macros.  The following
declarations are accepted by the compiler:

@table @code
@item (@var{dialect})
@opindex ieee-scheme
@opindex r4rs-scheme
@opindex r5rs-scheme
@opindex gambit-scheme
Use the given dialect's semantics.  @var{dialect} can be:
@samp{ieee-scheme}, @samp{r4rs-scheme}, @samp{r5rs-scheme}
or @samp{gambit-scheme}.

@item (@var{strategy})
@opindex block
@opindex separate
Select block compilation or separate compilation.  In block
compilation, the compiler assumes that global variables defined in the
current file that are not mutated in the file will never be mutated.
@var{strategy} can be: @samp{block} or @samp{separate}.

@item (@r{[}not@r{]} inline)
@opindex inline
Allow (or disallow) inlining of user procedures.

@item (@r{[}not@r{]} inline-primitives @var{primitive}@dots{})
@opindex inline-primitives
The given primitives should (or should not) be inlined
if possible (all primitives if none specified).

@item (inlining-limit @var{n})
@opindex inlining-limit
Select the degree to which the compiler inlines user procedures.
@var{n} is the upper-bound, in percent, on code expansion that will
result from inlining.  Thus, a value of 300 indicates that the size of
the program will not grow by more than 300 percent (i.e. it will be at
most 4 times the size of the original).  A value of 0 disables inlining.
The size of a program is the total number of subexpressions it contains
(i.e. the size of an expression is one plus the size of its immediate
subexpressions).  The following conditions must hold for a procedure to
be inlined: inlining the procedure must not cause the size of the call
site to grow more than specified by the inlining limit, the site of
definition (the @code{define} or @code{lambda}) and the call site must
be declared as @code{(inline)}, and the compiler must be able to find
the definition of the procedure referred to at the call site (if the
procedure is bound to a global variable, the definition site must have a
@code{(block)} declaration).  Note that inlining usually causes much
less code expansion than specified by the inlining limit (an expansion
around 10% is common for @var{n}=350).

@item (@r{[}not@r{]} lambda-lift)
@opindex lambda-lift
Lambda-lift (or don't lambda-lift) locally defined procedures.

@item (@r{[}not@r{]} constant-fold)
@opindex constant-fold
Allow (or disallow) constant-folding of primitive procedures.

@item (@r{[}not@r{]} standard-bindings @var{var}@dots{})
@opindex standard-bindings
The given global variables are known (or not known) to be equal to
the value defined for them in the dialect (all variables defined in
the standard if none specified).

@item (@r{[}not@r{]} extended-bindings @var{var}@dots{})
@opindex extended-bindings
The given global variables are known (or not known) to be equal to the
value defined for them in the runtime system (all variables defined
in the runtime if none specified).

@item (@r{[}not@r{]} run-time-bindings @var{var}@dots{})
@opindex run-time-bindings
The given global variables will be tested at run time to see if they
are equal to the value defined for them in the runtime system (all
variables defined in the runtime if none specified).

@item (@r{[}not@r{]} safe)
@opindex safe
Generate (or don't generate) code that will prevent fatal errors at
run time.  Note that in @samp{safe} mode certain semantic errors will
not be checked as long as they can't crash the system.  For example
the primitive @code{char=?} may disregard the type of its arguments in
@samp{safe} as well as @samp{not safe} mode.

@item (@r{[}not@r{]} interrupts-enabled)
@opindex interrupts-enabled
Generate (or don't generate) interrupt checks.  Interrupt checks are
used to detect user interrupts and also to check for stack overflows.
Interrupt checking should not be turned off casually.

@item (@r{[}not@r{]} debug)
@opindex debug
@opindex -debug
Enable (or disable) the generation of debugging information.  The kind
of debugging information that is generated depends on the declarations
@samp{debug-location}, @samp{debug-source}, and
@samp{debug-environments}.  If any of the command line options
@samp{-debug}, @samp{-debug-location}, @samp{-debug-source} and
@samp{-debug-environments} are present, the @samp{debug} declaration
is initially enabled, otherwise it is initially disabled.  When all
kinds of debugging information are generated there is a substantial
increase in the C compilation time and the size of the generated code.
When compiling a 3000 line Scheme file it was observed that the total
compilation time is 500% longer and the executable code is 150%
bigger.

@item (@r{[}not@r{]} debug-location)
@opindex debug-location
@opindex -debug-location
Select (or deselect) source code location debugging information.  When
this declaration and the @samp{debug} declaration are in effect, run
time error messages indicate the location of the error in the source
code file.  If any of the command line options @samp{-debug-source}
and @samp{-debug-environments} are present and @samp{-debug-location}
is absent, the @samp{debug-location} declaration is initially
disabled, otherwise it is initially enabled.  When compiling a 3000
line Scheme file it was observed that the total compilation time is
200% longer and the executable code is 60% bigger.

@item (@r{[}not@r{]} debug-source)
@opindex debug-source
@opindex -debug-source
Select (or deselect) source code debugging information.  When this
declaration and the @samp{debug} declaration are in effect, run time
error messages indicate the source code, the backtraces are more
precise, and the @code{pp} procedure will display the source code of
compiled procedures.  If any of the command line options
@samp{-debug-location} and @samp{-debug-environments} are present and
@samp{-debug-source} is absent, the @samp{debug-source} declaration is
initially disabled, otherwise it is initially enabled.  When compiling
a 3000 line Scheme file it was observed that the total compilation
time is 90% longer and the executable code is 90% bigger.

@item (@r{[}not@r{]} debug-environments)
@opindex debug-environments
@opindex -debug-environments
Select (or deselect) environment debugging information.  When this
declaration and the @samp{debug} declaration are in effect, the
debugger will have access to the environments of the continuations.
In other words the local variables defined in compiled procedures (and
not optimized away by the compiler) will be shown by the @samp{,e}
REPL command.  If any of the command line options
@samp{-debug-location} and @samp{-debug-source} are present and
@samp{-debug-environments} is absent, the @samp{debug-environments}
declaration is initially disabled, otherwise it is initially enabled.
When compiling a 3000 line Scheme file it was observed that the total
compilation time is 70% longer and the executable code is 40% bigger.

@item (@r{[}not@r{]} proper-tail-calls)
@opindex proper-tail-calls
@cindex proper tail-calls
@cindex tail-calls
Generate (or don't generate) proper tail calls.  When proper tail
calls are turned off, tail calls are handled like non-tail calls, that
is a continuation frame will be created for all calls regardless of
their kind.  This is useful for debugging because the caller of a
procedure will be visible in the backtrace produced by the REPL's
@samp{,b} command even when the call is a tail call.  Be advised that
this does cause stack space to be consumed for tail calls which may
cause the stack to overflow when performing long iterations with tail
calls (whether they are expressed with a @code{letrec}, named
@code{let}, @code{do}, or other form).

@item (@r{[}not@r{]} generative-lambda)
@opindex generative-lambda
@cindex generative-lambda
Force (or don't force) the creation of fresh closures when evaluating
lambda-expressions.  A fresh closure is always created when a
lambda-expression has at least one free variable (that has not been
eliminated by dead-code elimination or other compiler optimization) or
when the generative-lambda declaration is turned on.  When a
lambda-expression has no free variables and the generative-lambda
declaration is turned off, the value of the lambda-expression may be
the same procedure (in the sense of @code{eq?}).

@item (@r{[}not@r{]} optimize-dead-local-variables)
@opindex optimize-dead-local-variables
Remove (or preserve) the dead local variables in the environment.
Preserving the dead local variables is useful for debugging because
continuations will contain the dead variables.  Thus, if the code is
also compiled with the declaration @samp{debug-environments}
the @samp{,e}, @samp{,ed}, @samp{,be}, and @samp{,bed} REPL
commands will display the dead variables.  On the other hand,
preserving the dead local variables may change the space complexity of
the program (i.e. some of the data that would normally be reclaimed by
the garbage collector will not be).  Note that due to other compiler
optimizations some dead local variables may be removed regardless of
this declaration.

@item (@var{number-type} @var{primitive}@dots{})
@opindex generic
@opindex fixnum
@opindex flonum
Numeric arguments and result of the specified primitives are
known to be of the given type (all primitives if none specified).
@var{number-type} can be: @samp{generic}, @samp{fixnum}, or
@samp{flonum}.

@item (@var{mostly-number-type} @var{primitive}@dots{})
@opindex mostly-generic
@opindex mostly-fixnum
@opindex mostly-fixnum-flonum
@opindex mostly-flonum
@opindex mostly-flonum-fixnum
Numeric arguments and result of the specified primitives are expected
to be most often of the given type (all primitives if none specified).
@var{mostly-number-type} can be: @samp{mostly-generic},
@samp{mostly-fixnum}, @samp{mostly-fixnum-flonum},
@samp{mostly-flonum}, or @samp{mostly-flonum-fixnum}.

@end table

The default declarations used by the compiler are equivalent to:

@smallexample
@b{}(declare
  (gambit-scheme)
  (separate)
  (inline)
  (inline-primitives)
  (inlining-limit 350)
  (constant-fold)
  (lambda-lift)
  (not standard-bindings)
  (not extended-bindings)
  (run-time-bindings)
  (safe)
  (interrupts-enabled)
  (not debug)           ;; depends on debugging command line options
  (debug-location)      ;; depends on debugging command line options
  (debug-source)        ;; depends on debugging command line options
  (debug-environments)  ;; depends on debugging command line options
  (proper-tail-calls)
  (not generative-lambda)
  (optimize-dead-local-variables)
  (generic)
  (mostly-fixnum-flonum)
)
@end smallexample

These declarations are compatible with the semantics of R5RS Scheme
and includes a few procedures from R6RS (mainly fixnum specific and
flonum specific procedures).  Typically used declarations that enhance
performance, at the cost of violating the R5RS Scheme semantics, are:
@code{(standard-bindings)}, @code{(block)}, @code{(not safe)} and
@code{(fixnum)}.

@end deffn

@node Undocumented extensions, , Miscellaneous extensions, Scheme extensions
@section Undocumented extensions

The procedures in this section are not yet documented.

@deffn procedure continuation? @var{obj}
@deffnx procedure continuation-capture @var{proc}
@deffnx procedure continuation-graft @var{cont} @var{proc} @var{obj}@dots{}
@deffnx procedure continuation-return @var{cont} @var{obj}@dots{}

These procedures provide access to internal first-class continuations
which are represented using continuation objects distinct from procedures.

The procedure @code{continuation?} returns @code{#t} when @var{obj} is
a continuation object and @code{#f} otherwise.

The procedure @code{continuation-capture} is similar to the
@code{call/cc} procedure but it represents the continuation with a
continuation object.  The @var{proc} parameter must be a procedure
accepting a single argument.  The procedure
@code{continuation-capture} reifies its continuation and calls
@var{proc} with the corresponding continuation object as its sole
argument.  Like for @code{call/cc}, the implicit continuation of the
call to @var{proc} is the implicit continuation of the call to
@code{continuation-capture}.

The procedure @code{continuation-graft} performs a procedure call to
the procedure @var{proc} with arguments @var{obj}@dots{} and the
implicit continuation corresponding to the continuation object
@var{cont}.  The current continuation of the call to procedure
@code{continuation-graft} is ignored.

The procedure @code{continuation-return} invokes the implicit
continuation corresponding to the continuation object @var{cont} with
the result(s) @var{obj}@dots{}.  This procedure can be easily
defined in terms of @code{continuation-graft}:

@smallexample
(define (continuation-return cont . objs)
  (continuation-graft (lambda () (apply values objs))))
@end smallexample

For example:

@smallexample
> @b{(define x #f)}
> @b{(define p (make-parameter 11))}
> @b{(pp (parameterize ((p 22))
        (cons 33 (continuation-capture
                  (lambda (c) (set! x c) 44)))))}
(33 . 44)
> @b{x}
#<continuation #2>
> @b{(continuation-return x 55)}
(33 . 55)
> @b{(continuation-graft x (lambda () (expt 2 10)))}
(33 . 1024)
> @b{(continuation-graft x expt 2 10)}
(33 . 1024)
> @b{(continuation-graft x (lambda () (p)))}
(33 . 22)
> @b{(define (map-sqrt1 lst)
    (call/cc
     (lambda (k)
       (map (lambda (x)
              (if (< x 0)
                  (k 'error)
                  (sqrt x)))
            lst))))}
> @b{(map-sqrt1 '(1 4 9))}
(1 2 3)
> @b{(map-sqrt1 '(1 -1 9))}
error
> @b{(define (map-sqrt2 lst)
    (continuation-capture
     (lambda (c)
       (map (lambda (x)
              (if (< x 0)
                  (continuation-return c 'error)
                  (sqrt x)))
            lst))))}
> @b{(map-sqrt2 '(1 4 9))}
(1 2 3)
> @b{(map-sqrt2 '(1 -1 9))}
error
@end smallexample

@end deffn

@deffn procedure display-exception @var{exc} @r{[}@var{port}@r{]}
@deffnx procedure display-exception-in-context @var{exc} @var{cont} @r{[}@var{port}@r{]}
@deffnx procedure display-procedure-environment @var{proc} @r{[}@var{port}@r{]}
@deffnx procedure display-continuation-environment @var{cont} @r{[}@var{port}@r{]}
@deffnx procedure display-continuation-dynamic-environment @var{cont} @r{[}@var{port}@r{]}
@end deffn

@deffn procedure display-continuation-backtrace @var{cont} @r{[}@var{port} @r{[}@var{all-frames?} @r{[}@var{display-env?} @r{[}@var{max-head} @r{[}@var{max-tail} @r{[}@var{depth}@r{]}@r{]}@r{]}@r{]}@r{]}@r{]}

The procedure @code{display-continuation-backtrace} displays the
frames of the continuation corresponding to the continuation object
@var{cont} on the port @var{port}.  If it is not specified, @var{port}
defaults to the current output-port.  The frames are displayed in the
same format as the REPL's @samp{,b} command.

The parameter @var{all-frames?}, which defaults to @code{#f}, controls
which frames are displayed.  Some frames of ancillary importance, such
as internal frames created by the interpreter, are not displayed when
@var{all-frames?} is @code{#f}.  Otherwise all frames are displayed.

The parameter @var{display-env?}, which defaults to @code{#f}, controls
if the frames are displayed with its environment (the variables
accessible and their bindings).

The parameters @var{max-head} and @var{max-tail}, which default to 10
and 4 respectively, control how many frames are displayed at the head
and tail of the continuation.

The parameter @var{depth}, which defaults to 0, causes the frame numbers
to be offset by that value.

For example:

@smallexample
> @b{(define x #f)}
> @b{(define (fib n)
    (if (< n 2)
        (continuation-capture
         (lambda (c) (set! x c) 1))
        (+ (fib (- n 1))
           (fib (- n 2)))))}
> @b{(fib 10)}
89
> @b{(display-continuation-backtrace x)}
0  fib             (console)@@7:12     (fib (- n 2))
1  fib             (console)@@7:12     (fib (- n 2))
2  fib             (console)@@7:12     (fib (- n 2))
3  fib             (console)@@7:12     (fib (- n 2))
4  fib             (console)@@7:12     (fib (- n 2))
5  (interaction)   (console)@@8:1      (fib 10)
#f
> @b{(display-continuation-backtrace x (current-output-port) #t)}
0  fib             (console)@@7:12     (fib (- n 2))
1  fib             (console)@@6:9      (+ (fib (- n 1)) (fib (- ...
2  fib             (console)@@7:12     (fib (- n 2))
3  fib             (console)@@6:9      (+ (fib (- n 1)) (fib (- ...
4  fib             (console)@@7:12     (fib (- n 2))
5  fib             (console)@@6:9      (+ (fib (- n 1)) (fib (- ...
6  fib             (console)@@7:12     (fib (- n 2))
7  fib             (console)@@6:9      (+ (fib (- n 1)) (fib (- ...
8  fib             (console)@@7:12     (fib (- n 2))
9  fib             (console)@@6:9      (+ (fib (- n 1)) (fib (- ...
...
13 ##with-no-result-expected-toplevel 
14 ##repl-debug            
15 ##repl-debug-main       
16 ##kernel-handlers       
#f
> @b{(display-continuation-backtrace x (current-output-port) #f #t)}
0  fib             (console)@@7:12     (fib (- n 2))
        n = 2
1  fib             (console)@@7:12     (fib (- n 2))
        n = 4
2  fib             (console)@@7:12     (fib (- n 2))
        n = 6
3  fib             (console)@@7:12     (fib (- n 2))
        n = 8
4  fib             (console)@@7:12     (fib (- n 2))
        n = 10
5  (interaction)   (console)@@8:1      (fib 10)
#f
> @b{(display-continuation-backtrace x (current-output-port) #f #f 2 1 100)}
100 fib            (console)@@7:12     (fib (- n 2))
101 fib            (console)@@7:12     (fib (- n 2))
...
105 (interaction)  (console)@@8:1      (fib 10)
#f
@end smallexample

@end deffn

@deffn procedure make-thread-group @r{[}@var{name} @r{[}@var{thread-group}@r{]}@r{]}
@deffnx procedure thread-group? @var{obj}
@deffnx procedure thread-group-name @var{thread-group}
@deffnx procedure thread-group-parent @var{thread-group}
@deffnx procedure thread-group-resume! @var{thread-group}
@deffnx procedure thread-group-suspend! @var{thread-group}
@deffnx procedure thread-group-terminate! @var{thread-group}
@deffnx procedure thread-group->thread-group-list @var{thread-group}
@deffnx procedure thread-group->thread-group-vector @var{thread-group}
@deffnx procedure thread-group->thread-list @var{thread-group}
@deffnx procedure thread-group->thread-vector @var{thread-group}
@end deffn

@deffn procedure thread-state @var{thread}
@deffnx procedure thread-state-uninitialized? @var{thread-state}
@deffnx procedure thread-state-initialized? @var{thread-state}
@deffnx procedure thread-state-active? @var{thread-state}
@deffnx procedure thread-state-active-waiting-for @var{thread-state}
@deffnx procedure thread-state-active-timeout @var{thread-state}
@deffnx procedure thread-state-normally-terminated? @var{thread-state}
@deffnx procedure thread-state-normally-terminated-result @var{thread-state}
@deffnx procedure thread-state-abnormally-terminated? @var{thread-state}
@deffnx procedure thread-state-abnormally-terminated-reason @var{thread-state}
@deffnx procedure top @r{[}@var{timeout} @r{[}@var{thread-group} @r{[}@var{port}@r{]}@r{]}@r{]}
@end deffn

@deffn procedure thread-interrupt! @var{thread} @r{[}@var{thunk}@r{]}
@end deffn

@deffn procedure thread-suspend! @var{thread}
@deffnx procedure thread-resume! @var{thread}
@end deffn

@deffn procedure thread-thread-group @var{thread}
@end deffn

@deffn {special form} define-type-of-thread @r{@i{name}} @r{@i{field}}@dots{}
@end deffn

@deffn procedure thread-init! @var{thread} @var{thunk} @r{[}@var{name} @r{[}@var{thread-group}@r{]}@r{]}
@end deffn

@deffn procedure initialized-thread-exception? @var{obj}
@deffnx procedure initialized-thread-exception-procedure @var{exc}
@deffnx procedure initialized-thread-exception-arguments @var{exc}
@end deffn

@deffn procedure uninitialized-thread-exception? @var{obj}
@deffnx procedure uninitialized-thread-exception-procedure @var{exc}
@deffnx procedure uninitialized-thread-exception-arguments @var{exc}
@end deffn

@deffn procedure inactive-thread-exception? @var{obj}
@deffnx procedure inactive-thread-exception-procedure @var{exc}
@deffnx procedure inactive-thread-exception-arguments @var{exc}
@end deffn

@deffn procedure rpc-remote-error-exception? @var{obj}
@deffnx procedure rpc-remote-error-exception-procedure @var{exc}
@deffnx procedure rpc-remote-error-exception-arguments @var{exc}
@deffnx procedure rpc-remote-error-exception-message @var{exc}
@end deffn

@deffn procedure timeout->time @var{timeout}
@end deffn

@deffn procedure open-dummy
@end deffn

@deffn procedure port-settings-set! @var{port} @var{settings}
@end deffn

@deffn procedure port-io-exception-handler-set! @var{port} @var{handler}
@end deffn

@deffn procedure input-port-bytes-buffered @var{port}
@end deffn

@deffn procedure input-port-characters-buffered @var{port}
@end deffn

@deffn procedure nonempty-input-port-character-buffer-exception? @var{obj}
@deffnx procedure nonempty-input-port-character-buffer-exception-arguments @var{exc}
@deffnx procedure nonempty-input-port-character-buffer-exception-procedure @var{exc}
@end deffn

@deffn procedure repl-input-port
@deffnx procedure repl-output-port
@deffnx procedure console-port
@end deffn

@deffn procedure current-user-interrupt-handler @r{[}@var{handler}@r{]}
@deffnx procedure defer-user-interrupts
@end deffn

@deffn procedure primordial-exception-handler @var{exc}
@end deffn

@deffn procedure err-code->string @var{code}
@end deffn

@deffn procedure foreign? @var{obj}
@deffnx procedure foreign-tags @var{foreign}
@deffnx procedure foreign-address @var{foreign}
@deffnx procedure foreign-release! @var{foreign}
@deffnx procedure foreign-released? @var{foreign}
@end deffn

@deffn procedure invalid-hash-number-exception? @var{obj}
@deffnx procedure invalid-hash-number-exception-procedure @var{exc}
@deffnx procedure invalid-hash-number-exception-arguments @var{exc}
@end deffn

@deffn procedure tcp-client-peer-socket-info @var{tcp-client-port}
@deffnx procedure tcp-client-self-socket-info @var{tcp-client-port}
@end deffn

@deffn procedure tcp-server-socket-info @var{tcp-server-port}
@end deffn

@deffn procedure socket-info? @var{obj}
@deffnx procedure socket-info-address @var{socket-info}
@deffnx procedure socket-info-family @var{socket-info}
@deffnx procedure socket-info-port-number @var{socket-info}
@end deffn

@deffn procedure system-version
@deffnx procedure system-version-string
@end deffn

@deffn procedure system-type
@deffnx procedure system-type-string
@deffnx procedure configure-command-string
@end deffn

@deffn procedure system-stamp
@end deffn

@deffn {special form} future @var{expr}
@deffnx procedure touch @var{obj}
@end deffn

@deffn procedure tty? @var{obj}
@deffnx procedure tty-history @var{tty}
@deffnx procedure tty-history-set! @var{tty} @var{history}
@deffnx procedure tty-history-max-length-set! @var{tty} @var{n}
@deffnx procedure tty-paren-balance-duration-set! @var{tty} @var{duration}
@deffnx procedure tty-text-attributes-set! @var{tty} @var{attributes}
@deffnx procedure tty-mode-set! @var{tty} @var{mode}
@deffnx procedure tty-type-set! @var{tty} @var{type}
@end deffn

@deffn procedure with-input-from-port @var{port} @var{thunk}
@deffnx procedure with-output-to-port @var{port} @var{thunk}
@end deffn

@deffn procedure input-port-char-position @var{port}
@deffnx procedure output-port-char-position @var{port}
@end deffn

@deffn procedure open-event-queue @var{n}
@end deffn

@deffn procedure main @dots{}
@end deffn

@deffn {special form} define-record-type @dots{}
@deffnx {special form} define-type @dots{}
@end deffn

@deffn {special form} namespace @dots{}
@end deffn

@deffn {special form} this-source-file
@end deffn

@deffn {special form} receive @dots{}
@end deffn

@deffn {special form} cond-expand @dots{}
@end deffn

@deffn {special form} define-cond-expand-feature @var{ident}
@end deffn

@deffn procedure finite? @var{x}
@deffnx procedure infinite? @var{x}
@deffnx procedure nan? @var{x}
@end deffn

@deffn undefined six.!
@deffnx {special form} six.!x @var{x}
@deffnx {special form} six.&x @var{x}
@deffnx {special form} six.*x @var{x}
@deffnx {special form} six.++x @var{x}
@deffnx {special form} six.+x @var{x}
@deffnx {special form} six.--x @var{x}
@deffnx {special form} six.-x @var{x}
@deffnx {special form} six.arrow @var{expr} @var{ident}
@deffnx undefined six.break
@deffnx {special form} six.call @var{func} @var{arg}@dots{}
@deffnx undefined six.case
@deffnx undefined six.clause
@deffnx {special form} six.compound @var{statement}@dots{}
@deffnx {special form} six.cons @var{x} @var{y}
@deffnx undefined six.continue
@deffnx {special form} six.define-procedure @var{ident} @var{proc}
@deffnx {special form} six.define-variable @var{ident} @var{type} @var{dims} @var{init}
@deffnx {special form} six.do-while @var{stat} @var{expr}
@deffnx {special form} six.dot @var{expr} @var{ident}
@deffnx {special form} six.for @var{stat1} @var{expr2} @var{expr3} @var{stat2}
@deffnx undefined six.goto
@deffnx {special form} six.identifier @var{ident}
@deffnx {special form} six.if @var{expr} @var{stat1} @r{[}@var{stat2}@r{]}
@deffnx {special form} six.index @var{expr1} @var{expr2}
@deffnx undefined six.label
@deffnx {special form} six.list @var{x} @var{y}
@deffnx {special form} six.literal @var{value}
@deffnx procedure six.make-array @var{init} @var{dim}@dots{}
@deffnx {special form} six.new @var{ident} @var{arg}@dots{}
@deffnx {special form} six.null
@deffnx {special form} six.prefix @var{datum}
@deffnx {special form} six.procedure @var{type} @var{params} @var{stat}
@deffnx {special form} six.procedure-body @var{stat}@dots{}
@deffnx undefined six.return
@deffnx undefined six.switch
@deffnx {special form} six.while @var{expr} @var{stat}@dots{}
@deffnx {special form} six.x!=y @var{x} @var{y}
@deffnx {special form} six.x%=y @var{x} @var{y}
@deffnx {special form} six.x%y @var{x} @var{y}
@deffnx {special form} six.x&&y @var{x} @var{y}
@deffnx {special form} six.x&=y @var{x} @var{y}
@deffnx {special form} six.x&y @var{x} @var{y}
@deffnx {special form} six.x*=y @var{x} @var{y}
@deffnx {special form} six.x*y @var{x} @var{y}
@deffnx {special form} six.x++ @var{x}
@deffnx {special form} six.x+=y @var{x} @var{y}
@deffnx {special form} six.x+y @var{x} @var{y}
@deffnx {special form} |six.x,y| @var{x} @var{y}
@deffnx {special form} six.x-- @var{x}
@deffnx {special form} six.x-=y @var{x} @var{y}
@deffnx {special form} six.x-y @var{x} @var{y}
@deffnx {special form} six.x/=y @var{x} @var{y}
@deffnx {special form} six.x/y @var{x} @var{y}
@deffnx undefined six.x:-y @var{x} @var{y}
@deffnx {special form} six.x:=y @var{x} @var{y}
@deffnx {special form} six.x:y @var{x} @var{y}
@deffnx {special form} six.x<<=y @var{x} @var{y}
@deffnx {special form} six.x<<y @var{x} @var{y}
@deffnx {special form} six.x<=y @var{x} @var{y}
@deffnx {special form} six.x<y @var{x} @var{y}
@deffnx {special form} six.x==y @var{x} @var{y}
@deffnx {special form} six.x=y @var{x} @var{y}
@deffnx {special form} six.x>=y @var{x} @var{y}
@deffnx {special form} six.x>>=y @var{x} @var{y}
@deffnx {special form} six.x>>y @var{x} @var{y}
@deffnx {special form} six.x>y @var{x} @var{y}
@deffnx {special form} six.x?y:z @var{x} @var{y} @var{z}
@deffnx {special form} six.x^=y @var{x} @var{y}
@deffnx {special form} six.x^y @var{x} @var{y}
@deffnx {special form} |six.x\|=y| @var{x} @var{y}
@deffnx {special form} |six.x\|y| @var{x} @var{y}
@deffnx {special form} |six.x\|\|y| @var{x} @var{y}
@deffnx {special form} six.~x @var{x}
@end deffn

@node Namespaces, Characters and strings, Scheme extensions, Top
@chapter Namespaces

TO DO!

@node Characters and strings, Numbers, Namespaces, Top
@chapter Characters and strings

Gambit supports the Unicode character encoding standard.  Scheme
characters can be any of the characters whose Unicode encoding is in
the range 0 to #x10ffff (inclusive) but not in the range #xd800 to
#xdfff.  Source code can also contain any Unicode character, however
to read such source code properly @code{gsi} and @code{gsc} must be
told which character encoding to use for reading the source code
(i.e. ASCII, ISO-8859-1, UTF-8, etc).  This can be done by specifying
the runtime option @samp{-:f} when @code{gsi} and @code{gsc} are
started.

@menu
* Extensions to character procedures:: Extensions to character procedures
* Extensions to string procedures::    Extensions to string procedures
@end menu

@node Extensions to character procedures, Extensions to string procedures, Characters and strings, Characters and strings
@section Extensions to character procedures

@deffn procedure char->integer @var{char}
@deffnx procedure integer->char @var{n}

The procedure @code{char->integer} returns the Unicode encoding of
the character @var{char}.

The procedure @code{integer->char} returns the character whose
Unicode encoding is the exact integer @var{n}.

For example:

@smallexample
> @b{(char->integer #\!)}
33
> @b{(integer->char 65)}
#\A
> @b{(integer->char (char->integer #\u1234))}
#\u1234
> @b{(integer->char #xd800)}
*** ERROR IN (console)@@4.1 -- (Argument 1) Out of range
(integer->char 55296)
@end smallexample

@end deffn

@deffn procedure char=? @var{char1}@dots{}
@deffnx procedure char<? @var{char1}@dots{}
@deffnx procedure char>? @var{char1}@dots{}
@deffnx procedure char<=? @var{char1}@dots{}
@deffnx procedure char>=? @var{char1}@dots{}
@deffnx procedure char-ci=? @var{char1}@dots{}
@deffnx procedure char-ci<? @var{char1}@dots{}
@deffnx procedure char-ci>? @var{char1}@dots{}
@deffnx procedure char-ci<=? @var{char1}@dots{}
@deffnx procedure char-ci>=? @var{char1}@dots{}

These procedures take any number of arguments including no argument.
This is useful to test if the elements of a list are sorted in a
particular order.  For example, testing that the list of characters
@code{lst} is sorted in nondecreasing order can be done with the call
@code{(apply char<? lst)}.

@end deffn

@node Extensions to string procedures, , Extensions to character procedures, Characters and strings
@section Extensions to string procedures

@deffn procedure string=? @var{string1}@dots{}
@deffnx procedure string<? @var{string1}@dots{}
@deffnx procedure string>? @var{string1}@dots{}
@deffnx procedure string<=? @var{string1}@dots{}
@deffnx procedure string>=? @var{string1}@dots{}
@deffnx procedure string-ci=? @var{string1}@dots{}
@deffnx procedure string-ci<? @var{string1}@dots{}
@deffnx procedure string-ci>? @var{string1}@dots{}
@deffnx procedure string-ci<=? @var{string1}@dots{}
@deffnx procedure string-ci>=? @var{string1}@dots{}

These procedures take any number of arguments including no argument.
This is useful to test if the elements of a list are sorted in a
particular order.  For example, testing that the list of strings
@code{lst} is sorted in nondecreasing order can be done with the call
@code{(apply string<? lst)}.

@end deffn

@node Numbers, Homogeneous vectors, Characters and strings, Top
@chapter Numbers

@menu
* Extensions to numeric procedures::     Extensions to numeric procedures
* IEEE floating point arithmetic::       IEEE floating point arithmetic
* Integer square root and nth root::     Integer square root and nth root
* Bitwise-operations on exact integers:: Bitwise-operations on exact integers
* Fixnum specific operations::           Operations on fixnums
* Flonum specific operations::           Operations on flonums
* Pseudo random numbers::                Pseudo random numbers
@end menu

@node Extensions to numeric procedures, IEEE floating point arithmetic, Numbers, Numbers
@section Extensions to numeric procedures

@deffn procedure = @var{z1}@dots{}
@deffnx procedure < @var{x1}@dots{}
@deffnx procedure > @var{x1}@dots{}
@deffnx procedure <= @var{x1}@dots{}
@deffnx procedure >= @var{x1}@dots{}

These procedures take any number of arguments including no argument.
This is useful to test if the elements of a list are sorted in a
particular order.  For example, testing that the list of numbers
@code{lst} is sorted in nondecreasing order can be done with the call
@code{(apply < lst)}.

@end deffn

@node IEEE floating point arithmetic, Integer square root and nth root, Extensions to numeric procedures, Numbers
@section IEEE floating point arithmetic

To better conform to IEEE floating point arithmetic the standard
numeric tower is extended with these special inexact reals:

@table @code
@item +inf.0
positive infinity
@item -inf.0
negative infinity
@item +nan.0
``not a number''
@item -0.
negative zero (@samp{0.} is the positive zero)
@end table

The infinities and ``not a number'' are reals (i.e. @code{(real?
+inf.0)} is @code{#t}) but are not rational (i.e. @code{(rational?
+inf.0)} is @code{#f}).

Both zeros are numerically equal (i.e. @code{(= -0. 0.)} is @code{#t})
but are not equivalent (i.e. @code{(eqv? -0. 0.)} and @code{(equal?
-0. 0.)} are @code{#f}).  All numerical comparisons with ``not a
number'', including @code{(= +nan.0 +nan.0)}, are @code{#f}.

@node Integer square root and nth root, Bitwise-operations on exact integers, IEEE floating point arithmetic, Numbers
@section Integer square root and nth root

@deffn procedure integer-sqrt @var{n}

This procedure returns the integer part of the square root of the
nonnegative exact integer @var{n}.

For example:

@smallexample
> @b{(integer-sqrt 123)}
11
@end smallexample

@end deffn

@deffn procedure integer-nth-root @var{n1} @var{n2}

This procedure returns the integer part of @var{n1} raised to the
power 1/@var{n2}, where @var{n1} is a nonnegative exact integer and
@var{n2} is a positive exact integer.

For example:

@smallexample
> @b{(integer-nth-root 100 3)}
4
@end smallexample

@end deffn

@node Bitwise-operations on exact integers, Fixnum specific operations, Integer square root and nth root, Numbers
@section Bitwise-operations on exact integers

The procedures defined in this section are compatible with the
withdrawn ``Integer Bitwise-operation Library SRFI'' (SRFI 33).  Note
that some of the procedures specified in SRFI 33 are not provided.

Most procedures in this section are specified in terms of the binary
representation of exact integers.  The two's complement representation
is assumed where an integer is composed of an infinite number of bits.
The upper section of an integer (the most significant bits) are either
an infinite sequence of ones when the integer is negative, or they are
an infinite sequence of zeros when the integer is nonnegative.

@deffn procedure arithmetic-shift @var{n1} @var{n2}

This procedure returns @var{n1} shifted to the left by @var{n2} bits,
that is @code{(floor (* @var{n1} (expt 2 @var{n2})))}.  Both @var{n1}
and @var{n2} must be exact integers.

For example:

@smallexample
> @b{(arithmetic-shift 1000 7)  @r{@i{; n1=...0000001111101000}}}
128000
> @b{(arithmetic-shift 1000 -6) @r{@i{; n1=...0000001111101000}}}
15
> @b{(arithmetic-shift -23 -3)  @r{@i{; n1=...1111111111101001}}}
-3
@end smallexample

@end deffn

@deffn procedure bitwise-merge @var{n1} @var{n2} @var{n3}

This procedure returns an exact integer whose bits combine the bits
from @var{n2} and @var{n3} depending on @var{n1}.  The bit at index
@var{i} of the result depends only on the bits at index @var{i} in
@var{n1}, @var{n2} and @var{n3}: it is equal to the bit in @var{n2}
when the bit in @var{n1} is 0 and it is equal to the bit in @var{n3}
when the bit in @var{n1} is 1.  All arguments must be exact integers.

For example:

@smallexample
> @b{(bitwise-merge -4 -11 10) @r{@i{; ...11111100 ...11110101 ...00001010}}}
9
> @b{(bitwise-merge 12 -11 10) @r{@i{; ...00001100 ...11110101 ...00001010}}}
-7
@end smallexample

@end deffn

@deffn procedure bitwise-and @var{n}@dots{}

This procedure returns the bitwise ``and'' of the exact integers
@var{n}@dots{}.  The value -1 is returned when there are no arguments.

For example:

@smallexample
> @b{(bitwise-and 6 12)  @r{@i{; ...00000110 ...00001100}}}
4
> @b{(bitwise-and 6 -4)  @r{@i{; ...00000110 ...11111100}}}
4
> @b{(bitwise-and -6 -4) @r{@i{; ...11111010 ...11111100}}}
-8
> @b{(bitwise-and)}
-1
@end smallexample

@end deffn

@deffn procedure bitwise-ior @var{n}@dots{}

This procedure returns the bitwise ``inclusive-or'' of the exact
integers @var{n}@dots{}.  The value 0 is returned when there are no
arguments.

For example:

@smallexample
> @b{(bitwise-ior 6 12)  @r{@i{; ...00000110 ...00001100}}}
14
> @b{(bitwise-ior 6 -4)  @r{@i{; ...00000110 ...11111100}}}
-2
> @b{(bitwise-ior -6 -4) @r{@i{; ...11111010 ...11111100}}}
-2
> @b{(bitwise-ior)}
0
@end smallexample

@end deffn

@deffn procedure bitwise-xor @var{n}@dots{}

This procedure returns the bitwise ``exclusive-or'' of the exact
integers @var{n}@dots{}.  The value 0 is returned when there are no
arguments.

For example:

@smallexample
> @b{(bitwise-xor 6 12)  @r{@i{; ...00000110 ...00001100}}}
10
> @b{(bitwise-xor 6 -4)  @r{@i{; ...00000110 ...11111100}}}
-6
> @b{(bitwise-xor -6 -4) @r{@i{; ...11111010 ...11111100}}}
6
> @b{(bitwise-xor)}
0
@end smallexample

@end deffn

@deffn procedure bitwise-not @var{n}

This procedure returns the bitwise complement of the exact integer
@var{n}.

For example:

@smallexample
> @b{(bitwise-not 3)  @r{@i{; ...00000011}}}
-4
> @b{(bitwise-not -1) @r{@i{; ...11111111}}}
0
@end smallexample

@end deffn

@deffn procedure bit-count @var{n}

This procedure returns the bit count of the exact integer @var{n}.  If
@var{n} is nonnegative, the bit count is the number of 1 bits in the
two's complement representation of @var{n}.  If @var{n} is negative,
the bit count is the number of 0 bits in the two's complement
representation of @var{n}.

For example:

@smallexample
> @b{(bit-count 0)   @r{@i{; ...00000000}}}
0
> @b{(bit-count 1)   @r{@i{; ...00000001}}}
1
> @b{(bit-count 2)   @r{@i{; ...00000010}}}
1
> @b{(bit-count 3)   @r{@i{; ...00000011}}}
2
> @b{(bit-count 4)   @r{@i{; ...00000100}}}
1
> @b{(bit-count -23) @r{@i{; ...11101001}}}
3
@end smallexample

@end deffn

@deffn procedure integer-length @var{n}

This procedure returns the bit length of the exact integer @var{n}.
If @var{n} is a positive integer the bit length is one more than the
index of the highest 1 bit (the least significant bit is at index 0).
If @var{n} is a negative integer the bit length is one more than the
index of the highest 0 bit.  If @var{n} is zero, the bit length is 0.

For example:

@smallexample
> @b{(integer-length 0)   @r{@i{; ...00000000}}}
0
> @b{(integer-length 1)   @r{@i{; ...00000001}}}
1
> @b{(integer-length 2)   @r{@i{; ...00000010}}}
2
> @b{(integer-length 3)   @r{@i{; ...00000011}}}
2
> @b{(integer-length 4)   @r{@i{; ...00000100}}}
3
> @b{(integer-length -23) @r{@i{; ...11101001}}}
5
@end smallexample

@end deffn

@deffn procedure bit-set? @var{n1} @var{n2}

This procedure returns a boolean indicating if the bit at index
@var{n1} of @var{n2} is set (i.e. equal to 1) or not.  Both @var{n1}
and @var{n2} must be exact integers, and @var{n1} must be
nonnegative.

For example:

@smallexample
> @b{(map (lambda (i) (bit-set? i -23)) @r{@i{; ...11101001}}
       '(7 6 5 4 3 2 1 0))}
(#t #t #t #f #t #f #f #t)
@end smallexample

@end deffn

@deffn procedure any-bits-set? @var{n1} @var{n2}

This procedure returns a boolean indicating if the bitwise and
of @var{n1} and @var{n2} is different from zero or not.  This procedure
is implemented more efficiently than the naive definition:

@smallexample
@b{}(define (any-bits-set? n1 n2) (not (zero? (bitwise-and n1 n2))))
@end smallexample

For example:

@smallexample
> @b{(any-bits-set? 5 10)   @r{@i{; ...00000101 ...00001010}}}
#f
> @b{(any-bits-set? -23 32) @r{@i{; ...11101001 ...00100000}}}
#t
@end smallexample

@end deffn

@deffn procedure all-bits-set? @var{n1} @var{n2}

This procedure returns a boolean indicating if the bitwise and
of @var{n1} and @var{n2} is equal to @var{n1} or not.  This procedure
is implemented more efficiently than the naive definition:

@smallexample
@b{}(define (all-bits-set? n1 n2) (= n1 (bitwise-and n1 n2)))
@end smallexample

For example:

@smallexample
> @b{(all-bits-set? 1 3) @r{@i{; ...00000001 ...00000011}}}
#t
> @b{(all-bits-set? 7 3) @r{@i{; ...00000111 ...00000011}}}
#f
@end smallexample

@end deffn

@deffn procedure first-bit-set @var{n}

This procedure returns the bit index of the least significant bit of
@var{n} equal to 1 (which is also the number of 0 bits that are below
the least significant 1 bit).  This procedure returns @code{-1} when
@var{n} is zero.

For example:

@smallexample
> @b{(first-bit-set 24) @r{@i{; ...00011000}}}
3
> @b{(first-bit-set 0)  @r{@i{; ...00000000}}}
-1
@end smallexample

@end deffn

@deffn procedure extract-bit-field @var{n1} @var{n2} @var{n3}
@deffnx procedure test-bit-field? @var{n1} @var{n2} @var{n3}
@deffnx procedure clear-bit-field @var{n1} @var{n2} @var{n3}
@deffnx procedure replace-bit-field @var{n1} @var{n2} @var{n3} @var{n4}
@deffnx procedure copy-bit-field @var{n1} @var{n2} @var{n3} @var{n4}

These procedures operate on a bit-field which is @var{n1} bits wide
starting at bit index @var{n2}.  All arguments must be exact integers
and @var{n1} and @var{n2} must be nonnegative.

The procedure @code{extract-bit-field} returns the bit-field of
@var{n3} shifted to the right so that the least significant bit of the
bit-field is the least significant bit of the result.

The procedure @code{test-bit-field?} returns @code{#t} if any bit in
the bit-field of @var{n3} is equal to 1, otherwise @code{#f} is
returned.

The procedure @code{clear-bit-field} returns @var{n3} with all bits
in the bit-field replaced with 0.

The procedure @code{replace-bit-field} returns @var{n4} with the
bit-field replaced with the least-significant @var{n1} bits of
@var{n3}.

The procedure @code{copy-bit-field} returns @var{n4} with the
bit-field replaced with the (same index and size) bit-field in
@var{n3}.

For example:

@smallexample
> @b{(extract-bit-field 5 2 -37)    @r{@i{; ...11011011}}}
22
> @b{(test-bit-field? 5 2 -37)      @r{@i{; ...11011011}}}
#t
> @b{(test-bit-field? 1 2 -37)      @r{@i{; ...11011011}}}
#f
> @b{(clear-bit-field 5 2 -37)      @r{@i{; ...11011011}}}
-125
> @b{(replace-bit-field 5 2 -6 -37) @r{@i{; ...11111010 ...11011011}}}
-21
> @b{(copy-bit-field 5 2 -6 -37)    @r{@i{; ...11111010 ...11011011}}}
-5
@end smallexample

@end deffn

@node Fixnum specific operations, Flonum specific operations, Bitwise-operations on exact integers, Numbers
@section Fixnum specific operations

@deffn procedure fixnum? @var{obj}
@end deffn

@deffn procedure fx* @var{n1}@dots{}
@end deffn

@deffn procedure fx+ @var{n1}@dots{}
@end deffn

@deffn procedure fx- @var{n1} @var{n2}@dots{}
@end deffn

@deffn procedure fx< @var{n1}@dots{}
@end deffn

@deffn procedure fx<= @var{n1}@dots{}
@end deffn

@deffn procedure fx= @var{n1}@dots{}
@end deffn

@deffn procedure fx> @var{n1}@dots{}
@end deffn

@deffn procedure fx>= @var{n1}@dots{}
@end deffn

@deffn procedure fxabs @var{n}
@end deffn

@deffn procedure fxand @var{n1}@dots{}
@end deffn

@deffn procedure fxarithmetic-shift @var{n1} @var{n2}
@end deffn

@deffn procedure fxarithmetic-shift-left @var{n1} @var{n2}
@end deffn

@deffn procedure fxarithmetic-shift-right @var{n1} @var{n2}
@end deffn

@deffn procedure fxbit-count @var{n}
@end deffn

@deffn procedure fxbit-set? @var{n1} @var{n2}
@end deffn

@deffn procedure fxeven? @var{n}
@end deffn

@deffn procedure fxfirst-bit-set @var{n}
@end deffn

@deffn procedure fxif @var{n1} @var{n2} @var{n3}
@end deffn

@deffn procedure fxior @var{n1}@dots{}
@end deffn

@deffn procedure fxlength @var{n}
@end deffn

@deffn procedure fxmax @var{n1} @var{n2}@dots{}
@end deffn

@deffn procedure fxmin @var{n1} @var{n2}@dots{}
@end deffn

@deffn procedure fxmodulo @var{n1} @var{n2}
@end deffn

@deffn procedure fxnegative? @var{n}
@end deffn

@deffn procedure fxnot @var{n}
@end deffn

@deffn procedure fxodd? @var{n}
@end deffn

@deffn procedure fxpositive? @var{n}
@end deffn

@deffn procedure fxquotient @var{n1} @var{n2}
@end deffn

@deffn procedure fxremainder @var{n1} @var{n2}
@end deffn

@deffn procedure fxwrap* @var{n1}@dots{}
@end deffn

@deffn procedure fxwrap+ @var{n1}@dots{}
@end deffn

@deffn procedure fxwrap- @var{n1} @var{n2}@dots{}
@end deffn

@deffn procedure fxwrapabs @var{n}
@end deffn

@deffn procedure fxwraparithmetic-shift @var{n1} @var{n2}
@end deffn

@deffn procedure fxwraparithmetic-shift-left @var{n1} @var{n2}
@end deffn

@deffn procedure fxwraplogical-shift-right @var{n1} @var{n2}
@end deffn

@deffn procedure fxwrapquotient @var{n1} @var{n2}
@end deffn

@deffn procedure fxxor @var{n1}@dots{}
@end deffn

@deffn procedure fxzero? @var{n}
@end deffn

@deffn procedure fixnum-overflow-exception? @var{obj}
@deffnx procedure fixnum-overflow-exception-procedure @var{exc}
@deffnx procedure fixnum-overflow-exception-arguments @var{exc}

Fixnum-overflow-exception objects are raised by some of the fixnum
specific procedures when the result is larger than can fit in a
fixnum.  The parameter @var{exc} must be a fixnum-overflow-exception
object.

The procedure @code{fixnum-overflow-exception?} returns
@code{#t} when @var{obj} is a fixnum-overflow-exception
object and @code{#f} otherwise.

The procedure @code{fixnum-overflow-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{fixnum-overflow-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (fixnum-overflow-exception? exc)
        (list (fixnum-overflow-exception-procedure exc)
              (fixnum-overflow-exception-arguments exc))
        'not-fixnum-overflow-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (fx* 100000 100000)))}
(#<procedure #2 fx*> (100000 100000))
@end smallexample

@end deffn

@node Flonum specific operations, Pseudo random numbers, Fixnum specific operations, Numbers
@section Flonum specific operations

@deffn procedure flonum? @var{obj}
@end deffn

@deffn procedure fixnum->flonum @var{n}
@end deffn

@deffn procedure fl* @var{x1}@dots{}
@end deffn

@deffn procedure fl+ @var{x1}@dots{}
@end deffn

@deffn procedure fl- @var{x1} @var{x2}@dots{}
@end deffn

@deffn procedure fl/ @var{x1} @var{x2}
@end deffn

@deffn procedure fl< @var{x1}@dots{}
@end deffn

@deffn procedure fl<= @var{x1}@dots{}
@end deffn

@deffn procedure fl= @var{x1}@dots{}
@end deffn

@deffn procedure fl> @var{x1}@dots{}
@end deffn

@deffn procedure fl>= @var{x1}@dots{}
@end deffn

@deffn procedure flabs @var{x}
@end deffn

@deffn procedure flacos @var{x}
@end deffn

@deffn procedure flasin @var{x}
@end deffn

@deffn procedure flatan @var{x}
@deffnx procedure flatan @var{y} @var{x}
@end deffn

@deffn procedure flceiling @var{x}
@end deffn

@deffn procedure flcos @var{x}
@end deffn

@deffn procedure fldenominator @var{x}
@end deffn

@deffn procedure fleven? @var{x}
@end deffn

@deffn procedure flexp @var{x}
@end deffn

@deffn procedure flexpt @var{x} @var{y}
@end deffn

@deffn procedure flfinite? @var{x}
@end deffn

@deffn procedure flfloor @var{x}
@end deffn

@deffn procedure flinfinite? @var{x}
@end deffn

@deffn procedure flinteger? @var{x}
@end deffn

@deffn procedure fllog @var{x}
@end deffn

@deffn procedure flmax @var{x1} @var{x2}@dots{}
@end deffn

@deffn procedure flmin @var{x1} @var{x2}@dots{}
@end deffn

@deffn procedure flnan? @var{x}
@end deffn

@deffn procedure flnegative? @var{x}
@end deffn

@deffn procedure flnumerator @var{x}
@end deffn

@deffn procedure flodd? @var{x}
@end deffn

@deffn procedure flpositive? @var{x}
@end deffn

@deffn procedure flround @var{x}
@end deffn

@deffn procedure flsin @var{x}
@end deffn

@deffn procedure flsqrt @var{x}
@end deffn

@deffn procedure fltan @var{x}
@end deffn

@deffn procedure fltruncate @var{x}
@end deffn

@deffn procedure flzero? @var{x}
@end deffn

@node Pseudo random numbers, , Flonum specific operations, Numbers
@section Pseudo random numbers

The procedures and variables defined in this section are compatible
with the ``Sources of Random Bits SRFI'' (SRFI 27).  The
implementation is based on Pierre L'Ecuyer's MRG32k3a pseudo random
number generator.  At the heart of SRFI 27's interface is the random
source type which encapsulates the state of a pseudo random number
generator.  The state of a random source object changes every time a
pseudo random number is generated from this random source object.

@defvr variable default-random-source

The global variable @code{default-random-source} is bound to the
random source object which is used by the @code{random-integer},
@code{random-real}, @code{random-u8vector} and @code{random-f64vector}
procedures.

@end defvr

@deffn procedure random-integer @var{n}

This procedure returns a pseudo random exact integer in the range 0 to
@var{n}-1.  The random source object in the global variable
@code{default-random-source} is used to generate this number.  The
parameter @var{n} must be a positive exact integer.

For example:

@smallexample
> @b{(random-integer 100)}
24
> @b{(random-integer 100)}
2
> @b{(random-integer 10000000000000000000000000000000000000000)}
6143360270902284438072426748425263488507
@end smallexample

@end deffn

@deffn procedure random-real

This procedure returns a pseudo random inexact real between, but not
including, 0 and 1.  The random source object in the global variable
@code{default-random-source} is used to generate this number.

For example:

@smallexample
> @b{(random-real)}
.24230672079133753
> @b{(random-real)}
.02317001922506932
@end smallexample

@end deffn

@deffn procedure random-u8vector @var{n}

This procedure returns a u8vector of length @var{n} containing pseudo
random exact integers in the range 0 to 255.  The random source object
in the global variable @code{default-random-source} is used to
generate these numbers.  The parameter @var{n} must be a nonnegative
exact integer.

For example:

@smallexample
> @b{(random-u8vector 10)}
#u8(200 53 29 202 3 85 208 187 73 219)
@end smallexample

@end deffn

@deffn procedure random-f64vector @var{n}

This procedure returns a f64vector of length @var{n} containing pseudo
random inexact reals between, but not including, 0 and 1.  The random
source object in the global variable @code{default-random-source} is
used to generate these numbers.  The parameter @var{n} must be a nonnegative
exact integer.

For example:

@smallexample
> @b{(random-f64vector 3)}
#f64(.7145854494613069 .47089632669147946 .5400124875182746)
@end smallexample

@end deffn

@deffn procedure make-random-source

This procedure returns a new random source object initialized to a
predetermined state (to initialize to a pseudo random state the
procedure @code{random-source-randomize!} should be called).

For example:

@smallexample
> @b{(define rs (make-random-source))}
> @b{((random-source-make-integers rs) 10000000)}
8583952
@end smallexample

@end deffn

@deffn procedure random-source? @var{obj}

This procedure returns @code{#t} when @var{obj} is a random source
object and @code{#f} otherwise.

For example:

@smallexample
> @b{(random-source? default-random-source)}
#t
> @b{(random-source? 123)}
#f
@end smallexample

@end deffn

@deffn procedure random-source-state-ref @var{random-source}
@deffnx procedure random-source-state-set! @var{random-source} @var{state}

The procedure @code{random-source-state-ref} extracts the state of
the random source object @var{random-source} and returns a vector
containing the state.

The procedure @code{random-source-state-set!} restores the state of
the random source object @var{random-source} to @var{state} which must
be a vector returned from a call to the procedure
@code{random-source-state-ref}.

For example:

@smallexample
> @b{(define s (random-source-state-ref default-random-source))}
> @b{(random-integer 10000000000000000000000000000000000000000)}
7583880188903074396261960585615270693321
> @b{(random-source-state-set! default-random-source s)}
> @b{(random-integer 10000000000000000000000000000000000000000)}
7583880188903074396261960585615270693321
@end smallexample

@end deffn

@deffn procedure random-source-randomize! @var{random-source}
@deffnx procedure random-source-pseudo-randomize! @var{random-source} @var{i} @var{j}

These procedures change the state of the random source object
@var{random-source}.  The procedure @code{random-source-randomize!}
sets the random source object to a state that depends on the current
time (which for typical uses can be considered to randomly initialize
the state).  The procedure @code{random-source-pseudo-randomize!}
sets the random source object to a state that is determined only by
the current state and the nonnegative exact integers @var{i} and
@var{j}.  For both procedures the value returned is unspecified.

For example:

@smallexample
> @b{(define s (random-source-state-ref default-random-source))}
> @b{(random-source-pseudo-randomize! default-random-source 5 99)}
> @b{(random-integer 10000000000000000000000000000000000000000)}
9816755163910623041601722050112674079767
> @b{(random-source-state-set! default-random-source s)}
> @b{(random-source-pseudo-randomize! default-random-source 5 99)}
> @b{(random-integer 10000000000000000000000000000000000000000)}
9816755163910623041601722050112674079767
> @b{(random-source-pseudo-randomize! default-random-source 5 99)}
> @b{(random-integer 10000000000000000000000000000000000000000)}
9816755163910623041601722050112674079767
> @b{(random-source-state-set! default-random-source s)}
> @b{(random-source-randomize! default-random-source)}
> @b{(random-integer 10000000000000000000000000000000000000000)}
2271441220851914333384493143687768110622
> @b{(random-source-state-set! default-random-source s)}
> @b{(random-source-randomize! default-random-source)}
> @b{(random-integer 10000000000000000000000000000000000000000)}
6247966138948323029033944059178072366895
@end smallexample

@end deffn

@deffn procedure random-source-make-integers @var{random-source}

This procedure returns a procedure for generating pseudo random exact
integers using the random source object @var{random-source}.  The
returned procedure accepts a single parameter @var{n}, a positive
exact integer, and returns a pseudo random exact integer in the range
0 to @var{n}-1.

For example:

@smallexample
> @b{(define rs (make-random-source))}
> @b{(define ri (random-source-make-integers rs))}
> @b{(ri 10000000)}
8583952
> @b{(ri 10000000)}
2879793
@end smallexample

@end deffn

@deffn procedure random-source-make-reals @var{random-source} @r{[}@var{precision}@r{]}

This procedure returns a procedure for generating pseudo random
inexact reals using the random source object @var{random-source}.  The
returned procedure accepts no parameters and returns a pseudo random
inexact real between, but not including, 0 and 1.  The optional parameter
@var{precision} specifies an upper bound on the minimum amount by which two
generated pseudo-random numbers can be separated.

For example:

@smallexample
> @b{(define rs (make-random-source))}
> @b{(define rr (random-source-make-reals rs))}
> @b{(rr)}
.857402537562821
> @b{(rr)}
.2876463473845367
@end smallexample

@end deffn

@deffn procedure random-source-make-u8vectors @var{random-source}

This procedure returns a procedure for generating pseudo random
u8vectors using the random source object @var{random-source}.  The
returned procedure accepts a single parameter @var{n}, a nonnegative
exact integer, and returns a u8vector of length @var{n} containing
pseudo random exact integers in the range 0 to 255.

For example:

@smallexample
> @b{(define rs (make-random-source))}
> @b{(define rv (random-source-make-u8vectors rs))}
> @b{(rv 10)}
#u8(200 53 29 202 3 85 208 187 73 219)
> @b{(rv 10)}
#u8(113 8 182 120 138 103 53 192 40 176)
@end smallexample

@end deffn

@deffn procedure random-source-make-f64vectors @var{random-source} @r{[}@var{precision}@r{]}

This procedure returns a procedure for generating pseudo random
f64vectors using the random source object @var{random-source}.  The
returned procedure accepts a single parameter @var{n}, a nonnegative
exact integer, and returns an f64vector of length @var{n} containing
pseudo random inexact reals between, but not including, 0 and 1.
The optional parameter @var{precision} specifies an upper bound on the
minimum amount by which two generated pseudo-random numbers can be separated.

For example:

@smallexample
> @b{(define rs (make-random-source))}
> @b{(define rv (random-source-make-f64vectors rs))}
> @b{(rv 3)}
#f64(.7342236104231586 .2876463473845367 .8574025375628211)
> @b{(rv 3)}
#f64(.013863292728449427 .33449296573515447 .8162050798467028)
@end smallexample

@end deffn

@node Homogeneous vectors, Hashing and weak references, Numbers, Top
@chapter Homogeneous vectors
@cindex homogeneous vectors

Homogeneous vectors are vectors containing raw numbers of the same
type (signed or unsigned exact integers or inexact reals).  There are
10 types of homogeneous vectors:
@samp{s8vector} (vector of exact integers in the range -2^7 to 2^7-1),
@samp{u8vector} (vector of exact integers in the range 0 to 2^8-1),
@samp{s16vector} (vector of exact integers in the range -2^15 to 2^15-1),
@samp{u16vector} (vector of exact integers in the range 0 to 2^16-1),
@samp{s32vector} (vector of exact integers in the range -2^31 to 2^31-1),
@samp{u32vector} (vector of exact integers in the range 0 to 2^32-1),
@samp{s64vector} (vector of exact integers in the range -2^63 to 2^63-1),
@samp{u64vector} (vector of exact integers in the range 0 to 2^64-1),
@samp{f32vector} (vector of 32 bit floating point numbers),
and @samp{f64vector} (vector of 64 bit floating point numbers).

The lexical syntax of homogeneous vectors is specified in
@ref{Homogeneous vector syntax}.

The procedures available for homogeneous vectors, listed below, are
the analog of the normal vector/string procedures for each of the
homogeneous vector types.

@deffn procedure s8vector? @var{obj}
@deffnx procedure make-s8vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure s8vector @var{exact-int8}@dots{}
@deffnx procedure s8vector-length @var{s8vector}
@deffnx procedure s8vector-ref @var{s8vector} @var{k}
@deffnx procedure s8vector-set! @var{s8vector} @var{k} @var{exact-int8}
@deffnx procedure s8vector->list @var{s8vector}
@deffnx procedure list->s8vector @var{list-of-exact-int8}
@deffnx procedure s8vector-fill! @var{s8vector} @var{fill}
@deffnx procedure subs8vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-s8vectors @var{lst}
@deffnx procedure s8vector-copy @var{s8vector}
@deffnx procedure s8vector-append @var{s8vector}@dots{}
@deffnx procedure subs8vector @var{s8vector} @var{start} @var{end}
@deffnx procedure subs8vector-move! @var{src-s8vector} @var{src-start} @var{src-end} @var{dst-s8vector} @var{dst-start}
@deffnx procedure s8vector-shrink! @var{s8vector} @var{k}
@end deffn

@deffn procedure u8vector? @var{obj}
@deffnx procedure make-u8vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure u8vector @var{exact-int8}@dots{}
@deffnx procedure u8vector-length @var{u8vector}
@deffnx procedure u8vector-ref @var{u8vector} @var{k}
@deffnx procedure u8vector-set! @var{u8vector} @var{k} @var{exact-int8}
@deffnx procedure u8vector->list @var{u8vector}
@deffnx procedure list->u8vector @var{list-of-exact-int8}
@deffnx procedure u8vector-fill! @var{u8vector} @var{fill}
@deffnx procedure subu8vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-u8vectors @var{lst}
@deffnx procedure u8vector-copy @var{u8vector}
@deffnx procedure u8vector-append @var{u8vector}@dots{}
@deffnx procedure subu8vector @var{u8vector} @var{start} @var{end}
@deffnx procedure subu8vector-move! @var{src-u8vector} @var{src-start} @var{src-end} @var{dst-u8vector} @var{dst-start}
@deffnx procedure u8vector-shrink! @var{u8vector} @var{k}
@end deffn

@deffn procedure s16vector? @var{obj}
@deffnx procedure make-s16vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure s16vector @var{exact-int16}@dots{}
@deffnx procedure s16vector-length @var{s16vector}
@deffnx procedure s16vector-ref @var{s16vector} @var{k}
@deffnx procedure s16vector-set! @var{s16vector} @var{k} @var{exact-int16}
@deffnx procedure s16vector->list @var{s16vector}
@deffnx procedure list->s16vector @var{list-of-exact-int16}
@deffnx procedure s16vector-fill! @var{s16vector} @var{fill}
@deffnx procedure subs16vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-s16vectors @var{lst}
@deffnx procedure s16vector-copy @var{s16vector}
@deffnx procedure s16vector-append @var{s16vector}@dots{}
@deffnx procedure subs16vector @var{s16vector} @var{start} @var{end}
@deffnx procedure subs16vector-move! @var{src-s16vector} @var{src-start} @var{src-end} @var{dst-s16vector} @var{dst-start}
@deffnx procedure s16vector-shrink! @var{s16vector} @var{k}
@end deffn

@deffn procedure u16vector? @var{obj}
@deffnx procedure make-u16vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure u16vector @var{exact-int16}@dots{}
@deffnx procedure u16vector-length @var{u16vector}
@deffnx procedure u16vector-ref @var{u16vector} @var{k}
@deffnx procedure u16vector-set! @var{u16vector} @var{k} @var{exact-int16}
@deffnx procedure u16vector->list @var{u16vector}
@deffnx procedure list->u16vector @var{list-of-exact-int16}
@deffnx procedure u16vector-fill! @var{u16vector} @var{fill}
@deffnx procedure subu16vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-u16vectors @var{lst}
@deffnx procedure u16vector-copy @var{u16vector}
@deffnx procedure u16vector-append @var{u16vector}@dots{}
@deffnx procedure subu16vector @var{u16vector} @var{start} @var{end}
@deffnx procedure subu16vector-move! @var{src-u16vector} @var{src-start} @var{src-end} @var{dst-u16vector} @var{dst-start}
@deffnx procedure u16vector-shrink! @var{u16vector} @var{k}
@end deffn

@deffn procedure s32vector? @var{obj}
@deffnx procedure make-s32vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure s32vector @var{exact-int32}@dots{}
@deffnx procedure s32vector-length @var{s32vector}
@deffnx procedure s32vector-ref @var{s32vector} @var{k}
@deffnx procedure s32vector-set! @var{s32vector} @var{k} @var{exact-int32}
@deffnx procedure s32vector->list @var{s32vector}
@deffnx procedure list->s32vector @var{list-of-exact-int32}
@deffnx procedure s32vector-fill! @var{s32vector} @var{fill}
@deffnx procedure subs32vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-s32vectors @var{lst}
@deffnx procedure s32vector-copy @var{s32vector}
@deffnx procedure s32vector-append @var{s32vector}@dots{}
@deffnx procedure subs32vector @var{s32vector} @var{start} @var{end}
@deffnx procedure subs32vector-move! @var{src-s32vector} @var{src-start} @var{src-end} @var{dst-s32vector} @var{dst-start}
@deffnx procedure s32vector-shrink! @var{s32vector} @var{k}
@end deffn

@deffn procedure u32vector? @var{obj}
@deffnx procedure make-u32vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure u32vector @var{exact-int32}@dots{}
@deffnx procedure u32vector-length @var{u32vector}
@deffnx procedure u32vector-ref @var{u32vector} @var{k}
@deffnx procedure u32vector-set! @var{u32vector} @var{k} @var{exact-int32}
@deffnx procedure u32vector->list @var{u32vector}
@deffnx procedure list->u32vector @var{list-of-exact-int32}
@deffnx procedure u32vector-fill! @var{u32vector} @var{fill}
@deffnx procedure subu32vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-u32vectors @var{lst}
@deffnx procedure u32vector-copy @var{u32vector}
@deffnx procedure u32vector-append @var{u32vector}@dots{}
@deffnx procedure subu32vector @var{u32vector} @var{start} @var{end}
@deffnx procedure subu32vector-move! @var{src-u32vector} @var{src-start} @var{src-end} @var{dst-u32vector} @var{dst-start}
@deffnx procedure u32vector-shrink! @var{u32vector} @var{k}
@end deffn

@deffn procedure s64vector? @var{obj}
@deffnx procedure make-s64vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure s64vector @var{exact-int64}@dots{}
@deffnx procedure s64vector-length @var{s64vector}
@deffnx procedure s64vector-ref @var{s64vector} @var{k}
@deffnx procedure s64vector-set! @var{s64vector} @var{k} @var{exact-int64}
@deffnx procedure s64vector->list @var{s64vector}
@deffnx procedure list->s64vector @var{list-of-exact-int64}
@deffnx procedure s64vector-fill! @var{s64vector} @var{fill}
@deffnx procedure subs64vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-s64vectors @var{lst}
@deffnx procedure s64vector-copy @var{s64vector}
@deffnx procedure s64vector-append @var{s64vector}@dots{}
@deffnx procedure subs64vector @var{s64vector} @var{start} @var{end}
@deffnx procedure subs64vector-move! @var{src-s64vector} @var{src-start} @var{src-end} @var{dst-s64vector} @var{dst-start}
@deffnx procedure s64vector-shrink! @var{s64vector} @var{k}
@end deffn

@deffn procedure u64vector? @var{obj}
@deffnx procedure make-u64vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure u64vector @var{exact-int64}@dots{}
@deffnx procedure u64vector-length @var{u64vector}
@deffnx procedure u64vector-ref @var{u64vector} @var{k}
@deffnx procedure u64vector-set! @var{u64vector} @var{k} @var{exact-int64}
@deffnx procedure u64vector->list @var{u64vector}
@deffnx procedure list->u64vector @var{list-of-exact-int64}
@deffnx procedure u64vector-fill! @var{u64vector} @var{fill}
@deffnx procedure subu64vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-u64vectors @var{lst}
@deffnx procedure u64vector-copy @var{u64vector}
@deffnx procedure u64vector-append @var{u64vector}@dots{}
@deffnx procedure subu64vector @var{u64vector} @var{start} @var{end}
@deffnx procedure subu64vector-move! @var{src-u64vector} @var{src-start} @var{src-end} @var{dst-u64vector} @var{dst-start}
@deffnx procedure u64vector-shrink! @var{u64vector} @var{k}
@end deffn

@deffn procedure f32vector? @var{obj}
@deffnx procedure make-f32vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure f32vector @var{inexact-real}@dots{}
@deffnx procedure f32vector-length @var{f32vector}
@deffnx procedure f32vector-ref @var{f32vector} @var{k}
@deffnx procedure f32vector-set! @var{f32vector} @var{k} @var{inexact-real}
@deffnx procedure f32vector->list @var{f32vector}
@deffnx procedure list->f32vector @var{list-of-inexact-real}
@deffnx procedure f32vector-fill! @var{f32vector} @var{fill}
@deffnx procedure subf32vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-f32vectors @var{lst}
@deffnx procedure f32vector-copy @var{f32vector}
@deffnx procedure f32vector-append @var{f32vector}@dots{}
@deffnx procedure subf32vector @var{f32vector} @var{start} @var{end}
@deffnx procedure subf32vector-move! @var{src-f32vector} @var{src-start} @var{src-end} @var{dst-f32vector} @var{dst-start}
@deffnx procedure f32vector-shrink! @var{f32vector} @var{k}
@end deffn

@deffn procedure f64vector? @var{obj}
@deffnx procedure make-f64vector @var{k} @r{[}@var{fill}@r{]}
@deffnx procedure f64vector @var{inexact-real}@dots{}
@deffnx procedure f64vector-length @var{f64vector}
@deffnx procedure f64vector-ref @var{f64vector} @var{k}
@deffnx procedure f64vector-set! @var{f64vector} @var{k} @var{inexact-real}
@deffnx procedure f64vector->list @var{f64vector}
@deffnx procedure list->f64vector @var{list-of-inexact-real}
@deffnx procedure f64vector-fill! @var{f64vector} @var{fill}
@deffnx procedure subf64vector-fill! @var{vector} @var{start} @var{end} @var{fill}
@deffnx procedure append-f64vectors @var{lst}
@deffnx procedure f64vector-copy @var{f64vector}
@deffnx procedure f64vector-append @var{f64vector}@dots{}
@deffnx procedure subf64vector @var{f64vector} @var{start} @var{end}
@deffnx procedure subf64vector-move! @var{src-f64vector} @var{src-start} @var{src-end} @var{dst-f64vector} @var{dst-start}
@deffnx procedure f64vector-shrink! @var{f64vector} @var{k}
@end deffn

For example:

@smallexample
> @b{(define v (u8vector 10 255 13))}
> @b{(u8vector-set! v 2 99)}
> @b{v}
#u8(10 255 99)
> @b{(u8vector-ref v 1)}
255
> @b{(u8vector->list v)}
(10 255 99)
> @b{(u8vector-shrink! v 2)}
> @b{(v)}
#u8(10 255)
@end smallexample

@deffn procedure object->u8vector @var{obj} @r{[}@var{encoder}@r{]}
@deffnx procedure u8vector->object @var{u8vector} @r{[}@var{decoder}@r{]}
@cindex serialization
@cindex deserialization

The procedure @code{object->u8vector} returns a u8vector that contains
the sequence of bytes that encodes the object @var{obj}.  The
procedure @code{u8vector->object} decodes the sequence of bytes
contained in the u8vector @var{u8vector}, which was produced by the
procedure @code{object->u8vector}, and reconstructs an object
structurally equal to the original object.  In other words the
procedures @code{object->u8vector} and @code{u8vector->object}
respectively perform serialization and deserialization of Scheme
objects.  Note that some objects are non-serializable (e.g. threads,
wills, some types of ports, and any object containing a
non-serializable object).

The optional @var{encoder} and @var{decoder} parameters are single
parameter procedures which default to the identity function.  The
@var{encoder} procedure is called during serialization.  As the
serializer walks through @var{obj}, it calls the @var{encoder}
procedure on each sub-object @var{X} that is encountered.  The
@var{encoder} transforms the object @var{X} into an object @var{Y}
that will be serialized instead of @var{X}.  Similarly the
@var{decoder} procedure is called during deserialization.  When an
object @var{Y} is encountered, the @var{decoder} procedure is called
to transform it into the object @var{X} that is the result of
deserialization.

The @var{encoder} and @var{decoder} procedures are useful to customize
the serialized representation of objects.  In particular, it can be
used to define the semantics of serializing objects, such as threads
and ports, that would otherwise not be serializable.  The
@var{decoder} procedure is typically the inverse of the @var{encoder}
procedure, i.e. @code{(@var{decoder} (@var{encoder} @var{X}))} =
@code{@var{X}}.

For example:

@smallexample
> @b{(define (make-adder x) (lambda (y) (+ x y)))}
> @b{(define f (make-adder 10))}
> @b{(define a (object->u8vector f))}
> @b{(define b (u8vector->object a))}
> @b{(u8vector-length a)}
1639
> @b{(f 5)}
15
> @b{(b 5)}
15
> @b{(pp b)}
(lambda (y) (+ x y))
@end smallexample

@end deffn

@node Hashing and weak references, Records, Homogeneous vectors, Top
@chapter Hashing and weak references
@cindex hashing
@cindex weak references
@cindex tables

@menu
* Hashing::                         Hashing
* Weak references::                 Weak references
@end menu

@node Hashing, Weak references, Hashing and weak references, Hashing and weak references
@section Hashing

@deffn procedure object->serial-number @var{obj}
@deffnx procedure serial-number->object @var{n} @r{[}@var{default}@r{]}

All Scheme objects are uniquely identified with a serial number which
is a nonnegative exact integer.  The @code{object->serial-number} procedure
returns the serial number of object @var{obj}.  This serial number is
only allocated the first time the @code{object->serial-number}
procedure is called on that object.  Objects which do not have an
external textual representation that can be read by the @code{read}
procedure, use an external textual representation that includes a
serial number of the form @code{#@var{n}}.  Consequently, the
procedures @code{write}, @code{pretty-print}, etc will call the
@code{object->serial-number} procedure to get the serial number, and
this may cause the serial number to be allocated.

The @code{serial-number->object} procedure takes an exact integer
parameter @var{n} and returns the object whose serial number is
@var{n}.  If no object currently exists with that serial number,
@var{default} is returned if it is specified, otherwise an
unbound-serial-number-exception object is raised.  The reader defines
the following abbreviation for calling @code{serial-number->object}:
the syntax @code{#@var{n}}, where @var{n} is a sequence of decimal
digits and it is not followed by @samp{@code{=}} or @samp{@code{#}},
is equivalent to the list @code{(serial-number->object @var{n})}.

For example:

@smallexample
> @b{(define z (list (lambda (x) (* x x)) (lambda (y) (/ 1 y))))}
> @b{z}
(#<procedure #2> #<procedure #3>)
> @b{(#3 10)}
1/10
> @b{'(#3 10)}
((serial-number->object 3) 10)
> @b{car}
#<procedure #4 car>
> @b{(#4 z)}
#<procedure #2>
@end smallexample

@end deffn

@deffn procedure unbound-serial-number-exception? @var{obj}
@deffnx procedure unbound-serial-number-exception-procedure @var{exc}
@deffnx procedure unbound-serial-number-exception-arguments @var{exc}

Unbound-serial-number-exception objects are raised by the procedure
@code{serial-number->object} when no object currently exists with that
serial number.  The parameter @var{exc} must be an
unbound-serial-number-exception object.

The procedure @code{unbound-serial-number-exception?} returns
@code{#t} when @var{obj} is a unbound-serial-number-exception
object and @code{#f} otherwise.

The procedure @code{unbound-serial-number-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{unbound-serial-number-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (unbound-serial-number-exception? exc)
        (list (unbound-serial-number-exception-procedure exc)
              (unbound-serial-number-exception-arguments exc))
        'not-unbound-serial-number-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (serial-number->object 1000)))}
(#<procedure #2 serial-number->object> (1000))
@end smallexample

@end deffn

@deffn procedure symbol-hash @var{symbol}

The @code{symbol-hash} procedure returns the hash number of the symbol
@var{symbol}.  The hash number is a small exact integer (fixnum).
When @var{symbol} is an interned symbol the value returned is the same
as @code{(string=?-hash (symbol->string @var{symbol}))}.

For example:

@smallexample
> @b{(symbol-hash 'car)}
444471047
@end smallexample

@end deffn

@deffn procedure keyword-hash @var{keyword}

The @code{keyword-hash} procedure returns the hash number of the
keyword @var{keyword}.  The hash number is a small exact integer
(fixnum).  When @var{keyword} is an interned keyword the value
returned is the same as @code{(string=?-hash (keyword->string
@var{keyword}))}.

For example:

@smallexample
> @b{(keyword-hash car:)}
444471047
@end smallexample

@end deffn

@deffn procedure string=?-hash @var{string}

The @code{string=?-hash} procedure returns the hash number of the
string @var{string}.  The hash number is a small exact integer
(fixnum).  For any two strings @var{s1} and @var{s2}, @code{(string=?
@var{s1} @var{s2})} implies @code{(= (string=?-hash @var{s1})
(string=?-hash @var{s2}))}.

For example:

@smallexample
> @b{(string=?-hash "car")}
444471047
@end smallexample

@end deffn

@deffn procedure string-ci=?-hash @var{string}

The @code{string-ci=?-hash} procedure returns the hash number of the
string @var{string}.  The hash number is a small exact integer
(fixnum).  For any two strings @var{s1} and @var{s2}, @code{(string-ci=?
@var{s1} @var{s2})} implies @code{(= (string-ci=?-hash @var{s1})
(string-ci=?-hash @var{s2}))}.

For example:

@smallexample
> @b{(string-ci=?-hash "CaR")}
444471047
@end smallexample

@end deffn

@deffn procedure eq?-hash @var{obj}

The @code{eq?-hash} procedure returns the hash number of the object
@var{obj}.  The hash number is a small exact integer (fixnum).  For
any two objects @var{o1} and @var{o2}, @code{(eq? @var{o1} @var{o2})}
implies @code{(= (eq?-hash @var{o1}) (eq?-hash @var{o2}))}.

For example:

@smallexample
> @b{(eq?-hash #t)}
536870910
@end smallexample

@end deffn

@deffn procedure eqv?-hash @var{obj}

The @code{eqv?-hash} procedure returns the hash number of the object
@var{obj}.  The hash number is a small exact integer (fixnum).  For
any two objects @var{o1} and @var{o2}, @code{(eqv? @var{o1} @var{o2})}
implies @code{(= (eqv?-hash @var{o1}) (eqv?-hash @var{o2}))}.

For example:

@smallexample
> @b{(eqv?-hash 1.5)}
496387656
@end smallexample

@end deffn

@deffn procedure equal?-hash @var{obj}

The @code{equal?-hash} procedure returns the hash number of the object
@var{obj}.  The hash number is a small exact integer (fixnum).  For
any two objects @var{o1} and @var{o2}, @code{(equal? @var{o1} @var{o2})}
implies @code{(= (equal?-hash @var{o1}) (equal?-hash @var{o2}))}.

For example:

@smallexample
> @b{(equal?-hash (list 1 2 3))}
442438567
@end smallexample

@end deffn

@node Weak references, , Hashing, Hashing and weak references
@section Weak references

The garbage collector is responsible for reclaiming objects that are
no longer needed by the program.  This is done by analyzing the
reachability graph of all objects from the roots (i.e. the global
variables, the runnable threads, permanently allocated objects such as
procedures defined in a compiled file, nonexecutable wills, etc).  If
a root or a reachable object @var{X} contains a reference to an object
@var{Y} then @var{Y} is reachable.  As a general rule, unreachable
objects are reclaimed by the garbage collector.

There are two types of references: strong references and weak
references.  Most objects, including pairs, vectors, records and
closures, contain strong references.  An object @var{X} is
@dfn{strongly reachable} if there is a path from the roots to @var{X}
that traverses only strong references.  Weak references only occur in
wills and tables.  There are two types of weak references: will-weak
references and table-weak references.  If all paths from the roots to
an object @var{Y} traverse at least one table-weak reference, then
@var{Y} will be reclaimed by the garbage collector.  The will-weak
references are used for finalization and are explained in the next
section.

@menu
* Wills::                           Wills
* Tables::                          Tables
@end menu

@node Wills, Tables, Weak references, Weak references
@subsection Wills

The following procedures implement the @dfn{will} data type.  Will
objects provide support for finalization.  A will is an object that
contains a will-weak reference to a @var{testator} object (the object
attached to the will), and a strong reference to an @var{action}
procedure which is a one parameter procedure which is called when the
will is executed.

@deffn procedure make-will @var{testator} @var{action}
@deffnx procedure will? @var{obj}
@deffnx procedure will-testator @var{will}
@deffnx procedure will-execute! @var{will}

The @code{make-will} procedure creates a will object with the given
@var{testator} object and @var{action} procedure.  The @code{will?}
procedure tests if @var{obj} is a will object.  The
@code{will-testator} procedure gets the testator object attached to
the @var{will}.  The @code{will-execute!} procedure executes
@var{will}.

A will becomes @dfn{executable} when its @var{testator} object is not
strongly reachable (i.e. the @var{testator} object is either
unreachable or only reachable using paths from the roots that traverse
at least one weak reference).  Some objects, including symbols, small
exact integers (fixnums), booleans and characters, are considered to
be always strongly reachable.

When the runtime system detects that a will has become executable the
current computation is interrupted, the will's testator is set to
@code{#f} and the will's action procedure is called with the will's
testator as the sole argument.  Currently only the garbage collector
detects when wills become executable but this may change in future
versions of Gambit (for example the compiler could perform an analysis
to infer will executability at compile time).  The garbage collector
builds a list of all executable wills.  Shortly after a garbage
collection, the action procedures of these wills will be called.  The
link from the will to the action procedure is severed when the action
procedure is called.

Note that the testator object will not be reclaimed during the garbage
collection that determined executability of the will.  It is only when
an object is not reachable from the roots that it is reclaimed by the
garbage collector.

A remarkable feature of wills is that an action procedure can
``resurrect'' an object.  An action procedure could for example assign
the testator object to a global variable or create a new will with the
same testator object.

For example:

@smallexample
> @b{(define a (list 123))}
> @b{(set-cdr! a a) @r{@i{; create a circular list}}}
> @b{(define b (vector a))}
> @b{(define c #f)}
> @b{(define w
    (let ((obj a))
      (make-will obj
                 (lambda (x) ; x will be eq? to obj
                   (display "executing action procedure")
                   (newline)
                   (set! c x)))))}
> @b{(will? w)}
#t
> @b{(car (will-testator w))}
123
> @b{(##gc)}
> @b{(set! a #f)}
> @b{(##gc)}
> @b{(set! b #f)}
> @b{(##gc)}
executing action procedure
> @b{(will-testator w)}
#f
> @b{(car c)}
123
@end smallexample

@end deffn

@node Tables, , Wills, Weak references
@subsection Tables

The following procedures implement the @dfn{table} data type.  Tables
are heterogenous structures whose elements are indexed by keys which
are arbitrary objects.  Tables are similar to association lists but
are abstract and the access time for large tables is typically smaller.
Each key contained in the table is bound to a value.  The length of
the table is the number of key/value bindings it contains.  New
key/value bindings can be added to a table, the value bound to a key
can be changed, and existing key/value bindings can be removed.

The references to the keys can either be all strong or all table-weak
and the references to the values can either be all strong or all
table-weak.  The garbage collector removes key/value bindings from a
table when 1) the key is a table-weak reference and the key is
unreachable or only reachable using paths from the roots that traverse
at least one table-weak reference, or 2) the value is a table-weak
reference and the value is unreachable or only reachable using paths
from the roots that traverse at least one table-weak reference.
Key/value bindings that are removed by the garbage collector are
reclaimed immediately.

Although there are several possible ways of implementing tables, the
current implementation uses hashing with open-addressing.  This is
space efficient and provides constant-time access.  Hash tables are
automatically resized to maintain the load within specified bounds.
The load is the number of active entries (the length of the table)
divided by the total number of entries in the hash table.

Tables are parameterized with a key comparison procedure.  By default
the @code{equal?} procedure is used, but @code{eq?}, @code{eqv?},
@code{string=?}, @code{string-ci=?}, or a user defined procedure can
also be used.  To support arbitrary key comparison procedures, tables
are also parameterized with a hashing procedure accepting a key as its
single parameter and returning a fixnum result.  The hashing procedure
@var{hash} must be consistent with the key comparison procedure
@var{test}, that is, for any two keys @var{k1} and @var{k2} in the
table, @code{(@var{test} @var{k1} @var{k2})} implies @code{(=
(@var{hash} @var{k1}) (@var{hash} @var{k2}))}.  A default hashing
procedure consistent with the key comparison procedure is provided by
the system.  The default hashing procedure generally gives good
performance when the key comparison procedure is @code{eq?},
@code{eqv?}, @code{equal?}, @code{string=?}, and @code{string-ci=?}.
However, for user defined key comparison procedures, the default
hashing procedure always returns 0.  This degrades the performance of
the table to a linear search.

Tables can be compared for equality using the @code{equal?} procedure.
Two tables @code{@var{X}} and @code{@var{Y}} are considered equal by
@code{equal?} when they have the same weakness attributes, the same
key comparison procedure, the same hashing procedure, the same length,
and for all the keys @code{@var{k}} in @code{@var{X}}, @code{(equal?
(table-ref @var{X} @var{k}) (table-ref @var{Y} @var{k}))}.

@deffn procedure make-table @r{[}@code{size:} @var{size}@r{]} @r{[}@code{init:} @var{init}@r{]} @r{[}@code{weak-keys:} @var{weak-keys}@r{]} @r{[}@code{weak-values:} @var{weak-values}@r{]} @r{[}@code{test:} @var{test}@r{]} @r{[}@code{hash:} @var{hash}@r{]} @r{[}@code{min-load:} @var{min-load}@r{]} @r{[}@code{max-load:} @var{max-load}@r{]}

The procedure @code{make-table} returns a new table.  The optional keyword
parameters specify various parameters of the table.

The @var{size} parameter is a nonnegative exact integer indicating
the expected length of the table.  The system uses @var{size} to
choose an appropriate initial size of the hash table so that it does not
need to be resized too often.

The @var{init} parameter indicates a value that is associated to keys
that are not in the table.  When @var{init} is not specified, no value
is associated to keys that are not in the table.

The @var{weak-keys} and @var{weak-values} parameters are extended
booleans indicating respectively whether the keys and values are
table-weak references (true) or strong references (false).  By default
the keys and values are strong references.

The @var{test} parameter indicates the key comparison procedure.  The
default key comparison procedure is @code{equal?}.  The key comparison
procedures @code{eq?}, @code{eqv?}, @code{equal?}, @code{string=?},
and @code{string-ci=?} are special because the system will use a
reasonably good hash procedure when none is specified.

The @var{hash} parameter indicates the hash procedure.  This procedure
must accept a single key parameter, return a fixnum, and be consistent
with the key comparison procedure.  When @var{hash} is not specified, a
default hash procedure is used.  The default hash procedure is
reasonably good when the key comparison procedure is @code{eq?},
@code{eqv?}, @code{equal?}, @code{string=?}, or @code{string-ci=?}.

The @var{min-load} and @var{max-load} parameters are real numbers that
indicate the minimum and maximum load of the table respectively.  The
table is resized when adding or deleting a key/value binding would
bring the table's load outside of this range.  The @var{min-load}
parameter must be no less than 0.05 and the @var{max-load} parameter
must be no greater than 0.95.  Moreover the difference between
@var{min-load} and @var{max-load} must be at least 0.20.  When
@var{min-load} is not specified, the value 0.45 is used.  When
@var{max-load} is not specified, the value 0.90 is used.

For example:

@smallexample
> @b{(define t (make-table))}
> @b{(table? t)}
#t
> @b{(table-length t)}
0
> @b{(table-set! t (list 1 2) 3)}
> @b{(table-set! t (list 4 5) 6)}
> @b{(table-ref t (list 1 2))}
3
> @b{(table-length t)}
2
@end smallexample

@end deffn

@deffn procedure table? @var{obj}

The procedure @code{table?} returns @code{#t} when @var{obj} is a
table and @code{#f} otherwise.

For example:

@smallexample
> @b{(table? (make-table))}
#t
> @b{(table? 123)}
#f
@end smallexample

@end deffn

@deffn procedure table-length @var{table}

The procedure @code{table-length} returns the number of key/value
bindings contained in the table @var{table}.

For example:

@smallexample
> @b{(define t (make-table weak-keys: #t))}
> @b{(define x (list 1 2))}
> @b{(define y (list 3 4))}
> @b{(table-set! t x 111)}
> @b{(table-set! t y 222)}
> @b{(table-length t)}
2
> @b{(table-set! t x)}
> @b{(table-length t)}
1
> @b{(##gc)}
> @b{(table-length t)}
1
> @b{(set! y #f)}
> @b{(##gc)}
> @b{(table-length t)}
0
@end smallexample

@end deffn

@deffn procedure table-ref @var{table} @var{key} @r{[}@var{default}@r{]}

The procedure @code{table-ref} returns the value bound to the object
@var{key} in the table @var{table}.  When @var{key} is not bound and
@var{default} is specified, @var{default} is returned.  When
@var{default} is not specified but an @var{init} parameter was
specified when @var{table} was created, @var{init} is returned.
Otherwise an unbound-table-key-exception object is raised.

For example:

@smallexample
> @b{(define t1 (make-table init: 999))}
> @b{(table-set! t1 (list 1 2) 3)}
> @b{(table-ref t1 (list 1 2))}
3
> @b{(table-ref t1 (list 4 5))}
999
> @b{(table-ref t1 (list 4 5) #f)}
#f
> @b{(define t2 (make-table))}
> @b{(table-ref t2 (list 4 5))}
*** ERROR IN (console)@@7.1 -- Unbound table key
(table-ref '#<table #2> '(4 5))
@end smallexample

@end deffn

@deffn procedure table-set! @var{table} @var{key} @r{[}@var{value}@r{]}

The procedure @code{table-set!} binds the object @var{key} to
@var{value} in the table @var{table}.  When @var{value} is not
specified, if @var{table} contains a binding for @var{key} then the
binding is removed from @var{table}.  The procedure @code{table-set!}
returns an unspecified value.

For example:

@smallexample
> @b{(define t (make-table))}
> @b{(table-set! t (list 1 2) 3)}
> @b{(table-set! t (list 4 5) 6)}
> @b{(table-set! t (list 4 5))}
> @b{(table-set! t (list 7 8))}
> @b{(table-ref t (list 1 2))}
3
> @b{(table-ref t (list 4 5))}
*** ERROR IN (console)@@7.1 -- Unbound table key
(table-ref '#<table #2> '(4 5))
@end smallexample

@end deffn

@deffn procedure table-search @var{proc} @var{table}

The procedure @code{table-search} searches the table @var{table} for a
key/value binding for which the two parameter procedure @var{proc}
returns a non false result.  For each key/value binding visited by
@code{table-search} the procedure @var{proc} is called with the key as
the first parameter and the value as the second parameter.  The
procedure @code{table-search} returns the first non false value
returned by @var{proc}, or @code{#f} if @var{proc} returned @code{#f}
for all key/value bindings in @var{table}.

The order in which the key/value bindings are visited is unspecified
and may vary from one call of @code{table-search} to the next.  While
a call to @code{table-search} is being performed on @var{table}, it is
an error to call any of the following procedures on @var{table}:
@code{table-ref}, @code{table-set!}, @code{table-search},
@code{table-for-each}, @code{table-copy}, @code{table-merge},
@code{table-merge!}, and @code{table->list}.  It is also an error to
compare with @code{equal?} (directly or indirectly with @code{member},
@code{assoc}, @code{table-ref}, etc.) an object that contains
@var{table}.  All these procedures may cause @var{table} to be
reordered and resized.  This restriction allows a more efficient
iteration over the key/value bindings.

For example:

@smallexample
> @b{(define square (make-table))}
> @b{(table-set! square 2 4)}
> @b{(table-set! square 3 9)}
> @b{(table-search (lambda (k v) (and (odd? k) v)) square)}
9
@end smallexample

@end deffn

@deffn procedure table-for-each @var{proc} @var{table}

The procedure @code{table-for-each} calls the two parameter procedure
@var{proc} for each key/value binding in the table @var{table}.  The
procedure @var{proc} is called with the key as the first parameter and
the value as the second parameter.  The procedure @code{table-for-each}
returns an unspecified value.

The order in which the key/value bindings are visited is unspecified
and may vary from one call of @code{table-for-each} to the next.
While a call to @code{table-for-each} is being performed on
@var{table}, it is an error to call any of the following procedures on
@var{table}: @code{table-ref}, @code{table-set!}, @code{table-search},
@code{table-for-each}, and @code{table->list}.  It is also an error to
compare with @code{equal?} (directly or indirectly with @code{member},
@code{assoc}, @code{table-ref}, etc.) an object that contains
@var{table}.  All these procedures may cause @var{table} to be
reordered and resized.  This restriction allows a more efficient
iteration over the key/value bindings.

For example:

@smallexample
> @b{(define square (make-table))}
> @b{(table-set! square 2 4)}
> @b{(table-set! square 3 9)}
> @b{(table-for-each (lambda (k v) (write (list k v)) (newline)) square)}
(2 4)
(3 9)
@end smallexample

@end deffn

@deffn procedure table->list @var{table}

The procedure @code{table->list} returns an association list
containing the key/value bindings in the table @var{table}.  Each
key/value binding yields a pair whose car field is the key and whose
cdr field is the value bound to that key.  The order of the bindings
in the list is unspecified.

For example:

@smallexample
> @b{(define square (make-table))}
> @b{(table-set! square 2 4)}
> @b{(table-set! square 3 9)}
> @b{(table->list square)}
((3 . 9) (2 . 4))
@end smallexample

@end deffn

@deffn procedure list->table @var{list} @r{[}@code{size:} @var{size}@r{]} @r{[}@code{init:} @var{init}@r{]} @r{[}@code{weak-keys:} @var{weak-keys}@r{]} @r{[}@code{weak-values:} @var{weak-values}@r{]} @r{[}@code{test:} @var{test}@r{]} @r{[}@code{hash:} @var{hash}@r{]} @r{[}@code{min-load:} @var{min-load}@r{]} @r{[}@code{max-load:} @var{max-load}@r{]}

The procedure @code{list->table} returns a new table containing the
key/value bindings in the association list @var{list}.  The optional
keyword parameters specify various parameters of the table and have
the same meaning as for the @code{make-table} procedure.

Each element of @var{list} is a pair whose car field is a key and
whose cdr field is the value bound to that key.  If a key appears more
than once in @var{list} (tested using the table's key comparison
procedure) it is the first key/value binding in @var{list} that has
precedence.

For example:

@smallexample
> @b{(define t (list->table '((b . 2) (a . 1) (c . 3) (a . 4))))}
> @b{(table->list t)}
((a . 1) (b . 2) (c . 3))
@end smallexample

@end deffn

@deffn procedure unbound-table-key-exception? @var{obj}
@deffnx procedure unbound-table-key-exception-procedure @var{exc}
@deffnx procedure unbound-table-key-exception-arguments @var{exc}

Unbound-table-key-exception objects are raised by the procedure
@code{table-ref} when the key does not have a binding in the table.
The parameter @var{exc} must be an unbound-table-key-exception object.

The procedure @code{unbound-table-key-exception?} returns
@code{#t} when @var{obj} is a unbound-table-key-exception
object and @code{#f} otherwise.

The procedure @code{unbound-table-key-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{unbound-table-key-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define t (make-table))}
> @b{(define (handler exc)
    (if (unbound-table-key-exception? exc)
        (list (unbound-table-key-exception-procedure exc)
              (unbound-table-key-exception-arguments exc))
        'not-unbound-table-key-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (table-ref t '(1 2))))}
(#<procedure #2 table-ref> (#<table #3> (1 2)))
@end smallexample

@end deffn

@deffn procedure table-copy @var{table}

The procedure @code{table-copy} returns a new table containing the
same key/value bindings as @var{table} and the same table parameters
(i.e. hash procedure, key comparison procedure, key and value
weakness, etc).

For example:

@smallexample
> @b{(define t (list->table '((b . 2) (a . 1) (c . 3))))}
> @b{(define x (table-copy t))}
> @b{(table-set! t 'b 99)}
> @b{(table->list t)}
((a . 1) (b . 99) (c . 3))
> @b{(table->list x)}
((a . 1) (b . 2) (c . 3))
@end smallexample

@end deffn

@deffn procedure table-merge! @var{table1} @var{table2} @r{[}@var{table2-takes-precedence?}@r{]}

The procedure @code{table-merge!} returns @var{table1} after the
key/value bindings contained in @var{table2} have been added to it.
When a key exists both in @var{table1} and @var{table2}, then the
parameter @var{table2-takes-precedence?} indicates which binding will
be kept (the one in @var{table1} if @var{table2-takes-precedence?}  is
false, and the one in @var{table2} otherwise).  If
@var{table2-takes-precedence?} is not specified the binding in
@var{table1} is kept.

For example:

@smallexample
> @b{(define t1 (list->table '((a . 1) (b . 2) (c . 3))))}
> @b{(define t2 (list->table '((a . 4) (b . 5) (z . 6))))}
> @b{(table->list (table-merge! t1 t2))}
((a . 1) (b . 2) (c . 3) (z . 6))
> @b{(define t1 (list->table '((a . 1) (b . 2) (c . 3))))}
> @b{(define t2 (list->table '((a . 4) (b . 5) (z . 6))))}
> @b{(table->list (table-merge! t1 t2 #t))}
((a . 4) (b . 5) (c . 3) (z . 6))
@end smallexample

@end deffn

@deffn procedure table-merge @var{table1} @var{table2} @r{[}@var{table2-takes-precedence?}@r{]}

The procedure @code{table-merge} returns a copy of @var{table1}
(created with @code{table-copy}) to which the key/value bindings
contained in @var{table2} have been added using @code{table-merge!}.
When a key exists both in @var{table1} and @var{table2}, then the
parameter @var{table2-takes-precedence?}  indicates which binding will
be kept (the one in @var{table1} if @var{table2-takes-precedence?}  is
false, and the one in @var{table2} otherwise).  If
@var{table2-takes-precedence?} is not specified the binding in
@var{table1} is kept.

For example:

@smallexample
> @b{(define t1 (list->table '((a . 1) (b . 2) (c . 3))))}
> @b{(define t2 (list->table '((a . 4) (b . 5) (z . 6))))}
> @b{(table->list (table-merge t1 t2))}
((a . 1) (b . 2) (c . 3) (z . 6))
> @b{(table->list (table-merge t1 t2 #t))}
((a . 4) (b . 5) (c . 3) (z . 6))
@end smallexample

@end deffn

@node Records, Threads, Hashing and weak references, Top
@chapter Records

@deffn {special form} define-structure @r{@i{name}} @r{@i{field}}@dots{}

Record data types similar to Pascal records and C @code{struct}
types can be defined using the @code{define-structure} special form.
The identifier @i{name} specifies the name of the new data type.  The
structure name is followed by @var{k} identifiers naming each field of
the record.  The @code{define-structure} expands into a set of definitions
of the following procedures:

@itemize @bullet{}

@item
`@t{make-}@i{name}' -- A @var{k} argument procedure which constructs
a new record from the value of its @var{k} fields.

@item
`@i{name}@t{?}' -- A procedure which tests if its single argument
is of the given record type.

@item
`@i{name}@t{-}@i{field}' -- For each field, a procedure taking
as its single argument a value of the given record type and returning
the content of the corresponding field of the record.

@item
`@i{name}@t{-}@i{field}@t{-set!}' -- For each field, a two
argument procedure taking as its first argument a value of the given
record type.  The second argument gets assigned to the corresponding
field of the record and the void object is returned.

@end itemize

Record data types have a printed representation that includes the name
of the type and the name and value of each field.  Record data types
can not be read by the @code{read} procedure.

For example:

@smallexample
> @b{(define-structure point x y color)}
> @b{(define p (make-point 3 5 'red))}
> @b{p}
#<point #2 x: 3 y: 5 color: red>
> @b{(point-x p)}
3
> @b{(point-color p)}
red
> @b{(point-color-set! p 'black)}
> @b{p}
#<point #2 x: 3 y: 5 color: black>
@end smallexample

@end deffn

@node Threads, Dynamic environment, Records, Top
@chapter Threads
@cindex threads

Gambit supports the execution of multiple Scheme threads.  These
threads are managed entirely by Gambit's runtime and are not related
to the host operating system's threads.  Gambit's runtime does not
currently take advantage of multiprocessors (i.e. at most one thread is
running).

@menu
* Introduction::                  Introduction
* Thread objects::                Thread objects
* Mutex objects::                 Mutex objects
* Condition variable objects::    Condition variable objects
* Fairness::                      Fairness
* Memory coherency::              Memory coherency
* Timeouts::                      Timeouts
* Primordial thread::             Primordial thread
* Procedures::                    Procedures
@end menu

@node Introduction, Thread objects, Threads, Threads
@section Introduction

Multithreading is a paradigm that is well suited for building complex
systems such as: servers, GUIs, and high-level operating systems.
Gambit's thread system offers mechanisms for creating threads of
execution and for synchronizing them.  The thread system also supports
features which are useful in a real-time context, such as priorities,
priority inheritance and timeouts.

The thread system provides the following data types:

@itemize @bullet{}

@item
Thread (a virtual processor which shares object space with all other
threads)

@item
Mutex (a mutual exclusion device, also known as a lock and binary
semaphore)

@item
Condition variable (a set of blocked threads)

@end itemize

@node Thread objects, Mutex objects, Introduction, Threads
@section Thread objects

A @dfn{running thread} is a thread that is currently executing.  A
@dfn{runnable thread} is a thread that is ready to execute or running.
A thread is @dfn{blocked} if it is waiting for a mutex to become
unlocked, an I/O operation to become possible, the end of a ``sleep''
period, etc.  A @dfn{new thread} is a thread that has been allocated
but has not yet been initialized.  An @dfn{initialized thread} is a
thread that can be made runnable.  A new thread becomes runnable when
it is started by calling @code{thread-start!}.  A @dfn{terminated
thread} is a thread that can no longer become runnable (but
@dfn{deadlocked threads} are not considered terminated).  The only
valid transitions between the thread states are from new to
initialized, from initialized to runnable, between runnable and
blocked, and from any state except new to terminated as indicated in
the following diagram:

@smallexample
@b{}                                            @b{unblock}
                          @b{start}            <-------
NEW -------> INITIALIZED -------> RUNNABLE -------> BLOCKED
                       \             |      @b{block}  /
                        \            v            /
                         +-----> TERMINATED <----+
@end smallexample

Each thread has a @dfn{base priority}, which is a real number (where a
higher numerical value means a higher priority), a @dfn{priority boost},
which is a nonnegative real number representing the priority increase
applied to a thread when it blocks, and a @dfn{quantum}, which is a
nonnegative real number representing a duration in seconds.

Each thread has a @dfn{specific field} which can be used in an
application specific way to associate data with the thread (some thread
systems call this ``thread local storage'').

Each thread has a @dfn{mailbox} which is used for inter-thread
communication.

@node Mutex objects, Condition variable objects, Thread objects, Threads
@section Mutex objects

A mutex can be in one of four states: @dfn{locked} (either @dfn{owned}
or @dfn{not owned}) and @dfn{unlocked} (either @dfn{abandoned} or
@dfn{not abandoned}).

An attempt to lock a mutex only succeeds if the mutex is in an unlocked
state, otherwise the current thread will wait.  A mutex in the
locked/owned state has an associated @dfn{owner thread}, which by
convention is the thread that is responsible for unlocking the mutex
(this case is typical of critical sections implemented as ``lock mutex,
perform operation, unlock mutex'').  A mutex in the locked/not-owned
state is not linked to a particular thread.

A mutex becomes locked when a thread locks it using the
@samp{mutex-lock!} primitive.  A mutex becomes unlocked/abandoned when
the owner of a locked/owned mutex terminates.  A mutex becomes
unlocked/not-abandoned when a thread unlocks it using the
@samp{mutex-unlock!} primitive.

The mutex primitives do not implement @dfn{recursive mutex semantics}.
An attempt to lock a mutex that is locked implies that the current
thread waits even if the mutex is owned by the current thread (this can
lead to a deadlock if no other thread unlocks the mutex).

Each mutex has a @dfn{specific field} which can be used in an
application specific way to associate data with the mutex.

@node Condition variable objects, Fairness, Mutex objects, Threads
@section Condition variable objects

A condition variable represents a set of blocked threads.  These blocked
threads are waiting for a certain condition to become true.  When a
thread modifies some program state that might make the condition true,
the thread unblocks some number of threads (one or all depending on the
primitive used) so they can check if the condition is now true.  This
allows complex forms of interthread synchronization to be expressed more
conveniently than with mutexes alone.

Each condition variable has a @dfn{specific field} which can be used in
an application specific way to associate data with the condition
variable.

@node Fairness, Memory coherency, Condition variable objects, Threads
@section Fairness

In various situations the scheduler must select one thread from a set of
threads (e.g. which thread to run when a running thread blocks or
expires its quantum, which thread to unblock when a mutex becomes
unlocked or a condition variable is signaled).  The constraints on the
selection process determine the scheduler's @dfn{fairness}.  The
selection depends on the order in which threads become runnable or
blocked and on the @dfn{priority} attached to the threads.

The definition of fairness requires the notion of time ordering,
i.e. ``event @var{A} occured before event @var{B}''.  For the purpose of
establishing time ordering, the scheduler uses a clock with a discrete,
usually variable, resolution (a ``tick'').  Events occuring in a given
tick can be considered to be simultaneous (i.e. if event @var{A} occured
before event @var{B} in real time, then the scheduler will claim that
event @var{A} occured before event @var{B} unless both events fall
within the same tick, in which case the scheduler arbitrarily chooses a
time ordering).

Each thread @var{T} has three priorities which affect fairness; the
@dfn{base priority}, the @dfn{boosted priority}, and the @dfn{effective
priority}.

@itemize

@item
The @dfn{base priority} is the value contained in @var{T}'s @dfn{base
priority} field (which is set with the @samp{thread-base-priority-set!}
primitive).

@item
@var{T}'s @dfn{boosted flag} field contains a boolean that affects
@var{T}'s @dfn{boosted priority}.  When the boosted flag field is false,
the boosted priority is equal to the base priority, otherwise the
boosted priority is equal to the base priority plus the value contained
in @var{T}'s @dfn{priority boost} field (which is set with the
@samp{thread-priority-boost-set!} primitive).  The boosted flag field is
set to false when a thread is created, when its quantum expires, and
when @dfn{thread-yield!} is called.  The boosted flag field is set to
true when a thread blocks.  By carefully choosing the base priority and
priority boost, relatively to the other threads, it is possible to set
up an interactive thread so that it has good I/O response time without
being a CPU hog when it performs long computations.

@item
The @dfn{effective priority} is equal to the maximum of @var{T}'s
boosted priority and the effective priority of all the threads that are
blocked on a mutex owned by @var{T}.  This @dfn{priority inheritance}
avoids priority inversion problems that would prevent a high priority
thread blocked at the entry of a critical section to progress because a
low priority thread inside the critical section is preempted for an
arbitrary long time by a medium priority thread.

@end itemize

Let @var{P}(@var{T}) be the effective priority of thread @var{T} and
let @var{R}(@var{T}) be the most recent time when one of the following
events occurred for thread @var{T}, thus making it runnable: @var{T}
was started by calling @samp{thread-start!}, @var{T} called
@samp{thread-yield!}, @var{T} expired its quantum, or @var{T} became
unblocked.  Let the relation @var{NL}(@var{T1},@var{T2}), ``@var{T1}
no later than @var{T2}'', be true if
@var{P}(@var{T1})<@var{P}(@var{T2}) or
@var{P}(@var{T1})=@var{P}(@var{T2}) and
@var{R}(@var{T1})>@var{R}(@var{T2}), and false otherwise.  The
scheduler will schedule the execution of threads in such a way that
whenever there is at least one runnable thread, 1) within a finite
time at least one thread will be running, and 2) there is never a pair
of runnable threads @var{T1} and @var{T2} for which
@var{NL}(@var{T1},@var{T2}) is true and @var{T1} is not running and
@var{T2} is running.

A thread @var{T} expires its quantum when an amount of time equal to
@var{T}'s quantum has elapsed since @var{T} entered the running state
and @var{T} did not block, terminate or call @samp{thread-yield!}.
At that point @var{T} exits the running state to allow other threads to
run.  A thread's quantum is thus an indication of the rate of progress
of the thread relative to the other threads of the same priority.
Moreover, the resolution of the timer measuring the running time may
cause a certain deviation from the quantum, so a thread's quantum should
only be viewed as an approximation of the time it can run before
yielding to another thread.

Threads blocked on a given mutex or condition variable will unblock in
an order which is consistent with decreasing priority and increasing
blocking time (i.e. the highest priority thread unblocks first, and
among equal priority threads the one that blocked first unblocks first).

@node Memory coherency, Timeouts, Fairness, Threads
@section Memory coherency

Read and write operations on the store (such as reading and writing a
variable, an element of a vector or a string) are not atomic.  It is
an error for a thread to write a location in the store while some
other thread reads or writes that same location.  It is the
responsibility of the application to avoid write/read and write/write
races through appropriate uses of the synchronization primitives.

Concurrent reads and writes to ports are allowed.  It is the
responsibility of the implementation to serialize accesses to a given
port using the appropriate synchronization primitives.

@node Timeouts, Primordial thread, Memory coherency, Threads
@section Timeouts

All synchronization primitives which take a timeout parameter accept
three types of values as a timeout, with the following meaning:

@itemize

@item
a time object represents an absolute point in time

@item
an exact or inexact real number represents a relative time in
seconds from the moment the primitive was called

@item
@samp{#f} means that there is no timeout

@end itemize

When a timeout denotes the current time or a time in the past, the
synchronization primitive claims that the timeout has been reached
only after the other synchronization conditions have been checked.
Moreover the thread remains running (it does not enter the blocked
state).  For example, @code{(mutex-lock! m 0)} will lock mutex
@code{m} and return @samp{#t} if @code{m} is
currently unlocked, otherwise @samp{#f} is returned because the
timeout is reached.

@node Primordial thread, Procedures, Timeouts, Threads
@section Primordial thread

The execution of a program is initially under the control of a single
thread known as the @dfn{primordial thread}.  The primordial thread has an
unspecified
base priority, priority boost, boosted flag, quantum,
name, specific field, dynamic environment, @samp{dynamic-wind}
stack, and exception-handler.  All threads are terminated when the
primordial thread terminates (normally or not).

@node Procedures, , Primordial thread, Threads
@section Procedures

@deffn procedure current-thread

This procedure returns the current thread.  For example:

@smallexample
> @b{(current-thread)}
#<thread #1 primordial>
> @b{(eq? (current-thread) (current-thread))}
#t
@end smallexample

@end deffn

@deffn procedure thread? @var{obj}

This procedure returns @code{#t} when @var{obj} is a thread object and
@code{#f} otherwise.

For example:

@smallexample
> @b{(thread? (current-thread))}
#t
> @b{(thread? 'foo)}
#f
@end smallexample

@end deffn

@deffn procedure make-thread @var{thunk} @r{[}@var{name} @r{[}@var{thread-group}@r{]}@r{]}
@deffnx procedure make-root-thread @var{thunk} @r{[}@var{name} @r{[}@var{thread-group} @r{[}@var{input-port} @r{[}@var{output-port}@r{]}@r{]}@r{]}@r{]}

The @code{make-thread} procedure creates and returns an initialized
thread.  This thread is not automatically made runnable (the procedure
@code{thread-start!} must be used for this).  A thread has the
following fields: base priority, priority boost, boosted flag,
quantum, name, specific, end-result, end-exception, and a list of
locked/owned mutexes it owns.  The thread's execution consists of a
call to @var{thunk} with the @dfn{initial continuation}.  This
continuation causes the (then) current thread to store the result in
its end-result field, abandon all mutexes it owns, and finally
terminate.  The @samp{dynamic-wind} stack of the initial continuation
is empty.  The optional @var{name} is an arbitrary Scheme object which
identifies the thread (useful for debugging); it defaults to an
unspecified value.  The specific field is set to an unspecified value.
The optional @var{thread-group} indicates which thread group this
thread belongs to; it defaults to the thread group of the current
thread.  The base priority, priority boost, and quantum of the thread
are set to the same value as the current thread and the boosted flag
is set to false.  The thread's mailbox is initially empty.  The thread
inherits the dynamic environment from the current thread. Moreover, in
this dynamic environment the exception-handler is bound to the
@dfn{initial exception-handler} which is a unary procedure which
causes the (then) current thread to store in its end-exception field
an uncaught-exception object whose ``reason'' is the argument of the
handler, abandon all mutexes it owns, and finally terminate.

The @code{make-root-thread} procedure behaves like the
@code{make-thread} procedure except the created thread does not
inherit the dynamic environment from the current thread and the base
priority is set to 0, the priority boost is set to 1.0e-6, and the
quantum is set to 0.02.  The dynamic environment of the thread has the
global bindings of the parameter objects, except
@code{current-input-port} which is bound to @var{input-port},
@code{current-output-port} which is bound to @var{output-port}, and
@code{current-directory} which is bound to the initial current working
directory of the current process.  If @var{input-port} is not
specified it defaults to a port corresponding to the standard input
(@samp{stdin}).  If @var{output-port} is not specified it defaults to
a port corresponding to the standard output (@samp{stdout}).

For example:

@smallexample
> @b{(make-thread (lambda () (write 'hello)))}
#<thread #2>
> @b{(make-root-thread (lambda () (write 'world)) 'a-name)}
#<thread #3 a-name>
@end smallexample

@end deffn

@deffn procedure thread-name @var{thread}

This procedure returns the name of the @var{thread}.  For example:

@smallexample
> @b{(thread-name (make-thread (lambda () #f) 'foo))}
foo
@end smallexample

@end deffn

@deffn procedure thread-specific @var{thread}
@deffnx procedure thread-specific-set! @var{thread} @var{obj}

The @code{thread-specific} procedure returns the content of the
@var{thread}'s specific field.

The @code{thread-specific-set!} procedure stores @var{obj} into the
@var{thread}'s specific field and returns an unspecified value.

For example:

@smallexample
> @b{(thread-specific-set! (current-thread) "hello")}
> @b{(thread-specific (current-thread))}
"hello"
@end smallexample

@end deffn

@deffn procedure thread-base-priority @var{thread}
@deffnx procedure thread-base-priority-set! @var{thread} @var{priority}

The procedure @code{thread-base-priority} returns a real number which
corresponds to the base priority of the @var{thread}.

The procedure @code{thread-base-priority-set!} changes the base
priority of the @var{thread} to @var{priority} and returns an
unspecified value.  The @var{priority} must be a real number.

For example:

@smallexample
> @b{(thread-base-priority-set! (current-thread) 12.3)}
> @b{(thread-base-priority (current-thread))}
12.3
@end smallexample

@end deffn

@deffn procedure thread-priority-boost @var{thread}
@deffnx procedure thread-priority-boost-set! @var{thread} @var{priority-boost}

The procedure @code{thread-priority-boost} returns a real number which
corresponds to the priority boost of the @var{thread}.

The procedure @code{thread-priority-boost-set!} changes the priority
boost of the @var{thread} to @var{priority-boost} and returns an
unspecified value.  The @var{priority-boost} must be a nonnegative
real.

For example:

@smallexample
> @b{(thread-priority-boost-set! (current-thread) 2.5)}
> @b{(thread-priority-boost (current-thread))}
2.5
@end smallexample

@end deffn

@deffn procedure thread-quantum @var{thread}
@deffnx procedure thread-quantum-set! @var{thread} @var{quantum}

The procedure @code{thread-quantum} returns a real number which
corresponds to the quantum of the @var{thread}.

The procedure @code{thread-quantum-set!} changes the quantum of the
@var{thread} to @var{quantum} and returns an unspecified value.  The
@var{quantum} must be a nonnegative real.  A value of zero selects the
smallest quantum supported by the implementation.

For example:

@smallexample
> @b{(thread-quantum-set! (current-thread) 1.5)}
> @b{(thread-quantum (current-thread))}
1.5
> @b{(thread-quantum-set! (current-thread) 0)}
> @b{(thread-quantum (current-thread))}
0.
@end smallexample

@end deffn

@deffn procedure thread-start! @var{thread}

This procedure makes @var{thread} runnable and returns the
@var{thread}.  The @var{thread} must be an initialized thread.

For example:

@smallexample
> @b{(let ((t (thread-start! (make-thread (lambda () (write 'a))))))
    (write 'b)
    (thread-join! t))}
ab> @r{@i{or}} ba>
@end smallexample

NOTE: It is useful to separate thread creation and thread activation
to avoid the race condition that would occur if the created thread
tries to examine a table in which the current thread stores the
created thread.  See the last example of the @code{thread-terminate!}
procedure which contains mutually recursive threads.

@end deffn

@deffn procedure thread-yield!

This procedure causes the current thread to exit the running state as
if its quantum had expired and returns an unspecified value.

For example:

@smallexample
@b{}@r{@i{; a busy loop that avoids being too wasteful of the CPU}}

(let loop ()
  (if (mutex-lock! m 0) @r{@i{; try to lock m but don't block}}
      (begin
        (display "locked mutex m")
        (mutex-unlock! m))
      (begin
        (do-something-else)
        (thread-yield!) @r{@i{; relinquish rest of quantum}}
        (loop))))
@end smallexample

@end deffn

@deffn procedure thread-sleep! @var{timeout}

This procedure causes the current thread to wait until the timeout is
reached and returns an unspecified value.  This blocks the thread only
if @var{timeout} represents a point in the future.  It is an error for
@var{timeout} to be @samp{#f}.

For example:

@smallexample
@b{}@r{@i{; a clock with a gradual drift:}}

(let loop ((x 1))
  (thread-sleep! 1)
  (write x)
  (loop (+ x 1)))

@r{@i{; a clock with no drift:}}

(let ((start (time->seconds (current-time)))
  (let loop ((x 1))
    (thread-sleep! (seconds->time (+ x start)))
    (write x)
    (loop (+ x 1))))
@end smallexample

@end deffn

@deffn procedure thread-terminate! @var{thread}

This procedure causes an abnormal termination of the @var{thread}.  If
the @var{thread} is not already terminated, all mutexes owned by the
@var{thread} become unlocked/abandoned and a
terminated-thread-exception object is stored in the @var{thread}'s
end-exception field.  If @var{thread} is the current thread,
@code{thread-terminate!} does not return.  Otherwise
@code{thread-terminate!} returns an unspecified value; the termination
of the @var{thread} will occur at some point between the calling of
@code{thread-terminate!}  and a finite time in the future (an explicit
thread synchronization is needed to detect termination, see
@code{thread-join!}).

For example:

@smallexample
@b{}(define (amb thunk1 thunk2)
  (let ((result #f)
        (result-mutex (make-mutex))
        (done-mutex (make-mutex)))
    (letrec ((child1
              (make-thread
                (lambda ()
                  (let ((x (thunk1)))
                    (mutex-lock! result-mutex #f #f)
                    (set! result x)
                    (thread-terminate! child2)
                    (mutex-unlock! done-mutex)))))
             (child2
              (make-thread
                (lambda ()
                  (let ((x (thunk2)))
                    (mutex-lock! result-mutex #f #f)
                    (set! result x)
                    (thread-terminate! child1)
                    (mutex-unlock! done-mutex))))))
      (mutex-lock! done-mutex #f #f)
      (thread-start! child1)
      (thread-start! child2)
      (mutex-lock! done-mutex #f #f)
      result)))
@end smallexample

NOTE: This operation must be used carefully because it terminates a
thread abruptly and it is impossible for that thread to perform any
kind of cleanup.  This may be a problem if the thread is in the middle
of a critical section where some structure has been put in an
inconsistent state.  However, another thread attempting to enter this
critical section will raise an abandoned-mutex-exception object
because the mutex is unlocked/abandoned.  This helps avoid observing
an inconsistent state.  Clean termination can be obtained by polling,
as shown in the example below.

For example:

@smallexample
@b{}(define (spawn thunk)
  (let ((t (make-thread thunk)))
    (thread-specific-set! t #t)
    (thread-start! t)
    t))

(define (stop! thread)
  (thread-specific-set! thread #f)
  (thread-join! thread))

(define (keep-going?)
  (thread-specific (current-thread)))

(define count!
  (let ((m (make-mutex))
        (i 0))
    (lambda ()
      (mutex-lock! m)
      (let ((x (+ i 1)))
        (set! i x)
        (mutex-unlock! m)
        x))))

(define (increment-forever!)
  (let loop () (count!) (if (keep-going?) (loop))))

(let ((t1 (spawn increment-forever!))
      (t2 (spawn increment-forever!)))
  (thread-sleep! 1)
  (stop! t1)
  (stop! t2)
  (count!))  ==>  377290
@end smallexample

@end deffn

@deffn procedure thread-join! thread @r{[}@var{timeout} @r{[}@var{timeout-val}@r{]}@r{]}

This procedure causes the current thread to wait until the
@var{thread} terminates (normally or not) or until the timeout is
reached if @var{timeout} is supplied.  If the timeout is reached,
@var{thread-join!} returns @var{timeout-val} if it is supplied,
otherwise a join-timeout-exception object is raised.  If the
@var{thread} terminated normally, the content of the end-result field
is returned, otherwise the content of the end-exception field is
raised.

For example:

@smallexample
@b{}(let ((t (thread-start! (make-thread (lambda () (expt 2 100))))))
  (do-something-else)
  (thread-join! t))  ==>  1267650600228229401496703205376

(let ((t (thread-start! (make-thread (lambda () (raise 123))))))
  (do-something-else)
  (with-exception-handler
    (lambda (exc)
      (if (uncaught-exception? exc)
          (* 10 (uncaught-exception-reason exc))
          99999))
    (lambda ()
      (+ 1 (thread-join! t)))))  ==>  1231

(define thread-alive?
  (let ((unique (list 'unique)))
    (lambda (thread)
      ; Note: this procedure raises an exception if
      ; the thread terminated abnormally.
      (eq? (thread-join! thread 0 unique) unique))))

(define (wait-for-termination! thread)
  (let ((eh (current-exception-handler)))
    (with-exception-handler
      (lambda (exc)
        (if (not (or (terminated-thread-exception? exc)
                     (uncaught-exception? exc)))
            (eh exc))) ; unexpected exceptions are handled by eh
      (lambda ()
        ; The following call to thread-join! will wait until the
        ; thread terminates.  If the thread terminated normally
        ; thread-join! will return normally.  If the thread
        ; terminated abnormally then one of these two exception
        ; objects is raised by thread-join!:
        ;   - terminated-thread-exception object
        ;   - uncaught-exception object
        (thread-join! thread)
        #f)))) ; ignore result of thread-join!
@end smallexample

@end deffn

@deffn procedure thread-send @var{thread} @var{msg}

Each thread has a mailbox which stores messages delivered to the
thread in the order delivered.

The procedure @code{thread-send} adds the message @var{msg} at the end
of the mailbox of thread @var{thread} and returns an unspecified
value.

For example:

@smallexample
> @b{(thread-send (current-thread) 111)}
> @b{(thread-send (current-thread) 222)}
> @b{(thread-receive)}
111
> @b{(thread-receive)}
222
@end smallexample

@end deffn

@deffn procedure thread-receive @r{[}@var{timeout} @r{[}@var{default}@r{]}@r{]}
@deffnx procedure thread-mailbox-next @r{[}@var{timeout} @r{[}@var{default}@r{]}@r{]}
@deffnx procedure thread-mailbox-rewind
@deffnx procedure thread-mailbox-extract-and-rewind

To allow a thread to examine the messages in its mailbox without
removing them from the mailbox, each thread has a @dfn{mailbox cursor}
which normally points to the last message accessed in the mailbox.
When a mailbox cursor is rewound using the procedure
@code{thread-mailbox-rewind} or
@code{thread-mailbox-extract-and-rewind} or @code{thread-receive}, the
cursor does not point to a message, but the next call to
@code{thread-receive} and @code{thread-mailbox-next} will set the
cursor to the oldest message in the mailbox.

The procedure @code{thread-receive} advances the mailbox cursor of the
current thread to the next message, removes that message from the
mailbox, rewinds the mailbox cursor, and returns the message.  When
@var{timeout} is not specified, the current thread will wait until a
message is available in the mailbox.  When @var{timeout} is specified
and @var{default} is not specified, a
mailbox-receive-timeout-exception object is raised if the timeout is
reached before a message is available.  When @var{timeout} is
specified and @var{default} is specified, @var{default} is returned if
the timeout is reached before a message is available.

The procedure @code{thread-mailbox-next} behaves like
@code{thread-receive} except that the message remains in the mailbox
and the mailbox cursor is not rewound.

The procedures @code{thread-mailbox-rewind} or
@code{thread-mailbox-extract-and-rewind} rewind the mailbox cursor of
the current thread so that the next call to @code{thread-mailbox-next}
and @code{thread-receive} will access the oldest message in the
mailbox.  Additionally the procedure
@code{thread-mailbox-extract-and-rewind} will remove from the mailbox
the message most recently accessed by a call to
@code{thread-mailbox-next}.  When @code{thread-mailbox-next} has not
been called since the last call to @code{thread-receive} or
@code{thread-mailbox-rewind} or
@code{thread-mailbox-extract-and-rewind}, a call to
@code{thread-mailbox-extract-and-rewind} only resets the mailbox
cursor (no message is removed).

For example:

@smallexample
> @b{(thread-send (current-thread) 111)}
> @b{(thread-receive 1 999)}
111
> @b{(thread-send (current-thread) 222)}
> @b{(thread-send (current-thread) 333)}
> @b{(thread-mailbox-next 1 999)}
222
> @b{(thread-mailbox-next 1 999)}
333
> @b{(thread-mailbox-next 1 999)}
999
> @b{(thread-mailbox-extract-and-rewind)}
> @b{(thread-receive 1 999)}
222
> @b{(thread-receive 1 999)}
999
@end smallexample

@end deffn

@deffn procedure mailbox-receive-timeout-exception? @var{obj}
@deffnx procedure mailbox-receive-timeout-exception-procedure @var{exc}
@deffnx procedure mailbox-receive-timeout-exception-arguments @var{exc}

Mailbox-receive-timeout-exception objects are raised by the procedures
@code{thread-receive} and @code{thread-mailbox-next} when a timeout
expires before a message is available and no default value is
specified.  The parameter @var{exc} must be a
mailbox-receive-timeout-exception object.

The procedure @code{mailbox-receive-timeout-exception?} returns
@code{#t} when @var{obj} is a mailbox-receive-timeout-exception
object and @code{#f} otherwise.

The procedure @code{mailbox-receive-timeout-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{mailbox-receive-timeout-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (mailbox-receive-timeout-exception? exc)
        (list (mailbox-receive-timeout-exception-procedure exc)
              (mailbox-receive-timeout-exception-arguments exc))
        'not-mailbox-receive-timeout-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (thread-receive 1)))}
(#<procedure #2 thread-receive> (1))
@end smallexample

@end deffn

@deffn procedure mutex? @var{obj}

This procedure returns @code{#t} when @var{obj} is a mutex object and
@code{#f} otherwise.

For example:

@smallexample
> @b{(mutex? (make-mutex))}
#t
> @b{(mutex? 'foo)}
#f
@end smallexample

@end deffn

@deffn procedure make-mutex @r{[}@var{name}@r{]}

This procedure returns a new mutex in the unlocked/not-abandoned
state.  The optional @var{name} is an arbitrary Scheme object which
identifies the mutex (useful for debugging); it defaults to an
unspecified value.  The mutex's specific field is set to an
unspecified value.

For example:

@smallexample
> @b{(make-mutex)}
#<mutex #2>
> @b{(make-mutex 'foo)}
#<mutex #3 foo>
@end smallexample

@end deffn

@deffn procedure mutex-name @var{mutex}

Returns the name of the @var{mutex}.  For example:

@smallexample
> @b{(mutex-name (make-mutex 'foo))}
foo
@end smallexample

@end deffn

@deffn procedure mutex-specific @var{mutex}
@deffnx procedure mutex-specific-set! @var{mutex} @var{obj}

The @code{mutex-specific} procedure returns the content of the
@var{mutex}'s specific field.

The @code{mutex-specific-set!} procedure stores @var{obj} into the
@var{mutex}'s specific field and returns an unspecified value.

For example:

@smallexample
> @b{(define m (make-mutex))}
> @b{(mutex-specific-set! m "hello")}
> @b{(mutex-specific m)}
"hello"
> @b{(define (mutex-lock-recursively! mutex)
    (if (eq? (mutex-state mutex) (current-thread))
        (let ((n (mutex-specific mutex)))
          (mutex-specific-set! mutex (+ n 1)))
        (begin
          (mutex-lock! mutex)
          (mutex-specific-set! mutex 0))))}
> @b{(define (mutex-unlock-recursively! mutex)
    (let ((n (mutex-specific mutex)))
      (if (= n 0)
          (mutex-unlock! mutex)
          (mutex-specific-set! mutex (- n 1)))))}
> @b{(mutex-lock-recursively! m)}
> @b{(mutex-lock-recursively! m)}
> @b{(mutex-lock-recursively! m)}
> @b{(mutex-specific m)}
2
@end smallexample

@end deffn

@deffn procedure mutex-state @var{mutex}

Thos procedure returns information about the state of the @var{mutex}.
The possible results are:

@itemize

@item thread @var{T}:
the @var{mutex} is in the locked/owned state
and thread @var{T} is the owner of the @var{mutex}

@item symbol @code{not-owned}:
the @var{mutex} is in the locked/not-owned state

@item symbol @code{abandoned}:
the @var{mutex} is in the unlocked/abandoned
state

@item symbol @code{not-abandoned}:
the @var{mutex} is in the unlocked/not-abandoned
state

@end itemize

For example:

@smallexample
@b{}(mutex-state (make-mutex))  ==>  not-abandoned

(define (thread-alive? thread)
  (let ((mutex (make-mutex)))
    (mutex-lock! mutex #f thread)
    (let ((state (mutex-state mutex)))
      (mutex-unlock! mutex) ; avoid space leak
      (eq? state thread))))
@end smallexample

@end deffn

@deffn procedure mutex-lock! @var{mutex} @r{[}@var{timeout} @r{[}@var{thread}@r{]}@r{]}

This procedure locks @var{mutex}.  If the @var{mutex} is currently
locked, the current thread waits until the @var{mutex} is unlocked, or
until the timeout is reached if @var{timeout} is supplied.  If the
timeout is reached, @code{mutex-lock!} returns @samp{#f}.  Otherwise,
the state of the @var{mutex} is changed as follows:

@itemize

@item if @var{thread} is @samp{#f} the
@var{mutex} becomes locked/not-owned,

@item otherwise, let @var{T} be @var{thread} (or the
current thread if @var{thread} is not
supplied),

@itemize

@item if @var{T} is terminated the @var{mutex}
becomes unlocked/abandoned,

@item otherwise @var{mutex} becomes locked/owned
with @var{T} as the owner.

@end itemize

@end itemize

After changing the state of the @var{mutex}, an
abandoned-mutex-exception object is raised if the @var{mutex} was
unlocked/abandoned before the state change, otherwise
@code{mutex-lock!} returns @samp{#t}.  It is not an error if the
@var{mutex} is owned by the current thread (but the current thread
will have to wait).

For example:

@smallexample
@b{}; an implementation of a mailbox object of depth one; this
; implementation does not behave well in the presence of forced
; thread terminations using thread-terminate! (deadlock can occur
; if a thread is terminated in the middle of a put! or get! operation)

(define (make-empty-mailbox)
  (let ((put-mutex (make-mutex)) ; allow put! operation
        (get-mutex (make-mutex))
        (cell #f))

    (define (put! obj)
      (mutex-lock! put-mutex #f #f) ; prevent put! operation
      (set! cell obj)
      (mutex-unlock! get-mutex)) ; allow get! operation

    (define (get!)
      (mutex-lock! get-mutex #f #f) ; wait until object in mailbox
      (let ((result cell))
        (set! cell #f) ; prevent space leaks
        (mutex-unlock! put-mutex) ; allow put! operation
        result))

    (mutex-lock! get-mutex #f #f) ; prevent get! operation

    (lambda (msg)
      (case msg
        ((put!) put!)
        ((get!) get!)
        (else (error "unknown message"))))))

(define (mailbox-put! m obj) ((m 'put!) obj))
(define (mailbox-get! m) ((m 'get!)))

; an alternate implementation of thread-sleep!

(define (sleep! timeout)
  (let ((m (make-mutex)))
    (mutex-lock! m #f #f)
    (mutex-lock! m timeout #f)))

; a procedure that waits for one of two mutexes to unlock

(define (lock-one-of! mutex1 mutex2)
  ; this procedure assumes that neither mutex1 or mutex2
  ; are owned by the current thread
  (let ((ct (current-thread))
        (done-mutex (make-mutex)))
    (mutex-lock! done-mutex #f #f)
    (let ((t1 (thread-start!
               (make-thread
                (lambda ()
                  (mutex-lock! mutex1 #f ct)
                  (mutex-unlock! done-mutex)))))
          (t2 (thread-start!
               (make-thread
                (lambda ()
                  (mutex-lock! mutex2 #f ct)
                  (mutex-unlock! done-mutex))))))
      (mutex-lock! done-mutex #f #f)
      (thread-terminate! t1)
      (thread-terminate! t2)
      (if (eq? (mutex-state mutex1) ct)
          (begin
            (if (eq? (mutex-state mutex2) ct)
                (mutex-unlock! mutex2)) ; don't lock both
            mutex1)
          mutex2))))
@end smallexample

@end deffn

@deffn procedure mutex-unlock! @var{mutex} @r{[}@var{condition-variable} @r{[}@var{timeout}@r{]}@r{]}

This procedure unlocks the @var{mutex} by making it
unlocked/not-abandoned.  It is not an error to unlock an unlocked
mutex and a mutex that is owned by any thread.  If
@var{condition-variable} is supplied, the current thread is blocked
and added to the @var{condition-variable} before unlocking
@var{mutex}; the thread can unblock at any time but no later than when
an appropriate call to @code{condition-variable-signal!} or
@code{condition-variable-broadcast!} is performed (see below), and no
later than the timeout (if @var{timeout} is supplied).  If there are
threads waiting to lock this @var{mutex}, the scheduler selects a
thread, the mutex becomes locked/owned or locked/not-owned, and the
thread is unblocked.  @code{mutex-unlock!} returns @samp{#f} when the
timeout is reached, otherwise it returns @samp{#t}.

NOTE: The reason the thread can unblock at any time (when
@var{condition-variable} is supplied) is that the scheduler, when it
detects a serious problem such as a deadlock, must interrupt one of
the blocked threads (such as the primordial thread) so that it can
perform some appropriate action.  After a thread blocked on a
condition-variable has handled such an interrupt it would be wrong for
the scheduler to return the thread to the blocked state, because any
calls to @code{condition-variable-broadcast!} during the interrupt
will have gone unnoticed.  It is necessary for the thread to remain
runnable and return from the call to @code{mutex-unlock!} with a
result of @samp{#t}.

NOTE: @code{mutex-unlock!} is related to the ``wait'' operation on
condition variables available in other thread systems.  The main
difference is that ``wait'' automatically locks @var{mutex} just
after the thread is unblocked.  This operation is not performed by
@code{mutex-unlock!} and so must be done by an explicit call to
@code{mutex-lock!}.  This has the advantages that a different timeout
and exception-handler can be specified on the @code{mutex-lock!} and
@code{mutex-unlock!} and the location of all the mutex operations is
clearly apparent.

For example:

@smallexample
@b{}(let loop ()
  (mutex-lock! m)
  (if (condition-is-true?)
      (begin
        (do-something-when-condition-is-true)
        (mutex-unlock! m))
      (begin
        (mutex-unlock! m cv)
        (loop))))
@end smallexample

@end deffn

@deffn procedure condition-variable? @var{obj}

This procedure returns @code{#t} when @var{obj} is a
condition-variable object and @code{#f} otherwise.

For example:

@smallexample
> @b{(condition-variable? (make-condition-variable))}
#t
> @b{(condition-variable? 'foo)}
#f
@end smallexample

@end deffn

@deffn procedure make-condition-variable @r{[}@var{name}@r{]}

This procedure returns a new empty condition variable.  The optional
@var{name} is an arbitrary Scheme object which identifies the
condition variable (useful for debugging); it defaults to an
unspecified value.  The condition variable's specific field is set to
an unspecified value.

For example:

@smallexample
> @b{(make-condition-variable)}
#<condition-variable #2>
@end smallexample

@end deffn

@deffn procedure condition-variable-name @var{condition-variable}

This procedure returns the name of the @var{condition-variable}.  For
example:

@smallexample
> @b{(condition-variable-name (make-condition-variable 'foo))}
foo
@end smallexample

@end deffn

@deffn procedure condition-variable-specific @var{condition-variable}
@deffnx procedure condition-variable-specific-set! @var{condition-variable} @var{obj}

The @code{condition-variable-specific} procedure returns the content
of the @var{condition-variable}'s specific field.

The @code{condition-variable-specific-set!} procedure stores @var{obj}
into the @var{condition-variable}'s specific field and returns
an unspecified value.

For example:

@smallexample
> @b{(define cv (make-condition-variable))}
> @b{(condition-variable-specific-set! cv "hello")}
> @b{(condition-variable-specific cv)}
"hello"
@end smallexample

@end deffn

@deffn procedure condition-variable-signal! @var{condition-variable}

This procedure unblocks a thread blocked on the
@var{condition-variable} (if there is at least one) and returns an
unspecified value.

For example:

@smallexample
@b{}; an implementation of a mailbox object of depth one; this
; implementation behaves gracefully when threads are forcibly
; terminated using thread-terminate! (an abandoned-mutex-exception
; object will be raised when a put! or get! operation is attempted
; after a thread is terminated in the middle of a put! or get!
; operation)

(define (make-empty-mailbox)
  (let ((mutex (make-mutex))
        (put-condvar (make-condition-variable))
        (get-condvar (make-condition-variable))
        (full? #f)
        (cell #f))

    (define (put! obj)
      (mutex-lock! mutex)
      (if full?
          (begin
            (mutex-unlock! mutex put-condvar)
            (put! obj))
          (begin
            (set! cell obj)
            (set! full? #t)
            (condition-variable-signal! get-condvar)
            (mutex-unlock! mutex))))

    (define (get!)
      (mutex-lock! mutex)
      (if (not full?)
          (begin
            (mutex-unlock! mutex get-condvar)
            (get!))
          (let ((result cell))
            (set! cell #f) ; avoid space leaks
            (set! full? #f)
            (condition-variable-signal! put-condvar)
            (mutex-unlock! mutex)
            result)))

    (lambda (msg)
      (case msg
        ((put!) put!)
        ((get!) get!)
        (else (error "unknown message"))))))

(define (mailbox-put! m obj) ((m 'put!) obj))
(define (mailbox-get! m) ((m 'get!)))
@end smallexample

@end deffn

@deffn procedure condition-variable-broadcast! @var{condition-variable}

This procedure unblocks all the thread blocked on the
@var{condition-variable} and returns an unspecified value.

For example:

@smallexample
@b{}(define (make-semaphore n)
  (vector n (make-mutex) (make-condition-variable)))

(define (semaphore-wait! sema)
  (mutex-lock! (vector-ref sema 1))
  (let ((n (vector-ref sema 0)))
    (if (> n 0)
        (begin
          (vector-set! sema 0 (- n 1))
          (mutex-unlock! (vector-ref sema 1)))
        (begin
          (mutex-unlock! (vector-ref sema 1) (vector-ref sema 2))
          (semaphore-wait! sema))))

(define (semaphore-signal-by! sema increment)
  (mutex-lock! (vector-ref sema 1))
  (let ((n (+ (vector-ref sema 0) increment)))
    (vector-set! sema 0 n)
    (if (> n 0)
        (condition-variable-broadcast! (vector-ref sema 2)))
    (mutex-unlock! (vector-ref sema 1))))
@end smallexample

@end deffn

@node Dynamic environment, Exceptions, Threads, Top
@chapter Dynamic environment

The @dfn{dynamic environment} is the structure which allows the system
to find the value returned by the standard procedures
@code{current-input-port} and @code{current-output-port}.  The
standard procedures @code{with-input-from-file} and
@code{with-output-to-file} extend the dynamic environment to produce a
new dynamic environment which is in effect for the dynamic extent of
the call to the thunk passed as their last argument.  These procedures
are essentially special purpose dynamic binding operations on hidden
dynamic variables (one for @code{current-input-port} and one for
@code{current-output-port}).  Gambit generalizes this dynamic binding
mechanism to allow the user to introduce new dynamic variables, called
@dfn{parameter objects}, and dynamically bind them.  The parameter
objects implemented by Gambit are compatible with the specification of
the ``Parameter objects SRFI'' (SRFI 39).

One important issue is the relationship between the dynamic
environments of the parent and child threads when a thread is created.
Each thread has its own dynamic environment that is accessed when
looking up the value bound to a parameter object by that thread.  When
a thread's dynamic environment is extended it does not affect the
dynamic environment of other threads.  When a thread is created it is
given a dynamic environment whose bindings are inherited from the
parent thread.  In this inherited dynamic environment the parameter
objects are bound to the same cells as the parent's dynamic
environment (in other words an assignment of a new value to a
parameter object is visible in the other thread).

Another important issue is the interaction between the
@code{dynamic-wind} procedure and dynamic environments.  When a thread
creates a continuation, the thread's dynamic environment and the
@samp{dynamic-wind} stack are saved within the continuation (an
alternate but equivalent point of view is that the @samp{dynamic-wind}
stack is part of the dynamic environment).  When this continuation is
invoked the required @samp{dynamic-wind} before and after thunks are
called and the saved dynamic environment is reinstated as the dynamic
environment of the current thread.  During the call to each required
@samp{dynamic-wind} before and after thunk, the dynamic environment
and the @samp{dynamic-wind} stack in effect when the corresponding
@samp{dynamic-wind} was executed are reinstated.  Note that this
specification precisely defines the semantics of calling
@samp{call-with-current-continuation} or invoking a continuation
within a before or after thunk.  The semantics are well defined even
when a continuation created by another thread is invoked.  Below is an
example exercising the subtleties of this semantics.

@smallexample
@b{}(with-output-to-file
 "foo"
 (lambda ()
   (let ((k (call-with-current-continuation
             (lambda (exit)
               (with-output-to-file
                "bar"
                (lambda ()
                  (dynamic-wind
                   (lambda ()
                     (write '(b1))
                     (force-output))
                   (lambda ()
                     (let ((x (call-with-current-continuation
                               (lambda (cont) (exit cont)))))
                       (write '(t1))
                       (force-output)
                       x))
                   (lambda ()
                     (write '(a1))
                     (force-output)))))))))
     (if k
         (dynamic-wind
          (lambda ()
            (write '(b2))
            (force-output))
          (lambda ()
            (with-output-to-file
             "baz"
             (lambda ()
               (write '(t2))
               (force-output)
               ; go back inside (with-output-to-file "bar" ...)
               (k #f))))
          (lambda ()
            (write '(a2))
            (force-output)))))))
@end smallexample

The following actions will occur when this code is executed:
@code{(b1)(a1)} is written to ``bar'', @code{(b2)} is then written to
``foo'', @code{(t2)} is then written to ``baz'', @code{(a2)} is then
written to ``foo'', and finally @code{(b1)(t1)(a1)} is written to
``bar''.

@deffn procedure make-parameter @var{obj} @r{[}@var{filter}@r{]}

The dynamic environment is composed of two parts: the @dfn{local
dynamic environment} and the @dfn{global dynamic environment}.  There
is a single global dynamic environment, and it is used to lookup
parameter objects that can't be found in the local dynamic
environment.

The @code{make-parameter} procedure returns a new @dfn{parameter
object}.  The @var{filter} argument is a one argument conversion
procedure.  If it is not specified, @var{filter} defaults to the
identity function.

The global dynamic environment is updated to associate the parameter
object to a new cell.  The initial content of the cell is the result
of applying the conversion procedure to @var{obj}.

A parameter object is a procedure which accepts zero or one argument.
The cell bound to a particular parameter object in the dynamic
environment is accessed by calling the parameter object.  When no
argument is passed, the content of the cell is returned.  When one
argument is passed the content of the cell is updated with the result
of applying the parameter object's conversion procedure to the
argument.  Note that the conversion procedure can be used for
guaranteeing the type of the parameter object's binding and/or to
perform some conversion of the value.

For example:

@smallexample
> @b{(define radix (make-parameter 10))}
> @b{(radix)}
10
> @b{(radix 2)}
> @b{(radix)}
2
> @b{(define prompt
    (make-parameter
      123
      (lambda (x)
        (if (string? x)
            x
            (object->string x)))))}
> @b{(prompt)}
"123"
> @b{(prompt "$")}
> @b{(prompt)}
"$"
> @b{(define write-shared
    (make-parameter
      #f
      (lambda (x)
        (if (boolean? x)
            x
            (error "only booleans are accepted by write-shared")))))}
> @b{(write-shared 123)}
*** ERROR IN ##make-parameter -- only booleans are accepted by write-shared
@end smallexample

@end deffn

@deffn {special form} parameterize ((@r{@i{procedure}} @r{@i{value}})@dots{}) @r{@i{body}}

The @code{parameterize} form, evaluates all @i{procedure} and
@i{value} expressions in an unspecified order.  All the
@i{procedure} expressions must evaluate to procedures, either parameter
objects or procedures accepting zero and one argument.  Then,
for each procedure @i{p} and in an unspecified order:

@itemize

@item
If @i{p} is a parameter object a new cell is created, initialized, and
bound to the parameter object in the local dynamic environment.  The
value contained in the cell is the result of applying the parameter
object's conversion procedure to @i{value}.  The resulting dynamic
environment is then used for processing the remaining bindings (or the
evaluation of @i{body} if there are no other bindings).

@item
Otherwise @i{p} will be used according to the following protocol: we
say that the call @code{(@r{@i{p}})} ``gets @i{p}'s value'' and that
the call @code{(@r{@i{p}} @r{@i{x}})} ``sets @i{p}'s value to @i{x}''.
First, the @code{parameterize} form gets @i{p}'s value and saves it in
a local variable.  It then sets @i{p}'s value to @i{value}.  It then
processes the remaining bindings (or evaluates @i{body} if there are
no other bindings).  Then it sets @i{p}'s value to the saved value.
These steps are performed in a @code{dynamic-wind} so that it is
possible to use continuations to jump into and out of the body
(i.e. the @code{dynamic-wind}'s before thunk sets @i{p}'s value to
@i{value} and the after thunk sets @i{p}'s value to the saved value).

@end itemize

The result(s) of the @code{parameterize} form are the result(s) of the
@i{body}.

Note that using procedures instead of parameter objects may lead to
unexpected results in multithreaded programs because the before and
after thunks of the @code{dynamic-wind} are not called when control
switches between threads.

For example:

@smallexample
> @b{(define radix (make-parameter 2))}
> @b{(define prompt
    (make-parameter
      123
      (lambda (x)
        (if (string? x)
            x
            (object->string x)))))}
> @b{(radix)}
2
> @b{(parameterize ((radix 16)) (radix))}
16
> @b{(radix)}
2
> @b{(define (f n) (number->string n (radix)))}
> @b{(f 10)}
"1010"
> @b{(parameterize ((radix 8)) (f 10))}
"12"
> @b{(parameterize ((radix 8) (prompt (f 10))) (prompt))}
"1010"
> @b{(define p
    (let ((x 1))
      (lambda args
        (if (null? args) x (set! x (car args))))))}
> @b{(let* ((a (p))
         (b (parameterize ((p 2)) (list (p))))
         (c (p)))
    (list a b c))}
(1 (2) 1)
@end smallexample

@end deffn

@node Exceptions, Host environment, Dynamic environment, Top
@chapter Exceptions

@menu
* Exception-handling::                                      Exception-handling
* Exception objects related to memory management::          Exception objects related to memory management
* Exception objects related to the host environment::       Exception objects related to the host environment
* Exception objects related to threads::                    Exception objects related to threads
* Exception objects related to C-interface::                Exception objects related to C-interface
* Exception objects related to the reader::                 Exception objects related to the reader
* Exception objects related to evaluation and compilation:: Exception objects related to evaluation and compilation
* Exception objects related to type checking::              Exception objects related to type checking
* Exception objects related to procedure call::             Exception objects related to procedure call
* Other exception objects::                                 Other exception objects
@end menu

@node Exception-handling, Exception objects related to memory management, Exceptions, Exceptions
@section Exception-handling

Gambit's exception-handling model is inspired from the withdrawn
``Exception Handling SRFI'' (SRFI 12), the ``Multithreading support
SRFI'' (SRFI 18), and the ``Exception Handling for Programs SRFI''
(SRFI 34).  The two fundamental operations are the dynamic binding of
an exception handler (i.e. the procedure
@code{with-exception-handler}) and the invocation of the exception
handler (i.e. the procedure @code{raise}).

All predefined procedures which check for errors (including type
errors, memory allocation errors, host operating-system errors, etc)
report these errors using the exception-handling system (i.e. they
``raise'' an exception that can be handled in a user-defined exception
handler).  When an exception is raised and the exception is not
handled by a user-defined exception handler, the predefined exception
handler will display an error message (if the primordial thread raised
the exception) or the thread will silently terminate with no error
message (if it is not the primordial thread that raised the
exception).  This default behavior can be changed through the
@samp{-:d} runtime option (@pxref{Runtime options}).

Predefined procedures normally raise exceptions by performing a
tail-call to the exception handler (the exceptions are ``complex''
procedures such as @code{eval}, @code{compile-file}, @code{read},
@code{write}, etc).  This means that the continuation of the exception
handler and of the REPL that may be started due to this is normally
the continuation of the predefined procedure that raised the
exception.  By exiting the REPL with the @code{,(c @var{expression})}
command it is thus possible to resume the program as though the call
to the predefined procedure returned the value of @var{expression}.
For example:

@smallexample
> @b{(define (f x) (+ (car x) 1))}
> @b{(f 2) @r{@i{; typo... we meant to say (f '(2))}}}
*** ERROR IN f, (console)@@1.18 -- (Argument 1) PAIR expected
(car 2)
1> @b{,(c 2)}
3
@end smallexample

@deffn procedure current-exception-handler @r{[}@var{new-exception-handler}@r{]}

@cindex current exception-handler
The parameter object @code{current-exception-handler} is bound to the
current exception-handler.  Calling this procedure with no argument
returns the current exception-handler and calling this procedure with
one argument sets the current exception-handler to
@var{new-exception-handler}.

For example:

@smallexample
> @b{(current-exception-handler)}
#<procedure #2 primordial-exception-handler>
> @b{(current-exception-handler (lambda (exc) (pp exc) 999))}
> @b{(/ 1 0)}
#<divide-by-zero-exception #3>
999
@end smallexample

@end deffn

@deffn procedure with-exception-handler @var{handler} @var{thunk}

Returns the result(s) of calling @var{thunk} with no arguments.  The
@var{handler}, which must be a procedure, is installed as the current
exception-handler in the dynamic environment in effect during the call
to @var{thunk}.  Note that the dynamic environment in effect during
the call to @var{handler} has @var{handler} as the exception-handler.
Consequently, an exception raised during the call to @var{handler} may
lead to an infinite loop.

For example:

@smallexample
> @b{(with-exception-handler
    (lambda (e) (write e) 5)
    (lambda () (+ 1 (* 2 3) 4)))}
11
> @b{(with-exception-handler
    (lambda (e) (write e) 5)
    (lambda () (+ 1 (* 'foo 3) 4)))}
#<type-exception #2>10
> @b{(with-exception-handler
    (lambda (e) (write e 9))
    (lambda () (+ 1 (* 'foo 3) 4)))}
@var{infinite loop}
@end smallexample

@end deffn

@deffn procedure with-exception-catcher @var{handler} @var{thunk}

Returns the result(s) of calling @var{thunk} with no arguments.  A new
exception-handler is installed as the current exception-handler in the
dynamic environment in effect during the call to @var{thunk}.  This
new exception-handler will call the @var{handler}, which must be a
procedure, with the exception object as an argument and with the same
continuation as the call to @code{with-exception-catcher}.  This
implies that the dynamic environment in effect during the call to
@var{handler} is the same as the one in effect at the call to
@code{with-exception-catcher}.  Consequently, an exception raised
during the call to @var{handler} will not lead to an infinite loop.

For example:

@smallexample
> @b{(with-exception-catcher
    (lambda (e) (write e) 5)
    (lambda () (+ 1 (* 2 3) 4)))}
11
> @b{(with-exception-catcher
    (lambda (e) (write e) 5)
    (lambda () (+ 1 (* 'foo 3) 4)))}
#<type-exception #2>5
> @b{(with-exception-catcher
    (lambda (e) (write e 9))
    (lambda () (+ 1 (* 'foo 3) 4)))}
*** ERROR IN (console)@@7.1 -- (Argument 2) OUTPUT PORT expected
(write '#<type-exception #3> 9)
@end smallexample

@end deffn

@deffn procedure raise @var{obj}

This procedure tail-calls the current exception-handler with @var{obj}
as the sole argument.  If the exception-handler returns, the
continuation of the call to @code{raise} is invoked.

For example:

@smallexample
> @b{(with-exception-handler
    (lambda (exc)
      (pp exc)
      100)
    (lambda ()
      (+ 1 (raise "hello"))))}
"hello"
101
@end smallexample

@end deffn

@deffn procedure abort @var{obj}
@deffnx procedure noncontinuable-exception? @var{obj}
@deffnx procedure noncontinuable-exception-reason @var{exc}

The procedure @code{abort} calls the current exception-handler with
@var{obj} as the sole argument.  If the exception-handler returns, the
procedure @code{abort} will be tail-called with a
noncontinuable-exception object, whose reason field is @var{obj}, as
sole argument.

Noncontinuable-exception objects are raised by the @code{abort}
procedure when the exception-handler returns.  The parameter @var{exc}
must be a noncontinuable-exception object.

The procedure @code{noncontinuable-exception?} returns
@code{#t} when @var{obj} is a noncontinuable-exception
object and @code{#f} otherwise.

The procedure @code{noncontinuable-exception-reason} returns the
argument of the call to @code{abort} that raised @var{exc}.

For example:

@smallexample
> @b{(call-with-current-continuation
    (lambda (k)
      (with-exception-handler
        (lambda (exc)
          (pp exc)
          (if (noncontinuable-exception? exc)
              (k (list (noncontinuable-exception-reason exc)))
              100))
        (lambda ()
          (+ 1 (abort "hello"))))))}
"hello"
#<noncontinuable-exception #2>
("hello")
@end smallexample

@end deffn

@node Exception objects related to memory management, Exception objects related to the host environment, Exception-handling, Exceptions
@section Exception objects related to memory management

@deffn procedure heap-overflow-exception? @var{obj}

Heap-overflow-exception objects are raised when the allocation of an
object would cause the heap to use more memory space than is available.

The procedure @code{heap-overflow-exception?} returns
@code{#t} when @var{obj} is a heap-overflow-exception
object and @code{#f} otherwise.

For example:

@smallexample
> @b{(define (handler exc)
    (if (heap-overflow-exception? exc)
        exc
        'not-heap-overflow-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (define (f x) (f (cons 1 x)))
      (f '())))}
#<heap-overflow-exception #2>
@end smallexample

@end deffn

@deffn procedure stack-overflow-exception? @var{obj}

Stack-overflow-exception objects are raised when the allocation of a
continuation frame would cause the heap to use more memory space than
is available.

The procedure @code{stack-overflow-exception?} returns
@code{#t} when @var{obj} is a stack-overflow-exception
object and @code{#f} otherwise.

For example:

@smallexample
> @b{(define (handler exc)
    (if (stack-overflow-exception? exc)
        exc
        'not-stack-overflow-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (define (f) (+ 1 (f)))
      (f)))}
#<stack-overflow-exception #2>
@end smallexample

@end deffn

@node Exception objects related to the host environment, Exception objects related to threads, Exception objects related to memory management, Exceptions
@section Exception objects related to the host environment

@deffn procedure os-exception? @var{obj}
@deffnx procedure os-exception-procedure @var{exc}
@deffnx procedure os-exception-arguments @var{exc}
@deffnx procedure os-exception-code @var{exc}
@deffnx procedure os-exception-message @var{exc}

Os-exception objects are raised by procedures which access the host
operating-system's services when the requested operation fails.  The
parameter @var{exc} must be a os-exception object.

The procedure @code{os-exception?} returns
@code{#t} when @var{obj} is a os-exception
object and @code{#f} otherwise.

The procedure @code{os-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{os-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

The procedure @code{os-exception-code} returns an exact integer error
code that can be converted to a string by the @code{err-code->string}
procedure.  Note that the error code is operating-system dependent.

The procedure @code{os-exception-message} returns
@code{#f} or a string giving details of the exception in a
human-readable form.

For example:

@smallexample
> @b{(define (handler exc)
    (if (os-exception? exc)
        (list (os-exception-procedure exc)
              (os-exception-arguments exc)
              (err-code->string (os-exception-code exc))
              (os-exception-message exc))
        'not-os-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (host-info "x.y.z")))}
(#<procedure #2 host-info> ("x.y.z") "Unknown host" #f)
@end smallexample

@end deffn

@deffn procedure no-such-file-or-directory-exception? @var{obj}
@deffnx procedure no-such-file-or-directory-exception-procedure @var{exc}
@deffnx procedure no-such-file-or-directory-exception-arguments @var{exc}

No-such-file-or-directory-exception objects are raised by procedures
which access the filesystem (such as @code{open-input-file} and
@code{directory-files}) when the path specified can't be found on the
filesystem.  The parameter @var{exc} must be a
no-such-file-or-directory-exception object.

The procedure @code{no-such-file-or-directory-exception?} returns
@code{#t} when @var{obj} is a no-such-file-or-directory-exception
object and @code{#f} otherwise.

The procedure @code{no-such-file-or-directory-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{no-such-file-or-directory-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (no-such-file-or-directory-exception? exc)
        (list (no-such-file-or-directory-exception-procedure exc)
              (no-such-file-or-directory-exception-arguments exc))
        'not-no-such-file-or-directory-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (with-input-from-file "nofile" read)))}
(#<procedure #2 with-input-from-file> ("nofile" #<procedure #3 read>))
@end smallexample

@end deffn

@deffn procedure unbound-os-environment-variable-exception? @var{obj}
@deffnx procedure unbound-os-environment-variable-exception-procedure @var{exc}
@deffnx procedure unbound-os-environment-variable-exception-arguments @var{exc}

Unbound-os-environment-variable-exception objects are raised when an
unbound operating-system environment variable is accessed by the
procedures @code{getenv} and @code{setenv}.  The parameter @var{exc}
must be an unbound-os-environment-variable-exception object.

The procedure @code{unbound-os-environment-variable-exception?} returns
@code{#t} when @var{obj} is an unbound-os-environment-variable-exception
object and @code{#f} otherwise.

The procedure @code{unbound-os-environment-variable-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{unbound-os-environment-variable-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (unbound-os-environment-variable-exception? exc)
        (list (unbound-os-environment-variable-exception-procedure exc)
              (unbound-os-environment-variable-exception-arguments exc))
        'not-unbound-os-environment-variable-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (getenv "DOES_NOT_EXIST")))}
(#<procedure #2 getenv> ("DOES_NOT_EXIST"))
@end smallexample

@end deffn

@node Exception objects related to threads, Exception objects related to C-interface, Exception objects related to the host environment, Exceptions
@section Exception objects related to threads

@deffn procedure scheduler-exception? @var{obj}
@deffnx procedure scheduler-exception-reason @var{exc}

Scheduler-exception objects are raised by the scheduler when some
operation requested from the host operating system failed
(e.g. checking the status of the devices in order to wake up threads
waiting to perform I/O on these devices).  The parameter @var{exc}
must be a scheduler-exception object.

The procedure @code{scheduler-exception?} returns
@code{#t} when @var{obj} is a scheduler-exception
object and @code{#f} otherwise.

The procedure @code{scheduler-exception-reason} returns the
os-exception object that describes the failure detected by the
scheduler.

@end deffn

@deffn procedure deadlock-exception? @var{obj}

Deadlock-exception objects are raised when the scheduler discovers
that all threads are blocked and can make no further progress.  In
that case the scheduler unblocks the primordial-thread and forces it
to raise a deadlock-exception object.

The procedure @code{deadlock-exception?} returns @code{#t} when
@var{obj} is a deadlock-exception object and @code{#f} otherwise.

For example:

@smallexample
> @b{(define (handler exc)
    (if (deadlock-exception? exc)
        exc
        'not-deadlock-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (read (open-vector))))}
#<deadlock-exception #2>
@end smallexample

@end deffn

@deffn procedure abandoned-mutex-exception? @var{obj}

Abandoned-mutex-exception objects are raised when the current thread
locks a mutex that was owned by a thread which terminated (see
@code{mutex-lock!}).

The procedure @code{abandoned-mutex-exception?} returns
@code{#t} when @var{obj} is a abandoned-mutex-exception
object and @code{#f} otherwise.

For example:

@smallexample
> @b{(define (handler exc)
    (if (abandoned-mutex-exception? exc)
        exc
        'not-abandoned-mutex-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (let ((m (make-mutex)))
        (thread-join!
          (thread-start!
            (make-thread
              (lambda () (mutex-lock! m)))))
        (mutex-lock! m))))}
#<abandoned-mutex-exception #2>
@end smallexample

@end deffn

@deffn procedure join-timeout-exception? @var{obj}
@deffnx procedure join-timeout-exception-procedure @var{exc}
@deffnx procedure join-timeout-exception-arguments @var{exc}

Join-timeout-exception objects are raised when a call to the
@code{thread-join!} procedure reaches its timeout before the target
thread terminates and a timeout-value parameter is not specified.  The
parameter @var{exc} must be a join-timeout-exception object.

The procedure @code{join-timeout-exception?} returns
@code{#t} when @var{obj} is a join-timeout-exception
object and @code{#f} otherwise.

The procedure @code{join-timeout-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{join-timeout-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (join-timeout-exception? exc)
        (list (join-timeout-exception-procedure exc)
              (join-timeout-exception-arguments exc))
        'not-join-timeout-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (thread-join!
        (thread-start!
          (make-thread
            (lambda () (thread-sleep! 10))))
        5)))}
(#<procedure #2 thread-join!> (#<thread #3> 5))
@end smallexample

@end deffn

@deffn procedure started-thread-exception? @var{obj}
@deffnx procedure started-thread-exception-procedure @var{exc}
@deffnx procedure started-thread-exception-arguments @var{exc}

Started-thread-exception objects are raised when the target thread of
a call to the procedure @code{thread-start!} is already started.  The
parameter @var{exc} must be a started-thread-exception object.

The procedure @code{started-thread-exception?} returns
@code{#t} when @var{obj} is a started-thread-exception
object and @code{#f} otherwise.

The procedure @code{started-thread-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{started-thread-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (started-thread-exception? exc)
        (list (started-thread-exception-procedure exc)
              (started-thread-exception-arguments exc))
        'not-started-thread-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (let ((t (make-thread (lambda () (expt 2 1000)))))
        (thread-start! t)
        (thread-start! t))))}
(#<procedure #2 thread-start!> (#<thread #3>))
@end smallexample

@end deffn

@deffn procedure terminated-thread-exception? @var{obj}
@deffnx procedure terminated-thread-exception-procedure @var{exc}
@deffnx procedure terminated-thread-exception-arguments @var{exc}

Terminated-thread-exception objects are raised when the
@code{thread-join!} procedure is called and the target thread has
terminated as a result of a call to the @code{thread-terminate!}
procedure.  The parameter @var{exc} must be a
terminated-thread-exception object.

The procedure @code{terminated-thread-exception?} returns
@code{#t} when @var{obj} is a terminated-thread-exception
object and @code{#f} otherwise.

The procedure @code{terminated-thread-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{terminated-thread-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (terminated-thread-exception? exc)
        (list (terminated-thread-exception-procedure exc)
              (terminated-thread-exception-arguments exc))
        'not-terminated-thread-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (thread-join!
        (thread-start!
          (make-thread
            (lambda () (thread-terminate! (current-thread))))))))}
(#<procedure #2 thread-join!> (#<thread #3>))
@end smallexample

@end deffn

@deffn procedure uncaught-exception? @var{obj}
@deffnx procedure uncaught-exception-procedure @var{exc}
@deffnx procedure uncaught-exception-arguments @var{exc}
@deffnx procedure uncaught-exception-reason @var{exc}

Uncaught-exception objects are raised when an object is raised in a
thread and that thread does not handle it (i.e. the thread terminated
because it did not catch an exception it raised).  The parameter
@var{exc} must be an uncaught-exception object.

The procedure @code{uncaught-exception?} returns
@code{#t} when @var{obj} is an uncaught-exception
object and @code{#f} otherwise.

The procedure @code{uncaught-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{uncaught-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

The procedure @code{uncaught-exception-reason} returns the object that
was raised by the thread and not handled by that thread.

For example:

@smallexample
> @b{(define (handler exc)
    (if (uncaught-exception? exc)
        (list (uncaught-exception-procedure exc)
              (uncaught-exception-arguments exc)
              (uncaught-exception-reason exc))
        'not-uncaught-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (thread-join!
        (thread-start!
          (make-thread
            (lambda () (open-input-file "data" 99)))))))}
(#<procedure #2 thread-join!>
 (#<thread #3>)
 #<wrong-number-of-arguments-exception #4>)
@end smallexample

@end deffn

@node Exception objects related to C-interface, Exception objects related to the reader, Exception objects related to threads, Exceptions
@section Exception objects related to C-interface

@deffn procedure cfun-conversion-exception? @var{obj}
@deffnx procedure cfun-conversion-exception-procedure @var{exc}
@deffnx procedure cfun-conversion-exception-arguments @var{exc}
@deffnx procedure cfun-conversion-exception-code @var{exc}
@deffnx procedure cfun-conversion-exception-message @var{exc}

Cfun-conversion-exception objects are raised by the C-interface when
converting between the Scheme representation and the C representation
of a value during a call from Scheme to C.  The parameter @var{exc}
must be a cfun-conversion-exception object.

The procedure @code{cfun-conversion-exception?} returns @code{#t} when
@var{obj} is a cfun-conversion-exception object and @code{#f}
otherwise.

The procedure @code{cfun-conversion-exception-procedure} returns the
procedure that raised @var{exc}.

The procedure @code{cfun-conversion-exception-arguments} returns the
list of arguments of the procedure that raised @var{exc}.

The procedure @code{cfun-conversion-exception-code} returns an exact
integer error code that can be converted to a string by the
@code{err-code->string} procedure.

The procedure @code{cfun-conversion-exception-message} returns
@code{#f} or a string giving details of the exception in a
human-readable form.

For example:

@smallexample
$ @b{cat test1.scm}
(define weird
  (c-lambda (char-string) nonnull-char-string
    "___result = ___arg1;"))
$ @b{gsc test1.scm}
$ @b{gsi}
Gambit @value{VERSION}

> @b{(load "test1")}
"/Users/feeley/gambit/doc/test1.o1"
> @b{(weird "hello")}
"hello"
> @b{(define (handler exc)
    (if (cfun-conversion-exception? exc)
        (list (cfun-conversion-exception-procedure exc)
              (cfun-conversion-exception-arguments exc)
              (err-code->string (cfun-conversion-exception-code exc))
              (cfun-conversion-exception-message exc))
        'not-cfun-conversion-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (weird 'not-a-string)))}
(#<procedure #2 weird>
 (not-a-string)
 "(Argument 1) Can't convert to C char-string"
 #f)
> @b{(with-exception-catcher
    handler
    (lambda () (weird #f)))}
(#<procedure #2 weird>
 (#f)
 "Can't convert result from C nonnull-char-string"
 #f)
@end smallexample

@end deffn

@deffn procedure sfun-conversion-exception? @var{obj}
@deffnx procedure sfun-conversion-exception-procedure @var{exc}
@deffnx procedure sfun-conversion-exception-arguments @var{exc}
@deffnx procedure sfun-conversion-exception-code @var{exc}
@deffnx procedure sfun-conversion-exception-message @var{exc}

Sfun-conversion-exception objects are raised by the C-interface when
converting between the Scheme representation and the C representation
of a value during a call from C to Scheme.  The parameter @var{exc}
must be a sfun-conversion-exception object.

The procedure @code{sfun-conversion-exception?} returns @code{#t} when
@var{obj} is a sfun-conversion-exception object and @code{#f}
otherwise.

The procedure @code{sfun-conversion-exception-procedure} returns the
procedure that raised @var{exc}.

The procedure @code{sfun-conversion-exception-arguments} returns the
list of arguments of the procedure that raised @var{exc}.

The procedure @code{sfun-conversion-exception-code} returns an exact
integer error code that can be converted to a string by the
@code{err-code->string} procedure.

The procedure @code{sfun-conversion-exception-message} returns
@code{#f} or a string giving details of the exception in a
human-readable form.

For example:

@smallexample
$ @b{cat test2.scm}
(c-define (f str) (nonnull-char-string) int "f" ""
  (string->number str))
(define t1 (c-lambda () int "___result = f (\"123\");"))
(define t2 (c-lambda () int "___result = f (0);"))
(define t3 (c-lambda () int "___result = f (\"1.5\");"))
$ @b{gsc test2.scm}
$ @b{gsi}
Gambit @value{VERSION}

> @b{(load "test2")}
"/u/feeley/test2.o1"
> @b{(t1)}
123
> @b{(define (handler exc)
    (if (sfun-conversion-exception? exc)
        (list (sfun-conversion-exception-procedure exc)
              (sfun-conversion-exception-arguments exc)
              (err-code->string (sfun-conversion-exception-code exc))
              (sfun-conversion-exception-message exc))
        'not-sfun-conversion-exception))}
> @b{(with-exception-catcher handler t2)}
(#<procedure #2 f>
 ()
 "(Argument 1) Can't convert from C nonnull-char-string"
 #f)
> @b{(with-exception-catcher handler t3)}
(#<procedure #2 f> () "Can't convert result to C int" #f)
@end smallexample

@end deffn

@deffn procedure multiple-c-return-exception? @var{obj}

Multiple-c-return-exception objects are raised by the C-interface when
a C to Scheme procedure call returns and that call's stack frame is no
longer on the C stack because the call has already returned, or has
been removed from the C stack by a @code{longjump}.

The procedure @code{multiple-c-return-exception?} returns @code{#t}
when @var{obj} is a multiple-c-return-exception object and @code{#f}
otherwise.

For example:

@smallexample
$ @b{cat test3.scm}
(c-define (f str) (char-string) scheme-object "f" ""
  (pp (list 'entry 'str= str))
  (let ((k (call-with-current-continuation (lambda (k) k))))
    (pp (list 'exit 'k= k))
    k))
(define scheme-to-c-to-scheme-and-back
  (c-lambda (char-string) scheme-object
    "___result = f (___arg1);"))
$ @b{gsc test3.scm}
$ @b{gsi}
Gambit @value{VERSION}

> @b{(load "test3")}
"/Users/feeley/gambit/doc/test3.o1"
> @b{(define (handler exc)
    (if (multiple-c-return-exception? exc)
        exc
        'not-multiple-c-return-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (let ((c (scheme-to-c-to-scheme-and-back "hello")))
        (pp c)
        (c 999))))}
(entry str= "hello")
(exit k= #<procedure #2>)
#<procedure #2>
(exit k= 999)
#<multiple-c-return-exception #3>
@end smallexample

@end deffn

@node Exception objects related to the reader, Exception objects related to evaluation and compilation, Exception objects related to C-interface, Exceptions
@section Exception objects related to the reader

@deffn procedure datum-parsing-exception? @var{obj}
@deffnx procedure datum-parsing-exception-kind @var{exc}
@deffnx procedure datum-parsing-exception-parameters @var{exc}
@deffnx procedure datum-parsing-exception-readenv @var{exc}

Datum-parsing-exception objects are raised by the reader (i.e. the
@code{read} procedure) when the input does not conform to the grammar
for datum.  The parameter @var{exc} must be a datum-parsing-exception
object.

The procedure @code{datum-parsing-exception?} returns @code{#t} when
@var{obj} is a datum-parsing-exception object and @code{#f}
otherwise.

The procedure @code{datum-parsing-exception-kind} returns a symbol
denoting the kind of parsing error that was encountered by the
reader when it raised @var{exc}.  Here is a table of the possible
return values:

@multitable @columnfractions .50 .50

@item @code{datum-or-eof-expected}          @tab Datum or EOF expected
@item @code{datum-expected}                 @tab Datum expected
@item @code{improperly-placed-dot}          @tab Improperly placed dot
@item @code{incomplete-form-eof-reached}    @tab Incomplete form, EOF reached
@item @code{incomplete-form}                @tab Incomplete form
@item @code{character-out-of-range}         @tab Character out of range
@item @code{invalid-character-name}         @tab Invalid '#\' name
@item @code{illegal-character}              @tab Illegal character
@item @code{s8-expected}                    @tab Signed 8 bit exact integer expected
@item @code{u8-expected}                    @tab Unsigned 8 bit exact integer expected
@item @code{s16-expected}                   @tab Signed 16 bit exact integer expected
@item @code{u16-expected}                   @tab Unsigned 16 bit exact integer expected
@item @code{s32-expected}                   @tab Signed 32 bit exact integer expected
@item @code{u32-expected}                   @tab Unsigned 32 bit exact integer expected
@item @code{s64-expected}                   @tab Signed 64 bit exact integer expected
@item @code{u64-expected}                   @tab Unsigned 64 bit exact integer expected
@item @code{inexact-real-expected}          @tab Inexact real expected
@item @code{invalid-hex-escape}             @tab Invalid hexadecimal escape
@item @code{invalid-escaped-character}      @tab Invalid escaped character
@item @code{open-paren-expected}            @tab '(' expected
@item @code{invalid-token}                  @tab Invalid token
@item @code{invalid-sharp-bang-name}        @tab Invalid '#!' name
@item @code{duplicate-label-definition}     @tab Duplicate definition for label
@item @code{missing-label-definition}       @tab Missing definition for label
@item @code{illegal-label-definition}       @tab Illegal definition of label
@item @code{invalid-infix-syntax-character} @tab Invalid infix syntax character
@item @code{invalid-infix-syntax-number}    @tab Invalid infix syntax number
@item @code{invalid-infix-syntax}           @tab Invalid infix syntax

@end multitable

The procedure @code{datum-parsing-exception-parameters} returns a list
of the parameters associated with the parsing error that was
encountered by the reader when it raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (datum-parsing-exception? exc)
        (list (datum-parsing-exception-kind exc)
              (datum-parsing-exception-parameters exc))
        'not-datum-parsing-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (with-input-from-string "(s #\\pace)" read)))}
(invalid-character-name ("pace"))
@end smallexample

@end deffn

@node Exception objects related to evaluation and compilation, Exception objects related to type checking, Exception objects related to the reader, Exceptions
@section Exception objects related to evaluation and compilation

@deffn procedure expression-parsing-exception? @var{obj}
@deffnx procedure expression-parsing-exception-kind @var{exc}
@deffnx procedure expression-parsing-exception-parameters @var{exc}
@deffnx procedure expression-parsing-exception-source @var{exc}

Expression-parsing-exception objects are raised by the evaluator and
compiler (i.e. the procedures @code{eval}, @code{compile-file}, etc)
when the input does not conform to the grammar for expression.  The
parameter @var{exc} must be a expression-parsing-exception object.

The procedure @code{expression-parsing-exception?} returns @code{#t} when
@var{obj} is a expression-parsing-exception object and @code{#f}
otherwise.

The procedure @code{expression-parsing-exception-kind} returns a
symbol denoting the kind of parsing error that was encountered by the
evaluator or compiler when it raised @var{exc}.  Here is a table of
the possible return values:

@multitable @columnfractions .50 .50

@item @code{id-expected}                      @tab Identifier expected
@item @code{ill-formed-namespace}             @tab Ill-formed namespace
@item @code{ill-formed-namespace-prefix}      @tab Ill-formed namespace prefix
@item @code{namespace-prefix-must-be-string}  @tab Namespace prefix must be a string
@item @code{macro-used-as-variable}           @tab Macro name can't be used as a variable
@item @code{variable-is-immutable}            @tab Variable is immutable
@item @code{ill-formed-macro-transformer}     @tab Macro transformer must be a lambda expression
@item @code{reserved-used-as-variable}        @tab Reserved identifier can't be used as a variable
@item @code{ill-formed-special-form}          @tab Ill-formed special form
@item @code{cannot-open-file}                 @tab Can't open file
@item @code{filename-expected}                @tab Filename expected
@item @code{ill-placed-define}                @tab Ill-placed 'define'
@item @code{ill-placed-**include}             @tab Ill-placed '##include'
@item @code{ill-placed-**define-macro}        @tab Ill-placed '##define-macro'
@item @code{ill-placed-**declare}             @tab Ill-placed '##declare'
@item @code{ill-placed-**namespace}           @tab Ill-placed '##namespace'
@item @code{ill-formed-expression}            @tab Ill-formed expression
@item @code{unsupported-special-form}         @tab Interpreter does not support
@item @code{ill-placed-unquote}               @tab Ill-placed 'unquote'
@item @code{ill-placed-unquote-splicing}      @tab Ill-placed 'unquote-splicing'
@item @code{parameter-must-be-id}             @tab Parameter must be an identifier
@item @code{parameter-must-be-id-or-default}  @tab Parameter must be an identifier or default binding
@item @code{duplicate-parameter}              @tab Duplicate parameter in parameter list
@item @code{ill-placed-dotted-rest-parameter} @tab Ill-placed dotted rest parameter
@item @code{parameter-expected-after-rest}    @tab #!rest must be followed by a parameter
@item @code{ill-formed-default}               @tab Ill-formed default binding
@item @code{ill-placed-optional}              @tab Ill-placed #!optional
@item @code{ill-placed-rest}                  @tab Ill-placed #!rest
@item @code{ill-placed-key}                   @tab Ill-placed #!key
@item @code{key-expected-after-rest}          @tab #!key expected after rest parameter
@item @code{ill-placed-default}               @tab Ill-placed default binding
@item @code{duplicate-variable-definition}    @tab Duplicate definition of a variable
@item @code{empty-body}                       @tab Body must contain at least one expression
@item @code{variable-must-be-id}              @tab Defined variable must be an identifier
@item @code{else-clause-not-last}             @tab Else clause must be last
@item @code{ill-formed-selector-list}         @tab Ill-formed selector list
@item @code{duplicate-variable-binding}       @tab Duplicate variable in bindings
@item @code{ill-formed-binding-list}          @tab Ill-formed binding list
@item @code{ill-formed-call}                  @tab Ill-formed procedure call
@item @code{ill-formed-cond-expand}           @tab Ill-formed 'cond-expand'
@item @code{unfulfilled-cond-expand}          @tab Unfulfilled 'cond-expand'

@end multitable

The procedure @code{expression-parsing-exception-parameters} returns a list
of the parameters associated with the parsing error that was
encountered by the evaluator or compiler when it raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (expression-parsing-exception? exc)
        (list (expression-parsing-exception-kind exc)
              (expression-parsing-exception-parameters exc))
        'not-expression-parsing-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (eval '(+ do 1))))}
(reserved-used-as-variable (do))
@end smallexample

@end deffn

@deffn procedure unbound-global-exception? @var{obj}
@deffnx procedure unbound-global-exception-variable @var{exc}
@deffnx procedure unbound-global-exception-code @var{exc}
@deffnx procedure unbound-global-exception-rte @var{exc}

Unbound-global-exception objects are raised when an unbound global
variable is accessed.  The parameter @var{exc} must be an
unbound-global-exception object.

The procedure @code{unbound-global-exception?} returns
@code{#t} when @var{obj} is an unbound-global-exception
object and @code{#f} otherwise.

The procedure @code{unbound-global-exception-variable} returns a
symbol identifying the unbound global variable.

For example:

@smallexample
> @b{(define (handler exc)
    (if (unbound-global-exception? exc)
        (list 'variable= (unbound-global-exception-variable exc))
        'not-unbound-global-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () foo))}
(variable= foo)
@end smallexample

@end deffn

@node Exception objects related to type checking, Exception objects related to procedure call, Exception objects related to evaluation and compilation, Exceptions
@section Exception objects related to type checking

@deffn procedure type-exception? @var{obj}
@deffnx procedure type-exception-procedure @var{exc}
@deffnx procedure type-exception-arguments @var{exc}
@deffnx procedure type-exception-arg-num @var{exc}
@deffnx procedure type-exception-type-id @var{exc}

Type-exception objects are raised when a primitive procedure is called
with an argument of incorrect type (i.e. when a run time type-check
fails).  The parameter @var{exc} must be a type-exception object.

The procedure @code{type-exception?} returns
@code{#t} when @var{obj} is a type-exception
object and @code{#f} otherwise.

The procedure @code{type-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{type-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

The procedure @code{type-exception-arg-num} returns the position of the
argument whose type is incorrect.  Position 1 is the first argument.

The procedure @code{type-exception-type-id} returns an identifier of
the type expected.  The type-id can be a symbol, such as @code{number}
and @code{string-or-nonnegative-fixnum}, or a record type descriptor.

For example:

@smallexample
> @b{(define (handler exc)
    (if (type-exception? exc)
        (list (type-exception-procedure exc)
              (type-exception-arguments exc)
              (type-exception-arg-num exc)
              (type-exception-type-id exc))
        'not-type-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (vector-ref '#(a b c) 'foo)))}
(#<procedure #2 vector-ref> (#(a b c) foo) 2 exact-integer)
> @b{(with-exception-catcher
    handler
    (lambda () (time->seconds 'foo)))}
(#<procedure #3 time->seconds> (foo) 1 #<type #4 time>)
@end smallexample

@end deffn

@deffn procedure range-exception? @var{obj}
@deffnx procedure range-exception-procedure @var{exc}
@deffnx procedure range-exception-arguments @var{exc}
@deffnx procedure range-exception-arg-num @var{exc}

Range-exception objects are raised when a numeric parameter is not in
the allowed range.  The parameter @var{exc} must be a range-exception
object.

The procedure @code{range-exception?} returns @code{#t} when @var{obj}
is a range-exception object and @code{#f} otherwise.

The procedure @code{range-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{range-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

The procedure @code{range-exception-arg-num} returns the position of
the argument which is not in the allowed range.  Position 1 is the
first argument.

For example:

@smallexample
> @b{(define (handler exc)
    (if (range-exception? exc)
        (list (range-exception-procedure exc)
              (range-exception-arguments exc)
              (range-exception-arg-num exc))
        'not-range-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (string-ref "abcde" 10)))}
(#<procedure #2 string-ref> ("abcde" 10) 2)
@end smallexample

@end deffn

@deffn procedure divide-by-zero-exception? @var{obj}
@deffnx procedure divide-by-zero-exception-procedure @var{exc}
@deffnx procedure divide-by-zero-exception-arguments @var{exc}

Divide-by-zero-exception objects are raised when a division by zero is
attempted.  The parameter @var{exc} must be a divide-by-zero-exception
object.

The procedure @code{divide-by-zero-exception?} returns
@code{#t} when @var{obj} is a divide-by-zero-exception
object and @code{#f} otherwise.

The procedure @code{divide-by-zero-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{divide-by-zero-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (divide-by-zero-exception? exc)
        (list (divide-by-zero-exception-procedure exc)
              (divide-by-zero-exception-arguments exc))
        'not-divide-by-zero-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (/ 5 0 7)))}
(#<procedure #2 /> (5 0 7))
@end smallexample

@end deffn

@deffn procedure improper-length-list-exception? @var{obj}
@deffnx procedure improper-length-list-exception-procedure @var{exc}
@deffnx procedure improper-length-list-exception-arguments @var{exc}
@deffnx procedure improper-length-list-exception-arg-num @var{exc}

Improper-length-list-exception objects are raised by the @code{map}
and @code{for-each} procedures when they are called with two or more
list arguments and the lists are not of the same length.  The
parameter @var{exc} must be an improper-length-list-exception object.

The procedure @code{improper-length-list-exception?} returns
@code{#t} when @var{obj} is an improper-length-list-exception
object and @code{#f} otherwise.

The procedure @code{improper-length-list-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{improper-length-list-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

The procedure @code{improper-length-list-exception-arg-num} returns
the position of the argument whose length is the shortest.  Position 1
is the first argument.

For example:

@smallexample
> @b{(define (handler exc)
    (if (improper-length-list-exception? exc)
        (list (improper-length-list-exception-procedure exc)
              (improper-length-list-exception-arguments exc)
              (improper-length-list-exception-arg-num exc))
        'not-improper-length-list-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (map + '(1 2) '(3) '(4 5))))}
(#<procedure #2 map> (#<procedure #3 +> (1 2) (3) (4 5)) 3)
@end smallexample

@end deffn

@node Exception objects related to procedure call, Other exception objects, Exception objects related to type checking, Exceptions
@section Exception objects related to procedure call

@deffn procedure wrong-number-of-arguments-exception? @var{obj}
@deffnx procedure wrong-number-of-arguments-exception-procedure @var{exc}
@deffnx procedure wrong-number-of-arguments-exception-arguments @var{exc}

Wrong-number-of-arguments-exception objects are raised when a
procedure is called with the wrong number of arguments.  The parameter
@var{exc} must be a wrong-number-of-arguments-exception object.

The procedure @code{wrong-number-of-arguments-exception?} returns
@code{#t} when @var{obj} is a wrong-number-of-arguments-exception
object and @code{#f} otherwise.

The procedure @code{wrong-number-of-arguments-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{wrong-number-of-arguments-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (wrong-number-of-arguments-exception? exc)
        (list (wrong-number-of-arguments-exception-procedure exc)
              (wrong-number-of-arguments-exception-arguments exc))
        'not-wrong-number-of-arguments-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (open-input-file "data" 99)))}
(#<procedure #2 open-input-file> ("data" 99))
@end smallexample

@end deffn

@deffn procedure number-of-arguments-limit-exception? @var{obj}
@deffnx procedure number-of-arguments-limit-exception-procedure @var{exc}
@deffnx procedure number-of-arguments-limit-exception-arguments @var{exc}

Number-of-arguments-limit-exception objects are raised by the
@code{apply} procedure when the procedure being called is passed more
than 8192 arguments.  The parameter @var{exc} must be a
number-of-arguments-limit-exception object.

The procedure @code{number-of-arguments-limit-exception?} returns
@code{#t} when @var{obj} is a number-of-arguments-limit-exception
object and @code{#f} otherwise.

The procedure @code{number-of-arguments-limit-exception-procedure}
returns the target procedure of the call to @code{apply} that raised
@var{exc}.

The procedure @code{number-of-arguments-limit-exception-arguments}
returns the list of arguments of the target procedure of the call to
@code{apply} that raised @var{exc}.

For example:

@smallexample
> @b{(define (iota n) (if (= n 0) '() (cons n (iota (- n 1)))))}
> @b{(define (handler exc)
    (if (number-of-arguments-limit-exception? exc)
        (list (number-of-arguments-limit-exception-procedure exc)
              (length (number-of-arguments-limit-exception-arguments exc)))
        'not-number-of-arguments-limit-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (apply + 1 2 3 (iota 8190))))}
(#<procedure #2 +> 8193)
@end smallexample

@end deffn

@deffn procedure nonprocedure-operator-exception? @var{obj}
@deffnx procedure nonprocedure-operator-exception-operator @var{exc}
@deffnx procedure nonprocedure-operator-exception-arguments @var{exc}
@deffnx procedure nonprocedure-operator-exception-code @var{exc}
@deffnx procedure nonprocedure-operator-exception-rte @var{exc}

Nonprocedure-operator-exception objects are raised when a procedure
call is executed and the operator position is not a procedure.  The
parameter @var{exc} must be an nonprocedure-operator-exception object.

The procedure @code{nonprocedure-operator-exception?} returns
@code{#t} when @var{obj} is an nonprocedure-operator-exception
object and @code{#f} otherwise.

The procedure @code{nonprocedure-operator-exception-operator} returns
the value in operator position of the procedure call that raised
@var{exc}.

The procedure @code{nonprocedure-operator-exception-arguments} returns
the list of arguments of the procedure call that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (nonprocedure-operator-exception? exc)
        (list (nonprocedure-operator-exception-operator exc)
              (nonprocedure-operator-exception-arguments exc))
        'not-nonprocedure-operator-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (11 22 33)))}
(11 (22 33))
@end smallexample

@end deffn

@deffn procedure unknown-keyword-argument-exception? @var{obj}
@deffnx procedure unknown-keyword-argument-exception-procedure @var{exc}
@deffnx procedure unknown-keyword-argument-exception-arguments @var{exc}

Unknown-keyword-argument-exception objects are raised when a procedure
accepting keyword arguments is called and one of the keywords supplied
is not among those that are expected.  The parameter @var{exc} must be
an unknown-keyword-argument-exception object.

The procedure @code{unknown-keyword-argument-exception?} returns
@code{#t} when @var{obj} is an unknown-keyword-argument-exception
object and @code{#f} otherwise.

The procedure @code{unknown-keyword-argument-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{unknown-keyword-argument-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (unknown-keyword-argument-exception? exc)
        (list (unknown-keyword-argument-exception-procedure exc)
              (unknown-keyword-argument-exception-arguments exc))
        'not-unknown-keyword-argument-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () ((lambda (#!key (foo 5)) foo) bar: 11)))}
(#<procedure #2> (bar: 11))
@end smallexample

@end deffn

@deffn procedure keyword-expected-exception? @var{obj}
@deffnx procedure keyword-expected-exception-procedure @var{exc}
@deffnx procedure keyword-expected-exception-arguments @var{exc}

Keyword-expected-exception objects are raised when a procedure
accepting keyword arguments is called and a nonkeyword was supplied
where a keyword was expected.  The parameter @var{exc} must be an
keyword-expected-exception object.

The procedure @code{keyword-expected-exception?} returns
@code{#t} when @var{obj} is an keyword-expected-exception
object and @code{#f} otherwise.

The procedure @code{keyword-expected-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{keyword-expected-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (keyword-expected-exception? exc)
        (list (keyword-expected-exception-procedure exc)
              (keyword-expected-exception-arguments exc))
        'not-keyword-expected-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () ((lambda (#!key (foo 5)) foo) 11 22)))}
(#<procedure #2> (11 22))
@end smallexample

@end deffn

@node Other exception objects, , Exception objects related to procedure call, Exceptions
@section Other exception objects

@deffn procedure error-exception? @var{obj}
@deffnx procedure error-exception-message @var{exc}
@deffnx procedure error-exception-parameters @var{exc}
@deffnx procedure error @var{message} @var{obj}@dots{}

Error-exception objects are raised when the @code{error} procedure is
called.  The parameter @var{exc} must be an error-exception
object.

The procedure @code{error-exception?} returns
@code{#t} when @var{obj} is an error-exception
object and @code{#f} otherwise.

The procedure @code{error-exception-message} returns the first
argument of the call to @code{error} that raised @var{exc}.

The procedure @code{error-exception-parameters} returns the list of
arguments, starting with the second argument, of the call to
@code{error} that raised @var{exc}.

The @code{error} procedure raises an error-exception object whose
message field is @var{message} and parameters field is the list of
values @var{obj}@dots{}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (error-exception? exc)
        (list (error-exception-message exc)
              (error-exception-parameters exc))
        'not-error-exception))}
> @b{(with-exception-catcher
    handler
    (lambda () (error "unexpected object:" 123)))}
("unexpected object:" (123))
@end smallexample

@end deffn

@node Host environment, I/O and ports, Exceptions, Top
@chapter Host environment

The host environment is the set of resources, such as the filesystem,
network and processes, that are managed by the operating system within
which the Scheme program is executing.  This chapter specifies how the
host environment can be accessed from within the Scheme program.

In this chapter we say that the Scheme program being executed is a
process, even though the concept of process does not exist in some
operating systems supported by Gambit (e.g. MSDOS).

@menu
* Handling of file names::                  Handling of file names
* Filesystem operations::                   Filesystem operations
* Shell command execution::                 Shell command execution
* Process termination::                     Process termination
* Command line arguments::                  Command line arguments
* Environment variables::                   Environment variables
* Measuring time::                          Measuring time
* File information::                        File information
* Group information::                       Group information
* User information::                        User information   .
* Host information::                        Host information
* Service information::                     Service information
* Protocol information::                    Protocol information
* Network information::                     Network information
@end menu

@node Handling of file names, Filesystem operations, Host environment, Host environment
@section Handling of file names
@cindex file names
@cindex current working directory
@cindex absolute path
@cindex relative path
@cindex home directory
@cindex central installation directory
@cindex installation directories

Gambit uses a naming convention for files that is compatible with
the one used by the host environment but extended to allow
referring to the @dfn{home directory} of the current user or some
specific user and the @dfn{installation directories}.

A @dfn{path} is a string that denotes a file, for example
@code{"src/readme.txt"}.  Each component of a path is separated by a
@samp{/} under UNIX and Mac OS X and by a @samp{/} or @samp{\} under
MSDOS and Microsoft Windows.  A leading separator indicates an
absolute path under UNIX, Mac OS X, MSDOS and Microsoft Windows.  A
path which does not contain a path separator is relative to the
@dfn{current working directory} on all operating systems.  A volume
specifier such as @samp{C:} may prefix a file name under MSDOS and
Microsoft Windows.

@cindex ~~
A path which starts with the characters @samp{~~} denotes a file in an
installation directory.  If nothing follows the @samp{~~} then the
directory denoted is the central installation directory.  Otherwise
what follows the @samp{~~} is the name of the installation directory,
for example @samp{~~lib} denotes the @samp{lib} installation
directory.  Note that the location of the installation directories may
be overridden by using the @samp{-:=@var{DIRECTORY}} and
@samp{-:~~@var{DIR}=@var{DIRECTORY}} runtime options or by defining
the @samp{GAMBCOPT} environment variable.

@cindex ~
A path which starts with the character @samp{~} not followed by
@samp{~} denotes a file in the user's home directory.  The user's home
directory is contained in the @samp{HOME} environment variable under
UNIX, Mac OS X, MSDOS and Microsoft Windows.  Under MSDOS and
Microsoft Windows, if the @samp{HOME} environment variable is not
defined, the environment variables @samp{HOMEDRIVE} and
@samp{HOMEPATH} are concatenated if they are defined.  If this fails
to yield a home directory, the central installation directory is used
instead.

@cindex ~username
A path which starts with the characters @samp{~@var{username}}
denotes a file in the home directory of the given user.  Under UNIX
and Mac OS X this is found using the password file.  There is no
equivalent under MSDOS and Microsoft Windows.

@deffn procedure current-directory @r{[}@var{new-current-directory}@r{]}

@cindex current working directory
The parameter object @code{current-directory} is bound to the current
working directory.  Calling this procedure with no argument returns
the absolute @dfn{normalized path} of the directory and calling this
procedure with one argument sets the directory to
@var{new-current-directory}.  The initial binding of this parameter
object is the current working directory of the current process.  The
path returned by @code{current-directory} always contains a trailing
directory separator.  Modifications of the parameter object do not
change the current working directory of the current process (i.e.
that is accessible with the UNIX @code{getcwd()} function and the
Microsoft Windows @code{GetCurrentDirectory} function).  It is an
error to mutate the string returned by @code{current-directory}.

For example under UNIX:

@smallexample
> @b{(current-directory)}
"/Users/feeley/gambit/doc/"
> @b{(current-directory "..")}
> @b{(current-directory)}
"/Users/feeley/gambit/"
> @b{(path-expand "foo" "~~")}
"/usr/local/Gambit-C/foo"
> @b{(parameterize ((current-directory "~~")) (path-expand "foo"))}
"/usr/local/Gambit-C/foo"
@end smallexample

@end deffn

@deffn procedure path-expand @var{path} @r{[}@var{origin-directory}@r{]}

@cindex absolute path
@cindex relative path
The procedure @code{path-expand} takes the path of a file or directory
and returns an expanded path, which is an absolute path when
@var{path} or @var{origin-directory} are absolute paths.
The optional @var{origin-directory} parameter, which defaults
to the current working directory, is the directory used to resolve
relative paths.  Components of the paths @var{path} and
@var{origin-directory} need not exist.

For example under UNIX:

@smallexample
> @b{(path-expand "foo")}
"/Users/feeley/gambit/doc/foo"
> @b{(path-expand "~/foo")}
"/Users/feeley/foo"
> @b{(path-expand "~~lib/foo")}
"/usr/local/Gambit-C/lib/foo"
> @b{(path-expand "../foo")}
"/Users/feeley/gambit/doc/../foo"
> @b{(path-expand "foo" "")}
"foo"
> @b{(path-expand "foo" "/tmp")}
"/tmp/foo"
> @b{(path-expand "this/file/does/not/exist")}
"/Users/feeley/gambit/doc/this/file/does/not/exist"
> @b{(path-expand "")}
"/Users/feeley/gambit/doc/"
@end smallexample

@end deffn

@deffn procedure path-normalize @var{path} @r{[}@var{allow-relative?} @r{[}@var{origin-directory}@r{]}@r{]}

@cindex normalized path
The procedure @code{path-normalize} takes a path of a file or
directory and returns its normalized path.  The optional
@var{origin-directory} parameter, which defaults to the current
working directory, is the directory used to resolve relative paths.
All components of the paths @var{path} and
@var{origin-directory} must exist, except possibly the last
component of @var{path}.  A normalized path is a path
containing no redundant parts and which is consistent with the current
structure of the filesystem.  A normalized path of a directory will
always end with a path separator (i.e. @samp{/}, @samp{\}, or @samp{:}
depending on the operating system).  The optional
@var{allow-relative?} parameter, which defaults to @code{#f},
indicates if the path returned can be expressed relatively to
@var{origin-directory}: a @code{#f} requests an absolute path,
the symbol @code{shortest} requests the shortest of the absolute and
relative paths, and any other value requests the relative path.  The
shortest path is useful for interaction with the user because short
relative paths are typically easier to read than long absolute paths.

For example under UNIX:

@smallexample
> @b{(path-expand "../foo")}
"/Users/feeley/gambit/doc/../foo"
> @b{(path-normalize "../foo")}
"/Users/feeley/gambit/foo"
> @b{(path-normalize "this/file/does/not/exist")}
*** ERROR IN (console)@@3.1 -- No such file or directory
(path-normalize "this/file/does/not/exist")
@end smallexample

@end deffn

@deffn procedure path-extension @var{path}
@deffnx procedure path-strip-extension @var{path}
@deffnx procedure path-directory @var{path}
@deffnx procedure path-strip-directory @var{path}
@deffnx procedure path-strip-trailing-directory-separator @var{path}
@deffnx procedure path-volume @var{path}
@deffnx procedure path-strip-volume @var{path}

These procedures extract various parts of a path, which need not be a
normalized path.  The procedure @code{path-extension} returns the file
extension (including the period) or the empty string if there is no
extension.  The procedure @code{path-strip-extension} returns the path
with the extension stripped off.  The procedure @code{path-directory}
returns the file's directory (including the last path separator) or
the empty string if no directory is specified in the path.  The
procedure @code{path-strip-directory} returns the path with the
directory stripped off.  The procedure
@code{path-strip-trailing-directory-separator} returns the path with
the directory separator stripped off if one is at the end of the path.
The procedure @code{path-volume} returns the file's volume (including
the last path separator) or the empty string if no volume is specified
in the path.  The procedure @code{path-strip-volume} returns the path
with the volume stripped off.

For example under UNIX:

@smallexample
> @b{(path-extension "/tmp/foo")}
""
> @b{(path-extension "/tmp/foo.txt")}
".txt"
> @b{(path-strip-extension "/tmp/foo.txt")}
"/tmp/foo"
> @b{(path-directory "/tmp/foo.txt")}
"/tmp/"
> @b{(path-strip-directory "/tmp/foo.txt")}
"foo.txt"
> @b{(path-strip-trailing-directory-separator "/usr/local/bin/")}
"/usr/local/bin"
> @b{(path-strip-trailing-directory-separator "/usr/local/bin")}
"/usr/local/bin"
> @b{(path-volume "/tmp/foo.txt")}
""
> @b{(path-volume "C:/tmp/foo.txt")}
"" @r{@i{; result is}} "C:" @r{@i{under Microsoft Windows}}
> @b{(path-strip-volume "C:/tmp/foo.txt")}
"C:/tmp/foo.txt" @r{@i{; result is}} "/tmp/foo.txt" @r{@i{under Microsoft Windows}}
@end smallexample

@end deffn

@node Filesystem operations, Shell command execution, Handling of file names, Host environment
@section Filesystem operations

@deffn procedure create-directory @var{path-or-settings}

This procedure creates a directory.  The argument
@var{path-or-settings} is either a string denoting a filesystem path
or a list of port settings which must contain a @code{path:} setting.
Here are the settings allowed:

@itemize

@item
@code{path:} @var{string}

This setting indicates the location of the directory to create in the
filesystem.  There is no default value for this setting.

@item
@code{permissions:} @var{12-bit-exact-integer}

This setting controls the UNIX permissions that will be attached to
the file if it is created.  The default value of this setting is
@code{#o777}.

@end itemize

For example:

@smallexample
> @b{(create-directory "newdir")}
> @b{(create-directory "newdir")}
*** ERROR IN (console)@@2.1 -- File exists
(create-directory "newdir")
@end smallexample

@end deffn

@deffn procedure create-fifo @var{path-or-settings}

This procedure creates a FIFO.  The argument @var{path-or-settings} is
either a string denoting a filesystem path or a list of port settings
which must contain a @code{path:} setting.  Here are the settings
allowed:

@itemize

@item
@code{path:} @var{string}

This setting indicates the location of the FIFO to create in the
filesystem.  There is no default value for this setting.

@item
@code{permissions:} @var{12-bit-exact-integer}

This setting controls the UNIX permissions that will be attached to
the file if it is created.  The default value of this setting is
@code{#o666}.

@end itemize

For example:

@smallexample
> @b{(create-fifo "fifo")}
> @b{(define a (open-input-file "fifo"))}
> @b{(define b (open-output-file "fifo"))}
> @b{(display "1 22 333" b)}
> @b{(force-output b)}
> @b{(read a)}
1
> @b{(read a)}
22
@end smallexample

@end deffn

@deffn procedure create-link @var{source-path} @var{destination-path}

This procedure creates a hard link between @var{source-path} and
@var{destination-path}.  The argument @var{source-path} must be a
string denoting the path of an existing file.  The argument
@var{destination-path} must be a string denoting the path of the link
to create.

@end deffn

@deffn procedure create-symbolic-link @var{source-path} @var{destination-path}

This procedure creates a symbolic link between @var{source-path} and
@var{destination-path}.  The argument @var{source-path} must be a
string denoting the path of an existing file.  The argument
@var{destination-path} must be a string denoting the path of the
symbolic link to create.

@end deffn

@deffn procedure rename-file @var{source-path} @var{destination-path}

This procedure renames the file @var{source-path} to
@var{destination-path}.  The argument @var{source-path} must be a
string denoting the path of an existing file.  The argument
@var{destination-path} must be a string denoting the new path of the
file.

@end deffn

@deffn procedure copy-file @var{source-path} @var{destination-path}

This procedure copies the file @var{source-path} to
@var{destination-path}.  The argument @var{source-path} must be a
string denoting the path of an existing file.  The argument
@var{destination-path} must be a string denoting the path of the
file to create.

@end deffn

@deffn procedure delete-file @var{path}

This procedure deletes the file @var{path}.  The argument @var{path}
must be a string denoting the path of an existing file.

@end deffn

@deffn procedure delete-directory @var{path}

This procedure deletes the directory @var{path}.  The argument
@var{path} must be a string denoting the path of an existing
directory.

@end deffn

@deffn procedure directory-files @r{[}@var{path-or-settings}@r{]}

This procedure returns the list of the files in a directory.  The
argument @var{path-or-settings} is either a string denoting a
filesystem path to a directory or a list of settings which must
contain a @code{path:} setting.  If it is not specified,
@var{path-or-settings} defaults to the current directory (the value
bound to the @code{current-directory} parameter object).  Here are the
settings allowed:

@itemize

@item
@code{path:} @var{string}

This setting indicates the location of the directory in the filesystem.
There is no default value for this setting.

@item
@code{ignore-hidden:} ( @code{#f} | @code{#t} | @code{dot-and-dot-dot} )

This setting controls whether hidden-files will be returned.  Under
UNIX and Mac OS X hidden-files are those that start with a period
(such as @samp{.}, @samp{..}, and @samp{.profile}).  Under Microsoft
Windows hidden files are the @samp{.} and @samp{..} entries and the
files whose ``hidden file'' attribute is set.  A setting of @code{#f}
will enumerate all the files.  A setting of @code{#t} will only
enumerate the files that are not hidden.  A setting of
@code{dot-and-dot-dot} will enumerate all the files except for the
@samp{.} and @samp{..} hidden files.  The default value of this
setting is @code{#t}.

@end itemize

For example:

@smallexample
> @b{(directory-files)}
("complex" "README" "simple")
> @b{(directory-files "../include")}
("config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")
> @b{(directory-files (list path: "../include" ignore-hidden: #f))}
("." ".." "config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")
@end smallexample

@end deffn

@node Shell command execution, Process termination, Filesystem operations, Host environment
@section Shell command execution

@deffn procedure shell-command @var{command} @r{[}@var{capture?}@r{]}

The procedure @code{shell-command} calls up the shell to execute
@var{command} which must be a string.  The argument @var{capture?},
which defaults to @code{#f}, indicates if the output of the command is
captured as a string.  If @var{capture?} is @code{#f}, this procedure
returns the exit status of the shell in the form that the C library's
@code{system} routine returns.  If @var{capture?} is not @code{#f},
this procedure returns a pair consisting of the exit status of the
shell in the @code{car} field, and the captured output in the
@code{cdr} field.  Be advised that the shell that is used, and
consequently the syntax of @var{command}, depends on the operating
system.  On Unix, the shell @code{/bin/sh} is usually invoked.  On Windows,
the shell @code{cmd.exe} is usually invoked.

For example under UNIX:

@smallexample
> @b{(shell-command "ls -sk f*.scm")}
4 fact.scm   4 fib.scm
0
> @b{(shell-command "ls -sk f*.scm" #t)}
(0 . "4 fact.scm   4 fib.scm\n")
> @b{(shell-command "echo x\\\\\\\\y $HOME" #t)}
(0 . "x\\y /Users/feeley\n")
@end smallexample

For example under Windows:

@smallexample
> @b{(shell-command "echo x\\\\\\\\y %HOME%" #t)}
(0 . "x\\\\\\\\y C:\\Users\\feeley\r\n")
@end smallexample

@end deffn

@node Process termination, Command line arguments, Shell command execution, Host environment
@section Process termination

@deffn procedure exit @r{[}@var{status}@r{]}

The procedure @code{exit} causes the process to terminate with the
status @var{status} which must be an exact integer in the range 0 to
255.  If it is not specified, @var{status} defaults to 0.

For example under UNIX:

@smallexample
$ @b{gsi}
Gambit @value{VERSION}

> @b{(exit 42)}
$ @b{echo $?}
42
@end smallexample

@end deffn

@node Command line arguments, Environment variables, Process termination, Host environment
@section Command line arguments

@deffn procedure command-line

This procedure returns a list of strings corresponding to the command
line arguments, including the program file name as the first element
of the list.  When the interpreter executes a Scheme script, the list
returned by @code{command-line} contains the script's absolute path
followed by the remaining command line arguments.

For example under UNIX:

@smallexample
$ @b{gsi -:d -e "(pretty-print (command-line))"}
("gsi" "-e" "(pretty-print (command-line))")
$ @b{cat foo}
#!/usr/local/Gambit-C/bin/gsi-script
(pretty-print (command-line))
$ @b{./foo 1 2 "3 4"}
("/u/feeley/./foo" "1" "2" "3 4")
@end smallexample

@end deffn

@node Environment variables, Measuring time, Command line arguments, Host environment
@section Environment variables

@deffn procedure getenv @var{name} @r{[}@var{default}@r{]}
@deffnx procedure setenv @var{name} @r{[}@var{new-value}@r{]}

The procedure @code{getenv} returns the value of the environment
variable @var{name} of the current process.  Variable names are
denoted with strings.  A string is returned if the environment
variable is bound, otherwise @var{default} is returned if it is
specified, otherwise an exception is raised.

The procedure @code{setenv} changes the binding of the environment
variable @var{name} to @var{new-value} which must be a string.
If @var{new-value} is not specified the binding is removed.

For example under UNIX:

@smallexample
> @b{(getenv "HOME")}
"/Users/feeley"
> @b{(getenv "DOES_NOT_EXIST" #f)}
#f
> @b{(setenv "DOES_NOT_EXIST" "it does now")}
> @b{(getenv "DOES_NOT_EXIST" #f)}
"it does now"
> @b{(setenv "DOES_NOT_EXIST")}
> @b{(getenv "DOES_NOT_EXIST" #f)}
#f
> @b{(getenv "DOES_NOT_EXIST")}
*** ERROR IN (console)@@7.1 -- Unbound OS environment variable
(getenv "DOES_NOT_EXIST")
@end smallexample

@end deffn

@node Measuring time, File information, Environment variables, Host environment
@section Measuring time

Procedures are available for measuring real time (aka ``wall'' time)
and cpu time (the amount of time the cpu has been executing the
process).  The resolution of the real time and cpu time clock is
operating system dependent.  Typically the resolution of the cpu time
clock is rather coarse (measured in ``ticks'' of 1/60th or 1/100th of
a second).  Real time is internally computed relative to some
arbitrary point in time using floating point numbers, which means that
there is a gradual loss of resolution as time elapses.  Moreover, some
operating systems report time in number of ticks using a 32 bit
integer so the value returned by the time related procedures may
wraparound much before any significant loss of resolution occurs (for
example 2.7 years if ticks are 1/50th of a second).

@deffn procedure current-time
@deffnx procedure time? @var{obj}
@deffnx procedure time->seconds @var{time}
@deffnx procedure seconds->time @var{x}

The procedure @code{current-time} returns a @dfn{time object}
representing the current point in real time.

The procedure @code{time?} returns @code{#t} when @var{obj} is a time
object and @code{#f} otherwise.

The procedure @code{time->seconds} converts the time object @var{time}
into an inexact real number representing the number of seconds elapsed
since the ``epoch'' (which is 00:00:00 Coordinated Universal Time
01-01-1970).

The procedure @code{seconds->time} converts the real number @var{x}
representing the number of seconds elapsed since the ``epoch'' into a
time object.

For example:

@smallexample
> @b{(current-time)}
#<time #2>
> @b{(time? (current-time))}
#t
> @b{(time? 123)}
#f
> @b{(time->seconds (current-time))}
1083118758.63973
> @b{(time->seconds (current-time))}
1083118759.909163
> @b{(seconds->time (+ 10 (time->seconds (current-time))}
#<time #3>  @r{@i{; a time object representing 10 seconds in the future}}
@end smallexample

@end deffn

@deffn procedure process-times
@deffnx procedure cpu-time
@deffnx procedure real-time

The procedure @code{process-times} returns a three element f64vector
containing the cpu time that has been used by the program and the real
time that has elapsed since it was started.  The first element
corresponds to ``user'' time in seconds, the second element
corresponds to ``system'' time in seconds and the third element is the
elapsed real time in seconds.  On operating systems that can't
differentiate user and system time, the system time is zero.  On
operating systems that can't measure cpu time, the user time is equal
to the elapsed real time and the system time is zero.

The procedure @code{cpu-time} returns the cpu time in seconds that has
been used by the program (user time plus system time).

The procedure @code{real-time} returns the real time that has elapsed
since the program was started.

For example:

@smallexample
> @b{(process-times)}
#f64(.02794 .021754 .159926176071167)
> @b{(cpu-time)}
.051223
> @b{(real-time)}
.40660619735717773
@end smallexample

@end deffn

@deffn {special form} time @r{@i{expr}} @r{[}@var{port}@r{]}

The @code{time} special form evaluates @i{expr} and returns the
result.  As a side effect it displays a message on the port @var{port}
which indicates various statistics about the evaluation of @i{expr}
including how long the evaluation took (in real time and cpu time),
how much time was spent in the garbage collector, how much memory was
allocated during the evaluation and how many minor and major page
faults occured (0 is reported if not running under UNIX).  If it is
not specified, @var{port} defaults to the interaction channel
(i.e. the output will appear at the REPL).

For example:

@smallexample
> @b{(define (f x)
    (let loop ((x x) (lst '()))
      (if (= x 0)
          lst
          (loop (- x 1) (cons x lst)))))}
> @b{(length (time (f 100000)))}
(time (f 100000))
    683 ms real time
    558 ms cpu time (535 user, 23 system)
    8 collections accounting for 102 ms real time (70 user, 5 system)
    6400160 bytes allocated
    no minor faults
    no major faults
100000
@end smallexample

@end deffn

@node File information, Group information, Measuring time, Host environment
@section File information

@deffn procedure file-exists? @var{path} @r{[}@var{chase?}@r{]}

The @var{path} argument must be a string.  This procedure returns
@code{#t} when a file by that name exists, and returns @code{#f}
otherwise.

When @var{chase?} is present and @code{#f}, symbolic links will not be
chased, in other words if @var{path} refers to a symbolic link,
@code{file-exists?} will return @code{#t} whether or not it points to
an existing file.

For example:

@smallexample
> @b{(file-exists? "nofile")}
#f
@end smallexample

@end deffn

@deffn procedure file-info @var{path} @r{[}@var{chase?}@r{]}

This procedure accesses the filesystem to get information about the
file whose location is given by the string @var{path}.  A
file-information record is returned that contains the file's type, the
device number, the inode number, the mode (permission bits), the
number of links, the file's user id, the file's group id, the file's
size in bytes, the times of last-access, last-modification and
last-change, the attributes, and the creation time.

When @var{chase?} is present and @code{#f}, symbolic links will not be
chased, in other words if @var{path} refers to a symbolic link the
@code{file-info} procedure will return information about the link
rather than the file it links to.

For example:

@smallexample
> @b{(file-info "/dev/tty")}
#<file-info #2
   type: character-special
   device: 19513156
   inode: 20728196
   mode: 438
   number-of-links: 1
   owner: 0
   group: 0
   size: 0
   last-access-time: #<time #3>
   last-modification-time: #<time #4>
   last-change-time: #<time #5>
   attributes: 128
   creation-time: #<time #6>>
@end smallexample

@end deffn

@deffn procedure file-info? @var{obj}

This procedure returns @code{#t} when @var{obj} is a file-information
record and @code{#f} otherwise.

For example:

@smallexample
> @b{(file-info? (file-info "/dev/tty"))}
#t
> @b{(file-info? 123)}
#f
@end smallexample

@end deffn

@deffn procedure file-info-type @var{file-info}

Returns the type field of the file-information record
@var{file-info}.  The type is denoted by a symbol.
The following types are possible:

@table @code
@item regular
Regular file
@item directory
Directory
@item character-special
Character special device
@item block-special
Block special device
@item fifo
FIFO
@item symbolic-link
Symbolic link
@item socket
Socket
@item unknown
File is of an unknown type
@end table

For example:

@smallexample
> @b{(file-info-type (file-info "/dev/tty"))}
character-special
> @b{(file-info-type (file-info "/dev"))}
directory
@end smallexample

@end deffn

@deffn procedure file-info-device @var{file-info}

Returns the device field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-device (file-info "/dev/tty"))}
19513156
@end smallexample

@end deffn

@deffn procedure file-info-inode @var{file-info}

Returns the inode field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-inode (file-info "/dev/tty"))}
20728196
@end smallexample

@end deffn

@deffn procedure file-info-mode @var{file-info}

Returns the mode field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-mode (file-info "/dev/tty"))}
438
@end smallexample

@end deffn

@deffn procedure file-info-number-of-links @var{file-info}

Returns the number-of-links field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-number-of-links (file-info "/dev/tty"))}
1
@end smallexample

@end deffn

@deffn procedure file-info-owner @var{file-info}

Returns the owner field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-owner (file-info "/dev/tty"))}
0
@end smallexample

@end deffn

@deffn procedure file-info-group @var{file-info}

Returns the group field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-group (file-info "/dev/tty"))}
0
@end smallexample

@end deffn

@deffn procedure file-info-size @var{file-info}

Returns the size field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-size (file-info "/dev/tty"))}
0
@end smallexample

@end deffn

@deffn procedure file-info-last-access-time @var{file-info}

Returns the last-access-time field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-last-access-time (file-info "/dev/tty"))}
#<time #2>
@end smallexample

@end deffn

@deffn procedure file-info-last-modification-time @var{file-info}

Returns the last-modification-time field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-last-modification-time (file-info "/dev/tty"))}
#<time #2>
@end smallexample

@end deffn

@deffn procedure file-info-last-change-time @var{file-info}

Returns the last-change-time field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-last-change-time (file-info "/dev/tty"))}
#<time #2>
@end smallexample

@end deffn

@deffn procedure file-info-attributes @var{file-info}

Returns the attributes field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-attributes (file-info "/dev/tty"))}
128
@end smallexample

@end deffn

@deffn procedure file-info-creation-time @var{file-info}

Returns the creation-time field of the file-information record
@var{file-info}.

For example:

@smallexample
> @b{(file-info-creation-time (file-info "/dev/tty"))}
#<time #2>
@end smallexample

@end deffn

@deffn procedure file-type @var{path}
@deffnx procedure file-device @var{path}
@deffnx procedure file-inode @var{path}
@deffnx procedure file-mode @var{path}
@deffnx procedure file-number-of-links @var{path}
@deffnx procedure file-owner @var{path}
@deffnx procedure file-group @var{path}
@deffnx procedure file-size @var{path}
@deffnx procedure file-last-access-time @var{path}
@deffnx procedure file-last-modification-time @var{path}
@deffnx procedure file-last-change-time @var{path}
@deffnx procedure file-attributes @var{path}
@deffnx procedure file-creation-time @var{path}

These procedures combine a call to the @code{file-info} procedure and
a call to a file-information record field accessor.  For instance
@code{(file-type @var{path})} is equivalent to @code{(file-info-type
(file-info @var{path}))}.

@end deffn

@deffn procedure file-last-access-and-modification-times-set! @var{path} @r{[}@var{atime} @r{[}@var{mtime}@r{]}@r{]}

This procedure changes the last-access and last-modification times of
the file whose location is given by the string @var{path}.  Time is
specified either with a time object indicating an absolute point in
time or a real number indicating the number of seconds relative to the
moment the procedure is called.  When @var{atime} and @var{mtime} are
not specified, the last-access and last-modification times are set to
the current time.  When @var{mtime} is not specified, the last-access
and last-modification times are set to @var{atime}.  Otherwise the
last-access time is set to @var{atime} and the last-modification time
is set to @var{mtime}.

For example:

@smallexample
> @b{(define (t path)
    (list (time->seconds (file-last-access-time path))
          (time->seconds (file-last-modification-time path))))}
> @b{(with-output-to-file "nl.txt" newline)}
> @b{(t "nl.txt")}
(1429547027. 1429547027.)
> @b{(t "nl.txt")}
(1429547027. 1429547027.)
> @b{(file-last-access-and-modification-times-set! "nl.txt")}
> @b{(t "nl.txt")}
(1429547039. 1429547039.)
> @b{(file-last-access-and-modification-times-set! "nl.txt" -60)}
> @b{(t "nl.txt")}
(1429547006. 1429547006.)
> @b{(file-last-access-and-modification-times-set! "nl.txt" -60 0)}
> @b{(t "nl.txt")}
(1429547049. 1429547109.)
@end smallexample

@end deffn

@node Group information, User information, File information, Host environment
@section Group information

@deffn procedure group-info @var{group-name-or-id}

This procedure accesses the group database to get information about the
group identified by @var{group-name-or-id}, which is the group's symbolic
name (string) or the group's GID (exact integer).  A group-information
record is returned that contains the group's symbolic name, the group's
id (GID), and the group's members (list of symbolic user names).

For example:

@smallexample
> @b{(group-info "staff")}
#<group-info #2 name: "staff" gid: 20 members: ("root")>
> @b{(group-info 29)}
#<group-info #3
   name: "certusers"
   gid: 29
   members: ("root" "jabber" "postfix" "cyrusimap")>
> @b{(group-info 5000)}
*** ERROR IN (console)@@3.1 -- Resource temporarily unavailable
(group-info 5000)
@end smallexample

@end deffn

@deffn procedure group-info? @var{obj}

This procedure returns @code{#t} when @var{obj} is a group-information
record and @code{#f} otherwise.

For example:

@smallexample
> @b{(group-info? (group-info "daemon"))}
#t
> @b{(group-info? 123)}
#f
@end smallexample

@end deffn

@deffn procedure group-info-name @var{group-info}

Returns the symbolic name field of the group-information record
@var{group-info}.

For example:

@smallexample
> @b{(group-info-name (group-info 29))}
"certusers"
@end smallexample

@end deffn

@deffn procedure group-info-gid @var{group-info}

Returns the group id field of the group-information record
@var{group-info}.

For example:

@smallexample
> @b{(group-info-gid (group-info "staff"))}
20
@end smallexample

@end deffn

@deffn procedure group-info-members @var{group-info}

Returns the members field of the group-information record
@var{group-info}.

For example:

@smallexample
> @b{(group-info-members (group-info "staff"))}
("root")
@end smallexample

@end deffn

@node User information, Host information, Group information, Host environment
@section User information

@deffn procedure user-name

This procedure returns the user's name as a string.

For example:

@smallexample
> @b{(user-name)}
"feeley"
@end smallexample

@end deffn

@deffn procedure user-info @var{user-name-or-id}

This procedure accesses the user database to get information about the
user identified by @var{user-name-or-id}, which is the user's symbolic
name (string) or the user's UID (exact integer).  A user-information
record is returned that contains the user's symbolic name, the user's
id (UID), the user's group id (GID), the path to the user's home
directory, and the user's login shell.

For example:

@smallexample
> @b{(user-info "feeley")}
#<user-info #2
   name: "feeley"
   uid: 506
   gid: 506
   home: "/Users/feeley"
   shell: "/bin/bash">
> @b{(user-info 0)}
#<user-info #3 name: "root" uid: 0 gid: 0 home: "/var/root" shell: "/bin/sh">
> @b{(user-info 5000)}
*** ERROR IN (console)@@3.1 -- Resource temporarily unavailable
(user-info 5000)
@end smallexample

@end deffn

@deffn procedure user-info? @var{obj}

This procedure returns @code{#t} when @var{obj} is a user-information
record and @code{#f} otherwise.

For example:

@smallexample
> @b{(user-info? (user-info "feeley"))}
#t
> @b{(user-info? 123)}
#f
@end smallexample

@end deffn

@deffn procedure user-info-name @var{user-info}

Returns the symbolic name field of the user-information record
@var{user-info}.

For example:

@smallexample
> @b{(user-info-name (user-info 0))}
"root"
@end smallexample

@end deffn

@deffn procedure user-info-uid @var{user-info}

Returns the user id field of the user-information record
@var{user-info}.

For example:

@smallexample
> @b{(user-info-uid (user-info "feeley"))}
506
@end smallexample

@end deffn

@deffn procedure user-info-gid @var{user-info}

Returns the group id field of the user-information record
@var{user-info}.

For example:

@smallexample
> @b{(user-info-gid (user-info "feeley"))}
506
@end smallexample

@end deffn

@deffn procedure user-info-home @var{user-info}

Returns the home directory field of the user-information record
@var{user-info}.

For example:

@smallexample
> @b{(user-info-home (user-info 0))}
"/var/root"
@end smallexample

@end deffn

@deffn procedure user-info-shell @var{user-info}

Returns the shell field of the user-information record
@var{user-info}.

For example:

@smallexample
> @b{(user-info-shell (user-info 0))}
"/bin/sh"
@end smallexample

@end deffn

@node Host information, Service information, User information, Host environment
@section Host information

@deffn procedure host-name

This procedure returns the machine's host name as a string.

For example:

@smallexample
> @b{(host-name)}
"mega.iro.umontreal.ca"
@end smallexample

@end deffn

@deffn procedure host-info @var{host-name}

This procedure accesses the internet host database to get information
about the machine whose name is denoted by the string @var{host-name}.
A host-information record is returned that contains the official name
of the machine, a list of aliases (alternative names), and a non-empty
list of IP addresses for this machine.  An exception is raised when
@var{host-name} does not appear in the database.

For example:

@smallexample
> @b{(host-info "www.google.com")}
#<host-info #2
   name: "www.l.google.com"
   aliases: ("www.google.com")
   addresses: (#u8(66 249 85 99) #u8(66 249 85 104))>
> @b{(host-info "unknown.domain")}
*** ERROR IN (console)@@2.1 -- Unknown host
(host-info "unknown.domain")
@end smallexample

@end deffn

@deffn procedure host-info? @var{obj}

This procedure returns @code{#t} when @var{obj} is a host-information
record and @code{#f} otherwise.

For example:

@smallexample
> @b{(host-info? (host-info "www.google.com"))}
#t
> @b{(host-info? 123)}
#f
@end smallexample

@end deffn

@deffn procedure host-info-name @var{host-info}

Returns the official name field of the host-information record
@var{host-info}.

For example:

@smallexample
> @b{(host-info-name (host-info "www.google.com"))}
"www.l.google.com"
@end smallexample

@end deffn

@deffn procedure host-info-aliases @var{host-info}

Returns the aliases field of the host-information record
@var{host-info}.  This field is a possibly empty list of strings.

For example:

@smallexample
> @b{(host-info-aliases (host-info "www.google.com"))}
("www.google.com")
@end smallexample

@end deffn

@deffn procedure host-info-addresses @var{host-info}

Returns the addresses field of the host-information record
@var{host-info}.  This field is a non-empty list of u8vectors
denoting IP addresses.

For example:

@smallexample
> @b{(host-info-addresses (host-info "www.google.com"))}
(#u8(66 249 85 99) #u8(66 249 85 104))
@end smallexample

@end deffn

@deffn procedure address-infos @r{[}@code{host:} @var{host}@r{]} @r{[}@code{service:} @var{service}@r{]} @r{[}@code{family:} @var{family}@r{]} @r{[}@code{socket-type:} @var{socket-type}@r{]} @r{[}@code{protocol:} @var{protocol}@r{]}

This procedure is an interface to the @code{getaddrinfo} system call.
It accesses the internet host database to get information about the
machine whose name is denoted by the string @var{host} and service is
denoted by the string @var{service} and network address family is
@var{family} (@code{INET} or @code{INET6}) and network socket-type is
@var{socket-type} (@code{STREAM} or @code{DGRAM} or @code{RAW}) and
network protocol is @var{socket-type} (@code{TCP} or @code{UDP}).  A
list of address-information records is returned.

For example:

@smallexample
> @b{(address-infos host: "ftp.at.debian.org")}
(#<address-info #2
    family: INET6
    socket-type: DGRAM
    protocol: UDP
    socket-info:
     #<socket-info #3
        family: INET6
        port-number: 0
        address: #u16(8193 2136 2 1 0 0 0 16)>>
 #<address-info #4
    family: INET6
    socket-type: STREAM
    protocol: TCP
    socket-info:
     #<socket-info #5
        family: INET6
        port-number: 0
        address: #u16(8193 2136 2 1 0 0 0 16)>>
 #<address-info #6
    family: INET
    socket-type: DGRAM
    protocol: UDP
    socket-info:
     #<socket-info #7
        family: INET
        port-number: 0
        address: #u8(213 129 232 18)>>
 #<address-info #8
    family: INET
    socket-type: STREAM
    protocol: TCP
    socket-info:
     #<socket-info #9
        family: INET
        port-number: 0
        address: #u8(213 129 232 18)>>)
> @b{(address-infos host: "ftp.at.debian.org"
                 family: 'INET
                 protocol: 'TCP)}
(#<address-info #10
    family: INET
    socket-type: STREAM
    protocol: TCP
    socket-info:
     #<socket-info #11
        family: INET
        port-number: 0
        address: #u8(213 129 232 18)>>)
> @b{(address-infos host: "unknown.domain")}
*** ERROR IN (console)@@5.1 -- nodename nor servname provided, or not known
(address-infos host: "unknown.domain")
@end smallexample

@end deffn

@deffn procedure address-info? @var{obj}

This procedure returns @code{#t} when @var{obj} is an address-information
record and @code{#f} otherwise.

For example:

@smallexample
> @b{(map address-info?
       (address-infos host: "ftp.at.debian.org"))}
(#t #t #t #t)
> @b{(address-info? 123)}
#f
@end smallexample

@end deffn

@deffn procedure address-info-family @var{address-info}

Returns the family field of the address-information record
@var{address-info}.

For example:

@smallexample
> @b{(map address-info-family
       (address-infos host: "ftp.at.debian.org"))}
(INET6 INET6 INET INET)
@end smallexample

@end deffn

@deffn procedure address-info-socket-type @var{address-info}

Returns the socket-type field of the address-information record
@var{address-info}.

For example:

@smallexample
> @b{(map address-info-socket-type
       (address-infos host: "ftp.at.debian.org"))}
(DGRAM STREAM DGRAM STREAM)
@end smallexample

@end deffn

@deffn procedure address-info-protocol @var{address-info}

Returns the protocol field of the address-information record
@var{address-info}.

For example:

@smallexample
> @b{(map address-info-protocol
       (address-infos host: "ftp.at.debian.org"))}
(UDP TCP UDP TCP)
@end smallexample

@end deffn

@deffn procedure address-info-socket-info @var{address-info}

Returns the socket-info field of the address-information record
@var{address-info}.

For example:

@smallexample
> @b{(map address-info-socket-info
       (address-infos host: "ftp.at.debian.org"))}
(#<socket-info #2
    family: INET6
    port-number: 0
    address: #u16(8193 2136 2 1 0 0 0 16)>
 #<socket-info #3
    family: INET6
    port-number: 0
    address: #u16(8193 2136 2 1 0 0 0 16)>
 #<socket-info #4
    family: INET
    port-number: 0
    address: #u8(213 129 232 18)>
 #<socket-info #5
    family: INET
    port-number: 0
    address: #u8(213 129 232 18)>)
@end smallexample

@end deffn

@node Service information, Protocol information, Host information, Host environment
@section Service information

@deffn procedure service-info @var{service-name-or-id}

This procedure accesses the service database to get information about
the service identified by @var{service-name-or-id}, which is the
service's symbolic name (string) or the service's port number (exact
integer).  A service-information record is returned that contains the
service's symbolic name, a list of aliases (alternative names), the
port number (exact integer), and the protocol name (string).  An
exception is raised when @var{service-name-or-id} does not appear in
the database.

For example:

@smallexample
> @b{(service-info "http")}
#<service-info #2
   name: "http"
   aliases: ("www" "www-http")
   port-number: 80
   protocol: "udp">
> @b{(service-info 80)}
#<service-info #3
   name: "http"
   aliases: ("www" "www-http")
   port-number: 80
   protocol: "udp">
@end smallexample

@end deffn

@deffn procedure service-info? @var{obj}

This procedure returns @code{#t} when @var{obj} is a service-information
record and @code{#f} otherwise.

For example:

@smallexample
> @b{(service-info? (service-info "http"))}
#t
> @b{(service-info? 123)}
#f
@end smallexample

@end deffn

@deffn procedure service-info-name @var{service-info}

Returns the symbolic name field of the service-information record
@var{service-info}.

For example:

@smallexample
> @b{(service-info-name (service-info 80))}
"http"
@end smallexample

@end deffn

@deffn procedure service-info-aliases @var{service-info}

Returns the aliases field of the service-information record
@var{service-info}.  This field is a possibly empty list of strings.

For example:

@smallexample
> @b{(service-info-aliases (service-info "http"))}
("www" "www-http")
@end smallexample

@end deffn

@deffn procedure service-info-port-number @var{service-info}

Returns the service port number field of the service-information
record @var{service-info}.

For example:

@smallexample
> @b{(service-info-port-number (service-info "http"))}
80
@end smallexample

@end deffn

@deffn procedure service-info-protocol @var{service-info}

Returns the service protocol name field of the service-information
record @var{service-info}.

For example:

@smallexample
> @b{(service-info-protocol (service-info "http"))}
"udp"
@end smallexample

@end deffn

@node Protocol information, Network information, Service information, Host environment
@section Protocol information

@deffn procedure protocol-info @var{protocol-name-or-id}

This procedure accesses the protocol database to get information about
the protocol identified by @var{protocol-name-or-id}, which is the
protocol's symbolic name (string) or the protocol's number (exact
integer).  A protocol-information record is returned that contains the
protocol's symbolic name, a list of aliases (alternative names), and
the protocol number (32 bit unsigned exact integer).  An exception is
raised when @var{protocol-name-or-id} does not appear in the database.

For example:

@smallexample
> @b{(protocol-info "tcp")}
#<protocol-info #2 name: "tcp" aliases: ("TCP") number: 6>
> @b{(protocol-info 6)}
#<protocol-info #2 name: "tcp" aliases: ("TCP") number: 6>
@end smallexample

@end deffn

@deffn procedure protocol-info? @var{obj}

This procedure returns @code{#t} when @var{obj} is a protocol-information
record and @code{#f} otherwise.

For example:

@smallexample
> @b{(protocol-info? (protocol-info "tcp"))}
#t
> @b{(protocol-info? 123)}
#f
@end smallexample

@end deffn

@deffn procedure protocol-info-name @var{protocol-info}

Returns the symbolic name field of the protocol-information record
@var{protocol-info}.

For example:

@smallexample
> @b{(protocol-info-name (protocol-info 6))}
"tcp"
@end smallexample

@end deffn

@deffn procedure protocol-info-aliases @var{protocol-info}

Returns the aliases field of the protocol-information record
@var{protocol-info}.  This field is a possibly empty list of strings.

For example:

@smallexample
> @b{(protocol-info-aliases (protocol-info "tcp"))}
("TCP")
@end smallexample

@end deffn

@deffn procedure protocol-info-number @var{protocol-info}

Returns the protocol number field of the protocol-information record
@var{protocol-info}.

For example:

@smallexample
> @b{(protocol-info-number (protocol-info "tcp"))}
6
@end smallexample

@end deffn

@node Network information, , Protocol information, Host environment
@section Network information

@deffn procedure network-info @var{network-name-or-id}

This procedure accesses the network database to get information about
the network identified by @var{network-name-or-id}, which is the
network's symbolic name (string) or the network's number (exact
integer).  A network-information record is returned that contains the
network's symbolic name, a list of aliases (alternative names), and
the network number (32 bit unsigned exact integer).  An exception is
raised when @var{network-name-or-id} does not appear in the database.

For example:

@smallexample
> @b{(network-info "loopback")}
#<network-info #2
   name: "loopback"
   aliases: ("loopback-net")
   number: 127>
> @b{(network-info 127)}
#<network-info #3
   name: "loopback"
   aliases: ("loopback-net")
   number: 127>
@end smallexample

@end deffn

@deffn procedure network-info? @var{obj}

This procedure returns @code{#t} when @var{obj} is a network-information
record and @code{#f} otherwise.

For example:

@smallexample
> @b{(network-info? (network-info "loopback"))}
#t
> @b{(network-info? 123)}
#f
@end smallexample

@end deffn

@deffn procedure network-info-name @var{network-info}

Returns the symbolic name field of the network-information record
@var{network-info}.

For example:

@smallexample
> @b{(network-info-name (network-info 127))}
"loopback"
@end smallexample

@end deffn

@deffn procedure network-info-aliases @var{network-info}

Returns the aliases field of the network-information record
@var{network-info}.  This field is a possibly empty list of strings.

For example:

@smallexample
> @b{(network-info-aliases (network-info "loopback"))}
("loopback-net")
@end smallexample

@end deffn

@deffn procedure network-info-number @var{network-info}

Returns the network number field of the network-information record
@var{network-info}.

For example:

@smallexample
> @b{(network-info-number (network-info "loopback"))}
127
@end smallexample

@end deffn

@node I/O and ports, Lexical syntax and readtables, Host environment, Top
@chapter I/O and ports

@menu
* Unidirectional and bidirectional ports::  Unidirectional and bidirectional ports
* Port classes::                            Port classes
* Port settings::                           Port settings
* Object-ports::                            Object-ports
* Character-ports::                         Character-ports
* Byte-ports::                              Byte-ports
* Device-ports::                            Device-ports
* Directory-ports::                         Directory-ports
* Vector-ports::                            Vector-ports
* String-ports::                            String-ports
* U8vector-ports::                          U8vector-ports
* Other procedures related to I/O::         Other procedures related to I/O
@end menu

@node Unidirectional and bidirectional ports, Port classes, I/O and ports, I/O and ports
@section Unidirectional and bidirectional ports

Unidirectional ports allow communication between a producer of
information and a consumer.  An input-port's producer is typically a
resource managed by the operating system (such as a file, a process or
a network connection) and the consumer is the Scheme program.  The
roles are reversed for an output-port.

Associated with each port are settings that affect I/O operations on
that port (encoding of characters to bytes, end-of-line encoding, type
of buffering, etc).  Port settings are specified when the port is
created.  Some port settings can be changed after a port is created.

Bidirectional ports, also called input-output-ports, allow
communication in both directions.  They are best viewed as an object
that groups two separate unidirectional ports (one in each direction).
Each direction has its own port settings and can be closed
independently from the other direction.

@node Port classes, Port settings, Unidirectional and bidirectional ports, I/O and ports
@section Port classes

The four classes of ports listed below form an inheritance hierarchy.
Operations possible for a certain class of port are also possible for
the subclasses.  Only device-ports are connected to a device managed
by the operating system.  For instance it is possible to create ports
that behave as a FIFO where the Scheme program is both the producer
and consumer of information (possibly one thread is the producer and
another thread is the consumer).

@enumerate

@item
An @dfn{object-port} (or simply a port) provides operations to read
and write Scheme data (i.e. any Scheme object) to/from the port.  It
also provides operations to force output to occur, to change the way
threads block on the port, and to close the port.  Note that the class
of objects for which write/read invariance is guaranteed depends on
the particular class of port.

@item
A @dfn{character-port} provides all the operations of an object-port,
and also operations to read and write individual characters to/from
the port.  When a Scheme object is written to a character-port, it is
converted into the sequence of characters that corresponds to its
external-representation.  When reading a Scheme object, an inverse
conversion occurs.  Note that some Scheme objects do not have an
external textual representation that can be read back.

@item
A @dfn{byte-port} provides all the operations of a character-port, and
also operations to read and write individual bytes to/from the port.
When a character is written to a byte-port, some encoding of that
character into a sequence of bytes will occur (for example,
@code{#\newline} will be encoded as the 2 bytes CR-LF when using
ISO-8859-1 character encoding and @code{cr-lf} end-of-line encoding, and
a non-ASCII character will generate more than 1 byte when using UTF-8
character encoding).  When reading a character, a similar decoding
occurs.

@item
A @dfn{device-port} provides all the operations of a byte-port, and
also operations to control the operating system managed device (file,
network connection, terminal, etc) that is connected to the port.

@end enumerate

@node Port settings, Object-ports, Port classes, I/O and ports
@section Port settings

Some port settings are only valid for specific port classes whereas
some others are valid for all ports.  Port settings are specified when
a port is created.  The settings that are not specified will default
to some reasonable values.  Keyword objects are used to name the
settings to be set.  As a simple example, a device-port connected to
the file @code{"foo"} can be created using the call

@smallexample
@b{}(open-input-file "foo")
@end smallexample

This will use default settings for the character encoding, buffering,
etc.  If the UTF-8 character encoding is desired, then the port could
be opened using the call

@smallexample
@b{}(open-input-file (list path: "foo" char-encoding: 'UTF-8))
@end smallexample

Here the argument of the procedure @code{open-input-file} has been
replaced by a @dfn{port settings list} which specifies the value of
each port setting that should not be set to the default value.  Note
that some port settings have no useful default and it is therefore
required to specify a value for them, such as the @code{path:} in the
case of the file opening procedures.  All port creation procedures
(i.e. named @code{open-...}) take a single argument that can either
be a port settings list or a value of a type that depends on the kind
of port being created (a path string for files, an IP port number for
socket servers, etc).

@node Object-ports, Character-ports, Port settings, I/O and ports
@section Object-ports

@menu
* Object-port settings::             Object-port settings
* Object-port operations::           Object-port operations
@end menu

@node Object-port settings, Object-port operations, Object-ports, Object-ports
@subsection Object-port settings

The following is a list of port settings that are valid for all types
of ports.

@itemize

@item
@code{direction:} ( @code{input} | @code{output} | @code{input-output} )

This setting controls the direction of the port.  The symbol
@code{input} indicates a unidirectional input-port, the symbol
@code{output} indicates a unidirectional output-port, and the symbol
@code{input-output} indicates a bidirectional port.  The default
value of this setting depends on the port creation procedure.

@item
@code{buffering:} ( @code{#f} | @code{#t} | @code{line} )

This setting controls the buffering of the port.  To set each
direction separately the keywords @code{input-buffering:} and
@code{output-buffering:} must be used instead of @code{buffering:}.
The value @code{#f} selects unbuffered I/O, the value @code{#t}
selects fully buffered I/O, and the symbol @code{line} selects line
buffered I/O (the output buffer is drained when a @code{#\newline}
character is written).  Line buffered I/O only applies to
character-ports.  The default value of this setting is operating
system dependent except consoles which are unbuffered.

@end itemize

@node Object-port operations, , Object-port settings, Object-ports
@subsection Object-port operations

@deffn procedure input-port? @var{obj}
@deffnx procedure output-port? @var{obj}
@deffnx procedure port? @var{obj}

The procedure @code{input-port?} returns @code{#t} when @var{obj} is a
unidirectional input-port or a bidirectional port and @code{#f}
otherwise.

The procedure @code{output-port?} returns @code{#t} when @var{obj} is a
unidirectional output-port or a bidirectional port and @code{#f}
otherwise.

The procedure @code{port?} returns @code{#t} when @var{obj} is a port
(either unidirectional or bidirectional) and @code{#f} otherwise.

For example:

@smallexample
> @b{(input-port? (current-input-port))}
#t
> @b{(call-with-input-string "some text" output-port?)}
#f
> @b{(port? (current-output-port))}
#t
@end smallexample

@end deffn

@deffn procedure read @r{[}@var{port}@r{]}

This procedure reads and returns the next Scheme datum from the
input-port @var{port}.  The end-of-file object is returned when the
end of the stream is reached.  If it is not specified, @var{port}
defaults to the current input-port.

For example:

@smallexample
> @b{(call-with-input-string "some text" read)}
some
> @b{(call-with-input-string "" read)}
#!eof
@end smallexample

@end deffn

@deffn procedure read-all @r{[}@var{port} @r{[}@var{reader}@r{]}@r{]}

This procedure repeatedly calls the procedure @var{reader} with
@var{port} as the sole argument and accumulates a list of each value
returned up to the end-of-file object.  The procedure @code{read-all}
returns the accumulated list without the end-of-file object.  If it is
not specified, @var{port} defaults to the current input-port.  If it
is not specified, @var{reader} defaults to the procedure @code{read}.

For example:

@smallexample
> @b{(call-with-input-string "3,2,1\ngo!" read-all)}
(3 ,2 ,1 go!)
> @b{(call-with-input-string "3,2,1\ngo!"
                          (lambda (p) (read-all p read-char)))}
(#\3 #\, #\2 #\, #\1 #\newline #\g #\o #\!)
> @b{(call-with-input-string "3,2,1\ngo!"
                          (lambda (p) (read-all p read-line)))}
("3,2,1" "go!")
@end smallexample

@end deffn

@deffn procedure write @var{obj} @r{[}@var{port}@r{]}

This procedure writes the Scheme datum @var{obj} to the output-port
@var{port} and the value returned is unspecified.  If it is not
specified, @var{port} defaults to the current output-port.

For example:

@smallexample
> @b{(write (list 'compare (list 'quote '@@x) 'and (list 'unquote '@@x))) }
(compare '@@x and , @@x)> 
@end smallexample

@end deffn

@deffn procedure newline @r{[}@var{port}@r{]}

This procedure writes an ``object separator'' to the output-port
@var{port} and the value returned is unspecified.  The separator
ensures that the next Scheme datum written with the @code{write}
procedure will not be confused with the latest datum that was written.
On character-ports this is done by writing the character
@code{#\newline}.  On ports where successive objects are implicitly
distinct (such as ``vector ports'') this procedure does nothing.

Regardless of the class of a port @var{p} and assuming that the
external textual representation of the object @var{x} is readable, the
expression @code{(begin (write @var{x} @var{p}) (newline @var{p}))}
will write to @var{p} a representation of @var{x} that can be read
back with the procedure @code{read}.  If it is not specified,
@var{port} defaults to the current output-port.

For example:

@smallexample
> @b{(begin (write 123) (newline) (write 456) (newline))}
123
456
@end smallexample

@end deffn

@deffn procedure force-output @r{[}@var{port} @r{[}@var{level}@r{]}@r{]}

The procedure @code{force-output} causes the data that was written to
the output-port @var{port} to be moved closer to its destination
according to @var{level}, an exact integer in the range 0 to 2.  If
@var{port} is not specified, the current output-port is used.  If
@var{level} is not specified, it defaults to 0.  Values of @var{level}
above 0 are equivalent to @var{level} = 0 except for device ports as
explained below.

When @var{level} is 0, the output buffers of @var{port} which are
managed in the Scheme process are drained (i.e.  the output operation
that was delayed due to buffering is actually performed).  In the case
of a device port the data is passed to the operating system and it
becomes its responsibility to transmit the data to the device.  The
operating system may implement its own buffering approach which delays
the transmission of the data to the device.

When @var{level} is 1, in addition to the operations for @var{level} =
0 and if the operating system supports the functionality, the
operating system is requested to transmit the data to the device.  On
UNIX this corresponds to a @code{fsync} system call.

When @var{level} is 2, in addition to the operations for @var{level} =
1 and if the operating system supports the functionality, the
operating system is requested to wait until the device reports that
the data was saved by the device (e.g. actually written to disk in the
case of a file).  This operation can take a long time on some
operating systems.  On Mac OS X this corresponds to a @code{fcntl}
system call with operation @code{F_FULLFSYNC}.

For example:

@smallexample
> @b{(define p (open-tcp-client "www.iro.umontreal.ca:80"))}
> @b{(display "GET /\n" p)}
> @b{(force-output p)}
> @b{(read-line p)}
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""
@end smallexample

@end deffn

@deffn procedure close-input-port @var{port}
@deffnx procedure close-output-port @var{port}
@deffnx procedure close-port @var{port}

The @var{port} argument of these procedures must be a unidirectional
or a bidirectional port.  For all three procedures the value returned
is unspecified.

The procedure @code{close-input-port} closes the input-port side of
@var{port}, which must not be a unidirectional output-port.

The procedure @code{close-output-port} closes the output-port side of
@var{port}, which must not be a unidirectional input-port.  The ouput
buffers are drained before @var{port} is closed.

The procedure @code{close-port} closes all sides of the @var{port}.
Unless @var{port} is a unidirectional input-port, the output buffers
are drained before @var{port} is closed.

For example:

@smallexample
> @b{(define p (open-tcp-client "www.iro.umontreal.ca:80"))}
> @b{(display "GET /\n" p)}
> @b{(close-output-port p)}
> @b{(read-line p)}
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""
@end smallexample

@end deffn

@deffn procedure input-port-timeout-set! @var{port} @var{timeout} @r{[}@var{thunk}@r{]}
@deffnx procedure output-port-timeout-set! @var{port} @var{timeout} @r{[}@var{thunk}@r{]}

When a thread tries to perform an I/O operation on a port, the
requested operation may not be immediately possible and the thread
must wait.  For example, the thread may be trying to read a line of
text from the console and the user has not typed anything yet, or the
thread may be trying to write to a network connection faster than the
network can handle.  In such situations the thread normally blocks
until the operation becomes possible.

It is sometimes necessary to guarantee that the thread will not block
too long.  For this purpose, to each input-port and output-port is
attached a @dfn{timeout} and @dfn{timeout-thunk}.  The timeout
indicates the point in time beyond which the thread should stop
waiting on an input and output operation respectively.  When the
timeout is reached, the thread calls the port's timeout-thunk.  If the
timeout-thunk returns @code{#f} the thread abandons trying to perform
the operation (in the case of an input operation an end-of-file is
read and in the case of an output operation an exception is raised).
Otherwise, the thread will block again waiting for the operation to
become possible (note that if the port's timeout has not changed the
thread will immediately call the timeout-thunk again).

The procedure @code{input-port-timeout-set!} sets the timeout of the
input-port @var{port} to @var{timeout} and the timeout-thunk to
@var{thunk}.  The procedure @code{output-port-timeout-set!} sets the
timeout of the output-port @var{port} to @var{timeout} and the
timeout-thunk to @var{thunk}.  If it is not specified, the @var{thunk}
defaults to a thunk that returns @code{#f}.  The @var{timeout} is
either a time object indicating an absolute point in time, or it is a
real number which indicates the number of seconds relative to the
moment the procedure is called.  For both procedures the value
returned is unspecified.

When a port is created the timeout is set to infinity (@code{+inf.0}).
This causes the thread to wait as long as needed for the operation to
become possible.  Setting the timeout to a point in the past
(@code{-inf.0}) will cause the thread to attempt the I/O operation and
never block (i.e. the timeout-thunk is called if the operation is not
immediately possible).

The following example shows how to cause the REPL to terminate
when the user does not enter an expression within the next 60 seconds.

@smallexample
> @b{(input-port-timeout-set! (repl-input-port) 60)}
> 
*** EOF again to exit
@end smallexample

@end deffn

@node Character-ports, Byte-ports, Object-ports, I/O and ports
@section Character-ports

@menu
* Character-port settings::          Character-port settings
* Character-port operations::        Character-port operations
@end menu

@node Character-port settings, Character-port operations, Character-ports, Character-ports
@subsection Character-port settings

The following is a list of port settings that are valid for
character-ports.

@itemize

@item
@code{readtable:} @var{readtable}

This setting determines the readtable attached to the character-port.
To set each direction separately the keywords @code{input-readtable:}
and @code{output-readtable:} must be used instead of
@code{readtable:}.  Readtables control the external textual
representation of Scheme objects, that is the encoding of Scheme
objects using characters.  The behavior of the @code{read} procedure
depends on the port's input-readtable and the behavior of the
procedures @code{write}, @code{pretty-print}, and related procedures
is affected by the port's output-readtable.  The default value of this
setting is the value bound to the parameter object
@code{current-readtable}.

@item
@code{output-width:} @var{positive-integer}

This setting indicates the width of the character output-port in
number of characters.  This information is used by the pretty-printer.
The default value of this setting is 80.

@end itemize

@node Character-port operations, , Character-port settings, Character-ports
@subsection Character-port operations

@deffn procedure input-port-line @var{port}
@deffnx procedure input-port-column @var{port}
@deffnx procedure output-port-line @var{port}
@deffnx procedure output-port-column @var{port}

The current character location of a character input-port is the
location of the next character to read.  The current character
location of a character output-port is the location of the next
character to write.  Location is denoted by a line number (the first
line is line 1) and a column number, that is the location on the
current line (the first column is column 1).  The procedures
@code{input-port-line} and @code{input-port-column} return the line
location and the column location respectively of the character
input-port @var{port}.  The procedures @code{output-port-line} and
@code{output-port-column} return the line location and the column
location respectively of the character output-port @var{port}.

For example:

@smallexample
> @b{(call-with-output-string
    '()
    (lambda (p)
      (display "abc\n123def" p)
      (write (list (output-port-line p) (output-port-column p))
             p)))}
"abc\n123def(2 7)"
@end smallexample

@end deffn

@deffn procedure output-port-width @var{port}

This procedure returns the width, in characters, of the character
output-port @var{port}.  The value returned is the port's output-width
setting.

For example:

@smallexample
> @b{(output-port-width (repl-output-port))}
80
@end smallexample

@end deffn

@deffn procedure read-char @r{[}@var{port}@r{]}

This procedure reads the character input-port @var{port} and returns
the character at the current character location and advances the
current character location to the next character, unless the
@var{port} is already at end-of-file in which case @code{read-char}
returns the end-of-file object.  If it is not specified, @var{port}
defaults to the current input-port.

For example:

@smallexample
> @b{(call-with-input-string
    "some text"
    (lambda (p)
      (let ((a (read-char p))) (list a (read-char p)))))}
(#\s #\o)
> @b{(call-with-input-string "" read-char)}
#!eof
@end smallexample

@end deffn

@deffn procedure peek-char @r{[}@var{port}@r{]}

This procedure returns the same result as @code{read-char} but it does
not advance the current character location of the input-port
@var{port}.  If it is not specified, @var{port} defaults to the
current input-port.

For example:

@smallexample
> @b{(call-with-input-string
    "some text"
    (lambda (p)
      (let ((a (peek-char p))) (list a (read-char p)))))}
(#\s #\s)
> @b{(call-with-input-string "" peek-char)}
#!eof
@end smallexample

@end deffn

@deffn procedure write-char @var{char} @r{[}@var{port}@r{]}

This procedure writes the character @var{char} to the character
output-port @var{port} and advances the current character location of
that output-port.  The value returned is unspecified.  If it is not
specified, @var{port} defaults to the current output-port.

For example:

@smallexample
> @b{(write-char #\=)}
=> 
@end smallexample

@end deffn

@deffn procedure read-line @r{[}@var{port} @r{[}@var{separator} @r{[}@var{include-separator?} @r{[}@var{max-length}@r{]}@r{]}@r{]}@r{]}

This procedure reads characters from the character input-port
@var{port} until a specific @var{separator} or the end-of-file is
encountered and returns a string containing the sequence of characters
read.  If it is specified, @var{max-length} must be a nonnegative
exact integer and it places an upper limit on the number of characters
that are read.

The @var{separator} is included at the end of the string only
if it was the last character read and @var{include-separator?} is not
@code{#f}.  The @var{separator} must be a character or @code{#f} (in
which case all the characters until the end-of-file are read).  If it
is not specified, @var{port} defaults to the current input-port.  If
it is not specified, @var{separator} defaults to @code{#\newline}.  If
it is not specified, @var{include-separator?} defaults to @code{#f}.

For example:

@smallexample
> @b{(define (split sep)
    (lambda (str)
      (call-with-input-string
        str
        (lambda (p)
          (read-all p (lambda (p) (read-line p sep)))))))}
> @b{((split #\,) "a,b,c")}
("a" "b" "c")
> @b{(map (split #\,)
       (call-with-input-string "1,2,3\n4,5"
                               (lambda (p) (read-all p read-line))))}
(("1" "2" "3") ("4" "5"))
> @b{(read-line (current-input-port) #\newline #f 2)1234}
"12"
> 34
@end smallexample

@end deffn

@deffn procedure read-substring @var{string} @var{start} @var{end} @r{[}@var{port} @r{[}@var{need}@r{]}@r{]}
@deffnx procedure write-substring @var{string} @var{start} @var{end} @r{[}@var{port}@r{]}

These procedures support bulk character I/O.  The part of the string
@var{string} starting at index @var{start} and ending just before
index @var{end} is used as a character buffer that will be the target
of @code{read-substring} or the source of the @code{write-substring}.
The @code{read-substring} also accepts a @var{need} parameter which
must be a nonnegative fixnum.  Up to @var{end}-@var{start} characters
will be transferred.  The number of characters transferred, possibly
zero, is returned by these procedures.  Fewer characters will be read
by @code{read-substring} if an end-of-file is read, or a timeout
occurs before all the requested characters are transferred and the
timeout thunk returns @code{#f} (see the procedure
@code{input-port-timeout-set!}), or @var{need} is specified and at
least that many characters have been read (in other words the
procedure does not block for more characters but may transfer more
characters if they are immediately available).  Fewer characters will
be written by @code{write-substring} if a timeout occurs before all
the requested characters are transferred and the timeout thunk returns
@code{#f} (see the procedure @code{output-port-timeout-set!}).  If it
is not specified, @var{port} defaults to the current input-port and
current output-port respectively.

For example:

@smallexample
> @b{(define s (make-string 10 #\x))}
> @b{(read-substring s 2 5)123456789}
3
> 456789
> @b{s}
"xx123xxxxx"
> @b{(read-substring s 2 10 (current-input-port) 3)abcd}
5
> @b{s}
"xxabcd\nxxx"
@end smallexample

@end deffn

@deffn procedure input-port-readtable @var{port}
@deffnx procedure output-port-readtable @var{port}

These procedures return the readtable attached to the character-port
@var{port}.  The @var{port} parameter of @code{input-port-readtable}
must be an input-port.  The @var{port} parameter of
@code{output-port-readtable} must be an output-port.

@end deffn

@deffn procedure input-port-readtable-set! @var{port} @var{readtable}
@deffnx procedure output-port-readtable-set! @var{port} @var{readtable}

These procedures change the readtable attached to the character-port
@var{port} to the readtable @var{readtable}.  The @var{port} parameter
of @code{input-port-readtable-set!}  must be an input-port.  The
@var{port} parameter of @code{output-port-readtable-set!} must be an
output-port.  The value returned is unspecified.

@end deffn

@node Byte-ports, Device-ports, Character-ports, I/O and ports
@section Byte-ports

@menu
* Byte-port settings::               Byte-port settings
* Byte-port operations::             Byte-port operations
@end menu

@node Byte-port settings, Byte-port operations, Byte-ports, Byte-ports
@subsection Byte-port settings

The following is a list of port settings that are valid for
byte-ports.

@itemize

@item
@code{char-encoding:} @var{encoding}

This setting controls the character encoding of the byte-port.  For
bidirectional byte-ports, the character encoding for input and output
is set.  To set each direction separately the keywords
@code{input-char-encoding:} and @code{output-char-encoding:} must be
used instead of @code{char-encoding:}.  The default value of this
setting is operating system dependent, but this can be overridden
through the runtime options (@pxref{Runtime options}).  The following
encodings are supported:

@table @code

@item ISO-8859-1
ISO-8859-1 character encoding.  Each character is encoded by a single byte.
Only Unicode characters with a code in the range 0 to 255 are allowed.

@item ASCII
ASCII character encoding.  Each character is encoded by a single byte.
In principle only Unicode characters with a code in the range 0 to 127
are allowed but most types of ports treat this exactly like @code{ISO-8859-1}.

@item UTF-8
UTF-8 character encoding.  Each character is encoded by a sequence of one
to four bytes.  The minimum length UTF-8 encoding is used.  If a BOM is
needed at the beginning of the stream then it must be explicitly
written.

@item UTF-16
UTF-16 character encoding.  Each character is encoded by one or two 16
bit integers (2 or 4 bytes).  The 16 bit integers may be encoded using
little-endian encoding or big-endian encoding.  If the port is an
input-port and the first two bytes read are a BOM (``Byte Order Mark''
character with hexadecimal code FEFF) then the BOM will be discarded
and the endianness will be set accordingly, otherwise the endianness
depends on the operating system and how the Gambit runtime was
compiled.  If the port is an output-port then a BOM will be output at
the beginning of the stream and the endianness depends on the
operating system and how the Gambit runtime was compiled.

@item UTF-16LE
UTF-16 character encoding with little-endian endianness.  It is like
@code{UTF-16} except the endianness is set to little-endian and there is no
BOM processing.  If a BOM is needed at the beginning of the stream
then it must be explicitly written.

@item UTF-16BE
UTF-16 character encoding with big-endian endianness.  It is like
@code{UTF-16LE} except the endianness is set to big-endian.

@item UTF / UTF-fallback-ASCII / UTF-fallback-ISO-8859-1 / UTF-fallback-UTF-16 / UTF-fallback-UTF-16LE / UTF-fallback-UTF-16BE
These encodings combine the UTF-8 and UTF-16 encodings.  When one of
these character encodings is used for an output port, characters will
be encoded using the UTF-8 encoding.  The first character, if there is
one, is prefixed with a UTF-8 BOM (the three byte sequence EF BB BF in
hexadecimal).  When one of these character encodings is used for an
input port, the character encoding depends on the first few bytes.  If
the first bytes of the stream are a UTF-16LE BOM (FF FE in
hexadecimal), or a UTF-16BE BOM (FE FF in hexadecimal), or a UTF-8 BOM
(EF BB BF in hexadecimal), then the BOM is discarded and the remaining
bytes of the stream are decoded using the corresponding character
encoding.  If a BOM is not present, then the stream is decoded using
the fallback encoding specified.  The encoding @code{UTF} is a synonym
for @code{UTF-fallback-UTF-8}.  Note that the @code{UTF} character
encoding for input will correctly handle streams produced using the
encodings @code{UTF}, @code{UTF-8}, @code{UTF-16}, @code{ASCII}, and
if an explicit BOM is output, the encodings @code{UTF-16LE}, and
@code{UTF-16BE}.

@item UCS-2
UCS-2 character encoding.  Each character is encoded by a 16 bit
integer (2 bytes).  The 16 bit integers may be encoded using
little-endian encoding or big-endian encoding.  If the port is an
input-port and the first two bytes read are a BOM (``Byte Order Mark''
character with hexadecimal code FEFF) then the BOM will be discarded
and the endianness will be set accordingly, otherwise the endianness
depends on the operating system and how the Gambit runtime was
compiled.  If the port is an output-port then a BOM will be output at
the beginning of the stream and the endianness depends on the
operating system and how the Gambit runtime was compiled.

@item UCS-2LE
UCS-2 character encoding with little-endian endianness.  It is like
@code{UCS-2} except the endianness is set to little-endian and there is no
BOM processing.  If a BOM is needed at the beginning of the stream
then it must be explicitly written.

@item UCS-2BE
UCS-2 character encoding with big-endian endianness.  It is like
@code{UCS-2LE} except the endianness is set to big-endian.

@item UCS-4
UCS-4 character encoding.  Each character is encoded by a 32 integer
(4 bytes).  The 32 bit integers may be encoded using little-endian
encoding or big-endian encoding.  If the port is an input-port and the
first four bytes read are a BOM (``Byte Order Mark'' character with
hexadecimal code 0000FEFF) then the BOM will be discarded and the
endianness will be set accordingly, otherwise the endianness depends
on the operating system and how the Gambit runtime was compiled.  If
the port is an output-port then a BOM will be output at the beginning
of the stream and the endianness depends on the operating system and
how the Gambit runtime was compiled.

@item UCS-4LE
UCS-4 character encoding with little-endian endianness.  It is like
@code{UCS-4} except the endianness is set to little-endian and there is no
BOM processing.  If a BOM is needed at the beginning of the stream
then it must be explicitly written.

@item UCS-4BE
UCS-4 character encoding with big-endian endianness.  It is like
@code{UCS-4LE} except the endianness is set to big-endian.

@end table

@item
@code{char-encoding-errors:} ( @code{#f} | @code{#t} )

This setting controls whether illegal character encodings are silently
replaced with the Unicode character #xfffd (replacement character) or
raise an error.  To set each direction separately the keywords
@code{input-char-encoding-errors:} and
@code{output-char-encoding-errors:} must be used instead of
@code{char-encoding-errors:}.  The default value of this setting is
@code{#t}.

@item
@code{eol-encoding:} @var{encoding}

This setting controls the end-of-line encoding of the byte-port.  To
set each direction separately the keywords @code{input-eol-encoding:}
and @code{output-eol-encoding:} must be used instead of
@code{eol-encoding:}.  The default value of this setting is operating
system dependent, but this can be overridden through the runtime
options (@pxref{Runtime options}).  Note that for output-ports the
end-of-line encoding is applied before the character encoding, and for
input-ports it is applied after.  The following encodings are
supported:

@table @code

@item lf
For an output-port, writing a @code{#\newline} character outputs a
@code{#\linefeed} character to the stream (Unicode character code 10).
For an input-port, a @code{#\newline} character is read when a
@code{#\linefeed} character is encountered on the stream.  Note that
@code{#\linefeed} and @code{#\newline} are two names for the same
character, so this end-of-line encoding is actually the identity
function.  Text files created by UNIX applications typically use this
end-of-line encoding.

@item cr
For an output-port, writing a @code{#\newline} character outputs a
@code{#\return} character to the stream (Unicode character code 13).
For an input-port, a @code{#\newline} character is read when a
@code{#\linefeed} character or a @code{#\return} character is
encountered on the stream.  Text files created by Classic Mac OS
applications typically use this end-of-line encoding.

@item cr-lf
For an output-port, writing a @code{#\newline} character outputs to
the stream a @code{#\return} character followed by a @code{#\linefeed}
character.  For an input-port, a @code{#\newline} character is read
when a @code{#\linefeed} character or a @code{#\return} character is
encountered on the stream.  Moreover, if this character is immediately
followed by the opposite character (@code{#\linefeed} followed by
@code{#\return} or @code{#\return} followed by @code{#\linefeed}) then
the second character is ignored.  In other words, all four possible
end-of-line encodings are read as a single @code{#\newline} character.
Text files created by DOS and Microsoft Windows applications typically
use this end-of-line encoding.

@end table

@end itemize

@node Byte-port operations, , Byte-port settings, Byte-ports
@subsection Byte-port operations

@deffn procedure read-u8 @r{[}@var{port}@r{]}

This procedure reads the byte input-port @var{port} and returns the
byte at the current byte location and advances the current byte
location to the next byte, unless the @var{port} is already at
end-of-file in which case @code{read-u8} returns the end-of-file
object.  If it is not specified, @var{port} defaults to the current
input-port.

This procedure must be called when the port's input character buffer
is empty otherwise the character-stream and byte-stream may be out of
sync due to buffering.  The input character buffer is used for bulk
decoding of encoded characters (i.e. to translate the byte-stream into
a character-stream).  The input character buffer is initially empty.
It is only when characters are read that it is filled with characters
obtained by decoding the byte-stream.

One way to ensure that the port's input character buffer is empty is
to call @code{read-u8} strictly before any use of the port in a character
input operation (i.e. a call to the procedures @code{read},
@code{read-char}, @code{peek-char}, etc).  Alternatively
@code{input-port-characters-buffered} can be used to get the number of
characters in the port's input character buffer, and to empty the
buffer with calls to @code{read-char} or @code{read-substring}.

For example:

@smallexample
> @b{(call-with-input-u8vector
    '#u8(11 22 33 44)
    (lambda (p)
      (let ((a (read-u8 p))) (list a (read-u8 p)))))}
(11 22)
> @b{(call-with-input-u8vector '#u8() read-u8)}
#!eof
@end smallexample

@end deffn

@deffn procedure write-u8 @var{n} @r{[}@var{port}@r{]}

This procedure writes the byte @var{n} to the byte output-port
@var{port} and advances the current byte location of that output-port.
The value returned is unspecified.  If it is not specified, @var{port}
defaults to the current output-port.

For example:

@smallexample
> @b{(call-with-output-u8vector '() (lambda (p) (write-u8 33 p)))}
#u8(33)
@end smallexample

@end deffn

@deffn procedure read-subu8vector @var{u8vector} @var{start} @var{end} @r{[}@var{port} @r{[}@var{need}@r{]}@r{]}
@deffnx procedure write-subu8vector @var{u8vector} @var{start} @var{end} @r{[}@var{port}@r{]}

These procedures support bulk byte I/O.  The part of the u8vector
@var{u8vector} starting at index @var{start} and ending just before
index @var{end} is used as a byte buffer that will be the target of
@code{read-subu8vector} or the source of the @code{write-subu8vector}.
The @code{read-subu8vector} also accepts a @var{need} parameter which
must be a nonnegative fixnum.  Up to @var{end}-@var{start} bytes will
be transferred.  The number of bytes transferred, possibly zero, is
returned by these procedures.  Fewer bytes will be read by
@code{read-subu8vector} if an end-of-file is read, or a timeout occurs
before all the requested bytes are transferred and the timeout thunk
returns @code{#f} (see the procedure @code{input-port-timeout-set!}),
or @var{need} is specified and at least that many bytes have been read
(in other words the procedure does not block for more bytes but may
transfer more bytes if they are immediately available).  Fewer bytes
will be written by @code{write-subu8vector} if a timeout occurs before
all the requested bytes are transferred and the timeout thunk returns
@code{#f} (see the procedure @code{output-port-timeout-set!}).  If it
is not specified, @var{port} defaults to the current input-port and
current output-port respectively.

The procedure @code{read-subu8vector} must be called before any use of
the port in a character input operation (i.e. a call to the procedures
@code{read}, @code{read-char}, @code{peek-char}, etc) because
otherwise the character-stream and byte-stream may be out of sync due
to the port buffering.

For example:

@smallexample
> @b{(define v (make-u8vector 10))}
> @b{(read-subu8vector v 2 5)123456789}
3
> 456789
> @b{v}
#u8(0 0 49 50 51 0 0 0 0 0)
> @b{(read-subu8vector v 2 10 (current-input-port) 3)abcd}
5
> @b{v}
#u8(0 0 97 98 99 100 10 0 0 0)
@end smallexample

@end deffn

@node Device-ports, Directory-ports, Byte-ports, I/O and ports
@section Device-ports

@menu
* Filesystem devices::            Filesystem devices
* Process devices::               Process devices
* Network devices::               Network devices
@end menu

@node Filesystem devices, Process devices, Device-ports, Device-ports
@subsection Filesystem devices

@deffn procedure open-file @var{path-or-settings}
@deffnx procedure open-input-file @var{path-or-settings}
@deffnx procedure open-output-file @var{path-or-settings}
@deffnx procedure call-with-input-file @var{path-or-settings} @var{proc}
@deffnx procedure call-with-output-file @var{path-or-settings} @var{proc}
@deffnx procedure with-input-from-file @var{path-or-settings} @var{thunk}
@deffnx procedure with-output-to-file @var{path-or-settings} @var{thunk}

All of these procedures create a port to interface to a byte-stream
device (such as a file, console, serial port, named pipe, etc) whose
name is given by a path of the filesystem.  The @code{direction:}
setting will default to the value @code{input} for the procedures
@code{open-input-file}, @code{call-with-input-file} and
@code{with-input-from-file}, to the value @code{output} for the
procedures @code{open-output-file}, @code{call-with-output-file} and
@code{with-output-to-file}, and to the value @code{input-output} for
the procedure @code{open-file}.

The procedures @code{open-file}, @code{open-input-file} and
@code{open-output-file} return the port that is created.  The
procedures @code{call-with-input-file} and
@code{call-with-output-file} call the procedure @var{proc} with the
port as single argument, and then return the value(s) of this call
after closing the port.  The procedures @code{with-input-from-file}
and @code{with-output-to-file} dynamically bind the current input-port
and current output-port respectively to the port created for the
duration of a call to the procedure @var{thunk} with no argument.  The
value(s) of the call to @var{thunk} are returned after closing the
port.

The first argument of these procedures is either a string denoting a
filesystem path or a list of port settings which must contain a
@code{path:} setting.  Here are the settings allowed in addition to
the generic settings of byte-ports:

@itemize

@item
@code{path:} @var{string}

This setting indicates the location of the file in the filesystem.
There is no default value for this setting.

@item
@code{append:} ( @code{#f} | @code{#t} )

This setting controls whether output will be added to the end of the
file.  This is useful for writing to log files that might be open by
more than one process.  The default value of this setting is
@code{#f}.

@item
@code{create:} ( @code{#f} | @code{#t} | @code{maybe} )

This setting controls whether the file will be created when it is
opened.  A setting of @code{#f} requires that the file exist
(otherwise an exception is raised).  A setting of @code{#t} requires
that the file does not exist (otherwise an exception is raised).  A
setting of @code{maybe} will create the file if it does not exist.
The default value of this setting is @code{maybe} for output-ports and
@code{#f} for input-ports and bidirectional ports.

@item
@code{permissions:} @var{12-bit-exact-integer}

This setting controls the UNIX permissions that will be attached to
the file if it is created.  The default value of this setting is
@code{#o666}.

@item
@code{truncate:} ( @code{#f} | @code{#t} )

This setting controls whether the file will be truncated when it is
opened.  For input-ports, the default value of this setting is
@code{#f}.  For output-ports, the default value of this setting is
@code{#t} when the @code{append:} setting is @code{#f}, and @code{#f}
otherwise.

@end itemize

For example:

@smallexample
> @b{(with-output-to-file
    (list path: "nofile"
          create: #f)
    (lambda ()
      (display "hello world!\n")))}
*** ERROR IN (console)@@1.1 -- No such file or directory
(with-output-to-file '(path: "nofile" create: #f) '#<procedure #2>)
@end smallexample

@end deffn

@deffn procedure input-port-byte-position @var{port} @r{[}@var{position} @r{[}@var{whence}@r{]}@r{]}
@deffnx procedure output-port-byte-position @var{port} @r{[}@var{position} @r{[}@var{whence}@r{]}@r{]}

When called with a single argument these procedures return the byte
position where the next I/O operation would take place in the file
attached to the given @var{port} (relative to the beginning of the
file).  When called with two or three arguments, the byte position for
subsequent I/O operations on the given @var{port} is changed to
@var{position}, which must be an exact integer.  When @var{whence} is
omitted or is 0, the @var{position} is relative to the beginning of
the file.  When @var{whence} is 1, the @var{position} is relative to
the current byte position of the file.  When @var{whence} is 2, the
@var{position} is relative to the end of the file.  The return value
is the new byte position.  On most operating systems the byte position
for reading and writing of a given bidirectional port are the same.

When @code{input-port-byte-position} is called to change the byte
position of an input-port, all input buffers will be flushed so that
the next byte read will be the one at the given position.

When @code{output-port-byte-position} is called to change the byte
position of an output-port, there is an implicit call to
@code{force-output} before the position is changed.

For example:

@smallexample
> @b{(define p  @r{@i{; p is an input-output-port}}
    (open-file '(path: "test" char-encoding: ISO-8859-1 create: maybe)))}
> @b{(list (input-port-byte-position p) (output-port-byte-position p))}
(0 0)
> @b{(display "abcdefghij\n" p)}
> @b{(list (input-port-byte-position p) (output-port-byte-position p))}
(0 0)
> @b{(force-output p)}
> @b{(list (input-port-byte-position p) (output-port-byte-position p))}
(11 11)
> @b{(input-port-byte-position p 2)}
2
> @b{(list (input-port-byte-position p) (output-port-byte-position p))}
(2 2)
> @b{(peek-char p)}
#\c
> @b{(list (input-port-byte-position p) (output-port-byte-position p))}
(11 11)
> @b{(output-port-byte-position p -7 2)}
4
> @b{(list (input-port-byte-position p) (output-port-byte-position p))}
(4 4)
> @b{(write-char #\! p)}
> @b{(list (input-port-byte-position p) (output-port-byte-position p))}
(4 4)
> @b{(force-output p)}
> @b{(list (input-port-byte-position p) (output-port-byte-position p))}
(5 5)
> @b{(input-port-byte-position p 1)}
1
> @b{(read p)}
bcd!fghij
@end smallexample

@end deffn

@node Process devices, Network devices, Filesystem devices, Device-ports
@subsection Process devices

@deffn procedure open-process @var{path-or-settings}
@deffnx procedure open-input-process @var{path-or-settings}
@deffnx procedure open-output-process @var{path-or-settings}
@deffnx procedure call-with-input-process @var{path-or-settings} @var{proc}
@deffnx procedure call-with-output-process @var{path-or-settings} @var{proc}
@deffnx procedure with-input-from-process @var{path-or-settings} @var{thunk}
@deffnx procedure with-output-to-process @var{path-or-settings} @var{thunk}

All of these procedures start a new operating system process and
create a bidirectional port which allows communication with that
process on its standard input and standard output.  The
@code{direction:} setting will default to the value @code{input} for
the procedures @code{open-input-process},
@code{call-with-input-process} and @code{with-input-from-process}, to
the value @code{output} for the procedures @code{open-output-process},
@code{call-with-output-process} and @code{with-output-to-process}, and
to the value @code{input-output} for the procedure
@code{open-process}.  If the @code{direction:} setting is
@code{input}, the output-port side is closed.  If the
@code{direction:} setting is @code{output}, the input-port side is
closed.

The procedures @code{open-process}, @code{open-input-process} and
@code{open-output-process} return the port that is created.  The
procedures @code{call-with-input-process} and
@code{call-with-output-process} call the procedure @var{proc} with the
port as single argument, and then return the value(s) of this call
after closing the port and waiting for the process to terminate.  The
procedures @code{with-input-from-process} and
@code{with-output-to-process} dynamically bind the current input-port
and current output-port respectively to the port created for the
duration of a call to the procedure @var{thunk} with no argument.  The
value(s) of the call to @var{thunk} are returned after closing the
port and waiting for the process to terminate.

The first argument of this procedure is either a string denoting a
filesystem path of an executable program or a list of port settings
which must contain a @code{path:} setting.  Here are the settings
allowed in addition to the generic settings of byte-ports:

@itemize

@item
@code{path:} @var{string}

This setting indicates the location of the executable program in the
filesystem.  There is no default value for this setting.

@item
@code{arguments:} @var{list-of-strings}

This setting indicates the string arguments that are passed to the
program.  The default value of this setting is the empty list (i.e. no
arguments).

@item
@code{environment:} @var{list-of-strings}

This setting indicates the set of environment variable bindings that
the process receives.  Each element of the list is a string of the
form ``@code{@var{VAR}=@var{VALUE}}'', where @code{@var{VAR}} is the
name of the variable and @code{@var{VALUE}} is its binding.  When
@var{list-of-strings} is @code{#f}, the process inherits the
environment variable bindings of the Scheme program.  The default
value of this setting is @code{#f}.

@item
@code{directory:} @var{dir}

This setting indicates the current working directory of the process.
When @var{dir} is @code{#f}, the process uses the value of
@code{(current-directory)}.  The default value of this setting is
@code{#f}.

@item
@code{stdin-redirection:} ( @code{#f} | @code{#t} )

This setting indicates how the standard input of the process is
redirected.  A setting of @code{#t} will redirect the standard input
from the process-port (i.e. what is written to the process-port will
be available on the standard input).  A setting of @code{#f} will
leave the standard input as-is, which typically results in input
coming from the console.  The default value of this setting is
@code{#t}.

@item
@code{stdout-redirection:} ( @code{#f} | @code{#t} )

This setting indicates how the standard output of the process is
redirected.  A setting of @code{#t} will redirect the standard output
to the process-port (i.e. all output to standard output can be read
from the process-port).  A setting of @code{#f} will leave the
standard output as-is, which typically results in the output going to
the console.  The default value of this setting is @code{#t}.

@item
@code{stderr-redirection:} ( @code{#f} | @code{#t} )

This setting indicates how the standard error of the process is
redirected.  A setting of @code{#t} will redirect the standard error
to the process-port (i.e. all output to standard error can be read
from the process-port).  A setting of @code{#f} will leave the
standard error as-is, which typically results in error messages being
output to the console.  The default value of this setting is
@code{#f}.

@item
@code{pseudo-terminal:} ( @code{#f} | @code{#t} )

This setting applies to UNIX.  It indicates what type of device will
be bound to the process' standard input and standard output.  A
setting of @code{#t} will use a pseudo-terminal device (this is a
device that behaves like a tty device even though there is no real
terminal or user directly involved).  A setting of @code{#f} will use
a pair of pipes.  The difference is important for programs which
behave differently when they are used interactively, for example
shells.  The default value of this setting is @code{#f}.

@item
@code{show-console:} ( @code{#f} | @code{#t} )

This setting applies to Microsoft Windows.  It controls whether the
process' console window will be hidden or visible.  The default value
of this setting is @code{#t} (i.e. show the console window).

@end itemize

For example:

@smallexample
> @b{(with-input-from-process "date" read-line)}
"Sun Jun 14 15:06:41 EDT 2009"
> @b{(define p (open-process (list path: "ls"
                                arguments: '("../examples"))))}
> @b{(read-line p)}
"README"
> @b{(read-line p)}
"Xlib-simple"
> @b{(close-port p)}
> @b{(define p (open-process "/usr/bin/dc"))}
> @b{(display "2 100 ^ p\n" p)}
> @b{(force-output p)}
> @b{(read-line p)}
"1267650600228229401496703205376"
@end smallexample

@end deffn

@deffn procedure process-pid @var{process-port}

This procedure returns the PID (Process Identifier) of the process of
@var{process-port}.  The PID is a small exact integer.

For example:

@smallexample
> @b{(let ((p (open-process "sort")))
    (process-pid p))}
318
@end smallexample

@end deffn

@deffn procedure process-status @var{process-port} @r{[}@var{timeout} @r{[}@var{timeout-val}@r{]}@r{]}

This procedure causes the current thread to wait until the process of
@var{process-port} terminates (normally or not) or until the timeout
is reached if @var{timeout} is supplied.  If the timeout is reached,
@var{process-status} returns @var{timeout-val} if it is supplied,
otherwise an unterminated-process-exception object is raised.  The
procedure returns the process exit status as encoded by the operating
system.  Typically, if the process exited normally the return value is
the process exit status multiplied by 256.

For example:

@smallexample
> @b{(let ((p (open-process "sort")))
    (for-each (lambda (x) (pretty-print x p))
              '(22 11 33))
    (close-output-port p)
    (let ((r (read-all p)))
      (close-input-port p)
      (list (process-status p) r)))}
(0 (11 22 33))
@end smallexample

@end deffn

@deffn procedure unterminated-process-exception? @var{obj}
@deffnx procedure unterminated-process-exception-procedure @var{exc}
@deffnx procedure unterminated-process-exception-arguments @var{exc}

Unterminated-process-exception objects are raised when a call to the
@code{process-status} procedure reaches its timeout before the target
process terminates and a timeout-value parameter is not specified.
The parameter @var{exc} must be an unterminated-process-exception
object.

The procedure @code{unterminated-process-exception?} returns
@code{#t} when @var{obj} is an unterminated-process-exception
object and @code{#f} otherwise.

The procedure @code{unterminated-process-exception-procedure}
returns the procedure that raised @var{exc}.

The procedure @code{unterminated-process-exception-arguments}
returns the list of arguments of the procedure that raised @var{exc}.

For example:

@smallexample
> @b{(define (handler exc)
    (if (unterminated-process-exception? exc)
        (list (unterminated-process-exception-procedure exc)
              (unterminated-process-exception-arguments exc))
        'not-unterminated-process-exception))}
> @b{(with-exception-catcher
    handler
    (lambda ()
      (let ((p (open-process "sort")))
        (process-status p 1))))}
(#<procedure #2 process-status> (#<input-output-port #3 (process "sort")>))
@end smallexample

@end deffn

@node Network devices, , Process devices, Device-ports
@subsection Network devices

@deffn procedure open-tcp-client @var{port-number-or-address-or-settings}

This procedure opens a network connection to a socket server and
returns a tcp-client-port (a subtype of device-port) that represents
this connection and allows communication with that server.  The
default value of the @code{direction:} setting is @code{input-output},
i.e. the Scheme program can send information to the server and receive
information from the server.  The sending direction can be
``shutdown'' using the @code{close-output-port} procedure and the
receiving direction can be ``shutdown'' using the
@code{close-input-port} procedure.  The @code{close-port} procedure
closes both directions of the connection.

The parameter of this procedure is an IP port number (16-bit nonnegative
exact integer), a string of the form @code{"@var{HOST}:@var{PORT}"} or
a list of port settings.  When the parameter is the number @var{PORT}
it is handled as if it was the setting @code{port-number:} @var{PORT}.
When the parameter is the string @code{"@var{HOST}:@var{PORT}"} it is
handled as if it was the setting @code{server-address:}
@code{"@var{HOST}:@var{PORT}"}.

Here are the settings allowed in addition to the generic settings of
byte-ports:

@itemize

@item
@code{server-address:} @var{string-or-ip-address}

This setting indicates the internet address of the server, and
possibly the IP port number.  When this parameter is not specified or
is @code{""}, the connection requests are sent to the loopback
interface (with IP address 127.0.0.1).  The parameter can be a string
denoting a host name, which will be translated to an IP address by the
@code{host-info} procedure, or a 4 element u8vector which contains the
32-bit IPv4 address or an 8 element u16vector which contains the
128-bit IPv6 address.  A string of the form
@code{"@var{HOST}:@var{PORT}"} is handled as if it was the combination
of settings @code{server-address:} @code{"@var{HOST}"}
@code{port-number:} @var{PORT}.

@item
@code{port-number:} @var{16-bit-exact-integer}

This setting indicates the IP port number of the server to connect
to (e.g. 80 for the standard HTTP server, 23 for the standard telnet
server).  There is no default value for this setting.

@item
@code{keep-alive:} ( @code{#f} | @code{#t} )

This setting controls the use of the ``keep alive'' option on the
connection.  The ``keep alive'' option will periodically send control
packets on otherwise idle network connections to ensure that the
server host is active and reachable.  The default value of this
setting is @code{#f}.

@item
@code{coalesce:} ( @code{#f} | @code{#t} )

This setting controls the use of TCP's ``Nagle algorithm'' which
reduces the number of small packets by delaying their transmission and
coalescing them into larger packets.  A setting of @code{#t} will
coalesce small packets into larger ones.  A setting of @code{#f} will
transmit packets as soon as possible.  The default value of this
setting is @code{#t}.  Note that this setting does not affect the
buffering of the port.

@item
@code{tls-context:} ( @code{#f} | @var{tls-context} )

This setting controls the use of TLS encryption.  If provided, the client
will use this configuration for setting up a TCP connection with TLS
encryption, otherwise it will use a plain TCP connection as usual.  Please
note that Gambit must be compiled with TLS support for this option to be
implemented.  See @code{make-tls-context} for futher information.  The
default value of this setting is @code{#f}.

@end itemize

Below is an example of the client-side code that opens a connection to
an HTTP server on port 8080 of the loopback interface (with IP address
127.0.0.1).  For the server-side code see the example for the
procedure @code{open-tcp-server}.

@smallexample
> @b{(define p (open-tcp-client (list port-number: 8080
                                   eol-encoding: 'cr-lf)))}
> @b{p}
#<input-output-port #2 (tcp-client #u8(127 0 0 1) 8080)>
> @b{(display "GET /\n" p)}
> @b{(force-output p)}
> @b{(read-line p)}
"<HTML>"
@end smallexample

@end deffn

@deffn procedure open-tcp-server @var{port-number-or-address-or-settings}

This procedure sets up a socket to accept network connection requests
from clients and returns a tcp-server-port from which network
connections to clients are obtained.  Tcp-server-ports are a direct
subtype of object-ports (i.e. they are not character-ports) and are
input-ports.  Reading from a tcp-server-port with the @code{read}
procedure will block until a network connection request is received
from a client.  The @code{read} procedure will then return a
tcp-client-port (a subtype of device-port) that represents this
connection and allows communication with that client.  Closing a
tcp-server-port with either the @code{close-input-port} or
@code{close-port} procedures will cause the network subsystem to stop
accepting connections on that socket.

The parameter of this procedure is an IP port number (16-bit nonnegative
exact integer), a string of the form @code{"@var{INTF}:@var{PORT}"} or
a list of port settings which must contain a @code{port-number:}
setting.  When the parameter is the number @var{PORT} it is handled as
if it was the setting @code{port-number:} @var{PORT}.  When the
parameter is the string @code{"@var{INTF}:@var{PORT}"} it is handled
as if it was the setting @code{server-address:}
@code{"@var{INTF}:@var{PORT}"}.

Below is a list of the settings allowed in addition to the settings
@code{keep-alive:} and @code{coalesce:} allowed by the
@code{open-tcp-client} procedure and the generic settings of
byte-ports.  The settings which are not listed below apply to the
tcp-client-port that is returned by @code{read} when a connection is
accepted and have the same meaning as if they were used in a call to
the @code{open-tcp-client} procedure.

@itemize

@item
@code{server-address:} @var{string-or-ip-address}

This setting indicates the internet address of the network interface
on which connections requests are accepted, and possibly the IP port
number.  When this parameter is not specified or is @code{""}, the
connection requests are accepted only on the loopback interface (with
IP address 127.0.0.1).  When this parameter is @code{"*"}, the
connection requests are accepted on all network interfaces
(i.e. address INADDR_ANY).  The parameter can be a string denoting a
host name, which will be translated to an IP address by the
@code{host-info} procedure, or a 4 element u8vector which contains the
32-bit IPv4 address or an 8 element u16vector which contains the
128-bit IPv6 address.  A string of the form
@code{"@var{INTF}:@var{PORT}"} is handled as if it was the combination
of settings @code{server-address:} @code{"@var{INTF}"}
@code{port-number:} @var{PORT}.

@item
@code{port-number:} @var{16-bit-exact-integer}

This setting indicates the IP port number assigned to the socket which
accepts connection requests from clients.  So called ``well-known
ports'', which are reserved for standard services, have a port number
below 1024 and can only be assigned to a socket by a process with
superuser priviledges (e.g. 80 for the HTTP service, 23 for the telnet
service).  No special priviledges are needed to assign higher
port numbers to a socket.  The special value 0 requests that a
currently unused port number be assigned to the socket (the port
number assigned can be retrieved using the procedure
@code{tcp-server-socket-info}).  There is no default value for this
setting.

@item
@code{backlog:} @var{positive-exact-integer}

This setting indicates the maximum number of connection requests that
can be waiting to be accepted by a call to @code{read} (technically it
is the value passed as the second argument of the UNIX @code{listen()}
function).  The default value of this setting is 128.

@item
@code{reuse-address:} ( @code{#f} | @code{#t} )

This setting controls whether it is possible to assign a port number
that is currently active.  Note that when a server process terminates,
the socket it was using to accept connection requests does not become
inactive immediately.  Instead it remains active for a few minutes to
ensure clean termination of the connections.  A setting of @code{#f}
will cause an exception to be raised in that case.  A setting of
@code{#t} will allow a port number to be used even if it is active.
The default value of this setting is @code{#t}.

@item
@code{tls-context:} ( @code{#f} | @var{tls-context} )

This setting controls the use of TLS encryption.  If provided, the server
will use this configuration for accepting TCP connections with TLS
encryption, otherwise it will accept plain TCP connections as usual.  Please
note that Gambit must be compiled with TLS support for this option to be
implemented.  See @code{make-tls-context} for futher information.  The
default value of this setting is @code{#f}.

@end itemize

Below is an example of the server-side code that accepts connections
on port 8080 of any network interface.  For the client-side code see
the example for the procedure @code{open-tcp-client}.

@smallexample
> @b{(define s (open-tcp-server (list server-address: "*"
                                   port-number: 8080
                                   eol-encoding: 'cr-lf)))}
> @b{(define p (read s))  @r{@i{; blocks until client connects}}}
> @b{p}
#<input-output-port #2 (tcp-client 8080)>
> @b{(read-line p)}
"GET /"
> @b{(display "<HTML>\n" p)}
> @b{(force-output p)}
@end smallexample

@end deffn

@deffn procedure tcp-service-register! @var{port-number-or-address-or-settings} @var{thunk} @r{[}@var{thread-group}@r{]}
@deffnx procedure tcp-service-unregister! @var{port-number-or-address-or-settings}

The procedure @code{tcp-service-register!} sets up a socket to accept
network connection requests from clients and creates a ``service''
thread which processes the incoming connections.  The parameter
@var{port-number-or-address-or-settings} has the same meaning as for
the procedure @code{open-tcp-server}.

For each connection established the service thread creates a
``handler'' thread which executes a call to the procedure @var{thunk}
with no argument.  The handler thread's current input-port and current
output-port are both set to the tcp-client-port created for the
connection.  There is no need for the @var{thunk} to close the
tcp-client-port, as this is done by the handler thread when the
@var{thunk} returns normally.

The procedure @code{tcp-service-unregister!} terminates the service
thread which was registered by @code{tcp-service-register!} with the
same network interface and port number (if a service thread is still
registered).  The procedure @code{tcp-service-register!} implicitly
calls @code{tcp-service-unregister!} before registering the new
service thread.

@smallexample
> @b{(tcp-service-register!
   8000
   (lambda () (display "hello\n")))}
> @b{(define p (open-tcp-client 8000))}
> @b{(read-line p)}
"hello"
> @b{(tcp-service-unregister! 8000)}
@end smallexample

@end deffn

@deffn procedure make-tls-context @r{[}@var{options}@r{]}

This procedure requires Gambit to be compiled with TLS support, which is
currently provided by OpenSSL. The @code{--enable-openssl} flag of the configure
script will activate it, provided that you have the OpenSSL library and headers
installed. It is strongly recommended that versions above 1.x are used.
On OSX, this means updating the OpenSSL bundled by default. This can be achieved
using Homebrew, but manual installation or any other package manager will do.
Some notes on Windows with MinGW are also relevant here. Once you have a sane
MinGW environment, remember to decompress the OpenSSL tarball with the tar
utility, otherwise links to files won't work during the compilation process. The
recommended build procedure for MinGW is as follows.

Configure OpenSSL on MinGW 32 bits:

@smallexample
perl Configure mingw no-asm --prefix=/usr/local --openssldir=/usr/local/openssl
@end smallexample

Configure OpenSSL on MinGW 64 bits:

@smallexample
perl Configure mingw64 no-asm --prefix=/usr/local --openssldir=/usr/local/openssl
@end smallexample

Build and install with the following commands:

@smallexample
make depend
make
make install
@end smallexample

A TLS context describes the options that will be used for setting up a TLS
connection. If no TLS context is provided to @code{open-tcp-client} or
@code{open-tcp-server}, regular TCP connections without encryption will be used
instead. The result of this procedure is a @code{SSL_CTX} pointer, which can be
further manipulated with custom OpenSSL bindings. The configuration options are:

@itemize

@item
@code{min-version:} @var{symbol}

Establish a minimum TLS version for the connection. If the other peer doesn't
support or agree with it, the connection will fail. Possible options (support
depends on linked OpenSSL version): @code{ssl-v2}, @code{ssl-v3}, @code{tls-v1},
@code{tls-v1.1}, @code{tls-v1.2}.

@item
@code{options:} @var{list-of-symbols}

A list of flags enabling/disabling TLS options. @code{server-mode} is required
for using the TLS context with @code{open-tcp-server}. @code{use-diffie-hellman}
enables the Diffie-Hellman key exchange. @code{use-elliptic-curves} enables
Elliptic Curves. If no curve name is provided (with @code{elliptic-curve:}),
@code{prime256v1} will be used. @code{request-client-authentication} is used by
a server to enable request of authentication to clients.
@code{insert-empty-fragments} enables a countermeasure against a SSL 3.0/TLS 1.0
protocol vulnerability affecting CBC ciphers. If used, the resulting connection
may not be handled by some broken SSL implementations. This option has no effect
for connections using other ciphers.

@item
@code{certificate:} @var{path}

Path to PEM Certificate file. This is a recommended option. If not provided
OpenSSL will try to use anonymous cipher suites.

@item
@code{private-key:} @var{path}

Path to PEM Private Key file. If not provided, the Certificate path will be used
instead.

@item
@code{client-ca:} @var{path}

Path to PEM file containing Certificate Authorities allowed for client
authentication. Used only if @code{request-client-authentication} option is
enabled.

@item
@code{elliptic-curve:} @var{string}

Name of the Elliptic Curve to use, according to RFC 4492. Used only if
@code{use-elliptic-curves} option is enabled.

@end itemize

TCP Client example with TLS encryption.

@smallexample
(define ctx (make-tls-context))
(define c (open-tcp-client (list server-address: "twitter.com"
                                 port-number: 443 tls-context: ctx)))
(display "GET / HTTP/1.1\nHost: twitter.com\n\n" c)
(force-output c)
(read-line c)
@end smallexample

TCP Server example with several options. These are not mandatory, except
for @code{server-mode}.

@smallexample
(define ctx (make-tls-context options: '(server-mode
                                         use-diffie-hellman
                                         use-elliptic-curves)
                              certificate: "server.pem"
                              diffie-hellman-parameters: "dh_param_1024.pem"
                              elliptic-curve: "prime256v1"))

(define s (open-tcp-server (list server-address: "localhost"
                                 port-number: 1443 tls-context: ctx)))
(define p (read s))
(display "<HTML></HTML>\n" p)
(force-output p)
@end smallexample

A practical way of testing TLS options are the @code{s_server} and
@code{s_client} commands of the @code{openssl} tool.

@end deffn

@node Directory-ports, Vector-ports, Device-ports, I/O and ports
@section Directory-ports

@deffn procedure open-directory @var{path-or-settings}

This procedure opens a directory of the filesystem for reading its
entries and returns a directory-port from which the entries can be
enumerated.  Directory-ports are a direct subtype of object-ports
(i.e. they are not character-ports) and are input-ports.  Reading from
a directory-port with the @code{read} procedure returns the next file
name in the directory as a string.  The end-of-file object is returned
when all the file names have been enumerated.  Another way to get the
list of all files in a directory is the @code{directory-files}
procedure which returns a list of the files in the directory.  The
advantage of using directory-ports is that it allows iterating over
the files in a directory in constant space, which is interesting when
the number of files in the directory is not known in advance and may
be large.  Note that the order in which the names are returned is
operating-system dependent.

The parameter of this procedure is either a string denoting a
filesystem path to a directory or a list of port settings which must
contain a @code{path:} setting.  Here are the settings allowed in
addition to the generic settings of object-ports:

@itemize

@item
@code{path:} @var{string}

This setting indicates the location of the directory in the filesystem.
There is no default value for this setting.

@item
@code{ignore-hidden:} ( @code{#f} | @code{#t} | @code{dot-and-dot-dot} )

This setting controls whether hidden-files will be returned.  Under
UNIX and Mac OS X hidden-files are those that start with a period
(such as @samp{.}, @samp{..}, and @samp{.profile}).  Under Microsoft
Windows hidden files are the @samp{.} and @samp{..} entries and the
files whose ``hidden file'' attribute is set.  A setting of @code{#f}
will enumerate all the files.  A setting of @code{#t} will only
enumerate the files that are not hidden.  A setting of
@code{dot-and-dot-dot} will enumerate all the files except for the
@samp{.} and @samp{..} hidden files.  The default value of this
setting is @code{#t}.

@end itemize

For example:

@smallexample
> @b{(let ((p (open-directory (list path: "../examples"
                                 ignore-hidden: #f))))
    (let loop ()
      (let ((fn (read p)))
        (if (string? fn)
            (begin
              (pp (path-expand fn))
              (loop)))))
    (close-input-port p))}
"/u/feeley/examples/."
"/u/feeley/examples/.."
"/u/feeley/examples/complex"
"/u/feeley/examples/README"
"/u/feeley/examples/simple"
> @b{(define x (open-directory "../examples"))}
> @b{(read-all x)}
("complex" "README" "simple")
@end smallexample

@end deffn

@node Vector-ports, String-ports, Directory-ports, I/O and ports
@section Vector-ports

@deffn procedure open-vector @r{[}@var{vector-or-settings}@r{]}
@deffnx procedure open-input-vector @r{[}@var{vector-or-settings}@r{]}
@deffnx procedure open-output-vector @r{[}@var{vector-or-settings}@r{]}
@deffnx procedure call-with-input-vector @var{vector-or-settings} @var{proc}
@deffnx procedure call-with-output-vector @var{vector-or-settings} @var{proc}
@deffnx procedure with-input-from-vector @var{vector-or-settings} @var{thunk}
@deffnx procedure with-output-to-vector @var{vector-or-settings} @var{thunk}

Vector-ports represent streams of Scheme objects.  They are a direct
subtype of object-ports (i.e. they are not character-ports).  All of
these procedures create vector-ports that are either unidirectional or
bidirectional.  The @code{direction:} setting will default to the
value @code{input} for the procedures @code{open-input-vector},
@code{call-with-input-vector} and @code{with-input-from-vector}, to
the value @code{output} for the procedures @code{open-output-vector},
@code{call-with-output-vector} and @code{with-output-to-vector}, and
to the value @code{input-output} for the procedure @code{open-vector}.
Bidirectional vector-ports behave like FIFOs: data written to the port
is added to the end of the stream that is read.  It is only when a
bidirectional vector-port's output-side is closed with a call to the
@code{close-output-port} procedure that the stream's end is known
(when the stream's end is reached, reading the port returns the
end-of-file object).

The procedures @code{open-vector}, @code{open-input-vector} and
@code{open-output-vector} return the port that is created.  The
procedures @code{call-with-input-vector} and
@code{call-with-output-vector} create a vector port, call the
procedure @var{proc} with the port as single argument and then close
the port.  The procedures @code{with-input-from-vector} and
@code{with-output-to-vector} create a vector port, dynamically bind
the current input-port and current output-port respectively to the
port created for the duration of a call to the procedure @var{thunk}
with no argument, and then close the port.  The procedures
@code{call-with-input-vector} and @code{with-input-from-vector} return
the value returned by the procedures @var{proc} and @var{thunk}
respectively.  The procedures @code{call-with-output-vector} and
@code{with-output-to-vector} return the vector accumulated in the port
(see @code{get-output-vector}).

The first parameter of these procedures is either a vector of the
elements used to initialize the stream or a list of port settings.  If
it is not specified, the parameter of the @code{open-vector},
@code{open-input-vector}, and @code{open-output-vector} procedures
defaults to an empty list of port settings.  Here are the settings
allowed in addition to the generic settings of object-ports:

@itemize

@item
@code{init:} @var{vector}

This setting indicates the initial content of the stream.  The default
value of this setting is an empty vector.

@item
@code{permanent-close:} ( @code{#f} | @code{#t} )

This setting controls whether a call to the procedures
@code{close-output-port} will close the output-side of a bidirectional
vector-port permanently or not.  A permanently closed bidirectional
vector-port whose end-of-file has been reached on the input-side will
return the end-of-file object for all subsequent calls to the
@code{read} procedure.  A non-permanently closed bidirectional
vector-port will return to its opened state when its end-of-file is
read.  The default value of this setting is @code{#t}.

@end itemize

For example:

@smallexample
> @b{(define p (open-vector))}
> @b{(write 1 p)}
> @b{(write 2 p)}
> @b{(write 3 p)}
> @b{(force-output p)}
> @b{(read p)}
1
> @b{(read p)}
2
> @b{(close-output-port p)}
> @b{(read p)}
3
> @b{(read p)}
#!eof
> @b{(with-output-to-vector '() (lambda () (write 1) (write 2)))}
#(1 2)
@end smallexample

@end deffn

@deffn procedure open-vector-pipe @r{[}@var{vector-or-settings1} @r{[}@var{vector-or-settings2}@r{]}@r{]}

The procedure @code{open-vector-pipe} creates two vector-ports and
returns these two ports.  The two ports are interrelated as follows:
the first port's output-side is connected to the second port's
input-side and the first port's input-side is connected to the second
port's output-side.  The value @var{vector-or-settings1} is used to
setup the first vector-port and @var{vector-or-settings2} is used to
setup the second vector-port.  The same settings as for
@code{open-vector} are allowed.  The default @code{direction:} setting
is @code{input-output} (i.e. a bidirectional port is created).  If it
is not specified @var{vector-or-settings1} defaults to the empty list.
If it is not specified @var{vector-or-settings2} defaults to
@var{vector-or-settings1} but with the @code{init:} setting set to the
empty vector and with the input and output settings exchanged (e.g. if
the first port is an input-port then the second port is an
output-port, if the first port's input-side is non-buffered then the
second port's output-side is non-buffered).

For example:

@smallexample
> @b{(define (server op)
    (receive (c s) (open-vector-pipe)  @r{@i{; client-side and server-side ports}}
      (thread-start!
        (make-thread
          (lambda ()
            (let loop ()
              (let ((request (read s)))
                (if (not (eof-object? request))
                    (begin
                      (write (op request) s)
                      (newline s)
                      (force-output s)
                      (loop))))))))
      c))}
> @b{(define a (server (lambda (x) (expt 2 x))))}
> @b{(define b (server (lambda (x) (expt 10 x))))}
> @b{(write 100 a)}
> @b{(write 30 b)}
> @b{(read a)}
1267650600228229401496703205376
> @b{(read b)}
1000000000000000000000000000000
@end smallexample

@end deffn

@deffn procedure get-output-vector @var{vector-port}

The procedure @code{get-output-vector} takes an output vector-port or
a bidirectional vector-port as parameter and removes all the objects
currently on the output-side, returning them in a vector.  The port
remains open and subsequent output to the port and calls to the
procedure @code{get-output-vector} are possible.

For example:

@smallexample
> @b{(define p (open-vector '#(1 2 3)))}
> @b{(write 4 p)}
> @b{(get-output-vector p)}
#(1 2 3 4)
> @b{(write 5 p)}
> @b{(write 6 p)}
> @b{(get-output-vector p)}
#(5 6)
@end smallexample

@end deffn

@node String-ports, U8vector-ports, Vector-ports, I/O and ports
@section String-ports

@deffn procedure open-string @r{[}@var{string-or-settings}@r{]}
@deffnx procedure open-input-string @r{[}@var{string-or-settings}@r{]}
@deffnx procedure open-output-string @r{[}@var{string-or-settings}@r{]}
@deffnx procedure call-with-input-string @var{string-or-settings} @var{proc}
@deffnx procedure call-with-output-string @var{string-or-settings} @var{proc}
@deffnx procedure with-input-from-string @var{string-or-settings} @var{thunk}
@deffnx procedure with-output-to-string @var{string-or-settings} @var{thunk}
@deffnx procedure open-string-pipe @r{[}@var{string-or-settings1} @r{[}@var{string-or-settings2}@r{]}@r{]}
@deffnx procedure get-output-string @var{string-port}

String-ports represent streams of characters.  They are a direct
subtype of character-ports.  These procedures are the string-port
analog of the procedures specified in the vector-ports section.  Note
that these procedures are a superset of the procedures specified in
the ``Basic String Ports SRFI'' (SRFI 6).

For example:

@smallexample
> @b{(define p (open-string))}
> @b{(write 1 p)}
> @b{(write 2 p)}
> @b{(write 3 p)}
> @b{(force-output p)}
> @b{(read-char p)}
#\1
> @b{(read-char p)}
#\2
> @b{(close-output-port p)}
> @b{(read-char p)}
#\3
> @b{(read-char p)}
#!eof
> @b{(with-output-to-string '() (lambda () (write 1) (write 2)))}
"12"
@end smallexample

@end deffn

@deffn procedure object->string @var{obj} @r{[}@var{n}@r{]}

This procedure converts the object @var{obj} to its external
representation and returns it in a string.  The parameter @var{n}
specifies the maximal width of the resulting string.  If the external
representation is wider than @var{n}, the resulting string will be
truncated to @var{n} characters and the last 3 characters will be set
to periods.  Note that the current readtable is used.

For example:

@smallexample
> @b{(object->string (expt 2 100))}
"1267650600228229401496703205376"
> @b{(object->string (expt 2 100) 30)}
"126765060022822940149670320..."
> @b{(object->string (cons car cdr))}
"(#<procedure #2 car> . #<procedure #3 cdr>)"
@end smallexample

@end deffn

@node U8vector-ports, Other procedures related to I/O, String-ports, I/O and ports
@section U8vector-ports

@deffn procedure open-u8vector @r{[}@var{u8vector-or-settings}@r{]}
@deffnx procedure open-input-u8vector @r{[}@var{u8vector-or-settings}@r{]}
@deffnx procedure open-output-u8vector @r{[}@var{u8vector-or-settings}@r{]}
@deffnx procedure call-with-input-u8vector @var{u8vector-or-settings} @var{proc}
@deffnx procedure call-with-output-u8vector @var{u8vector-or-settings} @var{proc}
@deffnx procedure with-input-from-u8vector @var{u8vector-or-settings} @var{thunk}
@deffnx procedure with-output-to-u8vector @var{u8vector-or-settings} @var{thunk}
@deffnx procedure open-u8vector-pipe @r{[}@var{u8vector-or-settings1} @r{[}@var{u8vector-or-settings2}@r{]}@r{]}
@deffnx procedure get-output-u8vector @var{u8vector-port}

U8vector-ports represent streams of bytes.  They are a direct subtype
of byte-ports.  These procedures are the u8vector-port analog of the
procedures specified in the vector-ports section.

For example:

@smallexample
> @b{(define p (open-u8vector))}
> @b{(write 1 p)}
> @b{(write 2 p)}
> @b{(write 3 p)}
> @b{(force-output p)}
> @b{(read-u8 p)}
49
> @b{(read-u8 p)}
50
> @b{(close-output-port p)}
> @b{(read-u8 p)}
51
> @b{(read-u8 p)}
#!eof
> @b{(with-output-to-u8vector '() (lambda () (write 1) (write 2)))}
#u8(49 50)
@end smallexample

@end deffn

@node Other procedures related to I/O, , U8vector-ports, I/O and ports
@section Other procedures related to I/O

@deffn procedure current-input-port @r{[}@var{new-value}@r{]}
@deffnx procedure current-output-port @r{[}@var{new-value}@r{]}
@deffnx procedure current-error-port @r{[}@var{new-value}@r{]}
@deffnx procedure current-readtable @r{[}@var{new-value}@r{]}

These procedures are parameter objects which represent respectively:
the current input-port, the current output-port, the current
error-port, and the current readtable.

@end deffn

@deffn procedure print @r{[}@code{port:} @var{port}@r{]} @var{obj}@dots{}
@deffnx procedure println @r{[}@code{port:} @var{port}@r{]} @var{obj}@dots{}

The @code{print} procedure writes a representation of each @var{obj},
from left to right, to @var{port}.  When a compound object is
encountered (pair, list, vector, box) the elements of that object are
recursively written without the surrounding tokens (parentheses,
spaces, dots, etc).  Strings, symbols, keywords and characters are
written like the @code{display} procedure.  If there are more than one
@var{obj}, the first @var{obj} must not be a keyword object.  If it is
not specified, @var{port} defaults to the current output-port.  The
procedure @code{print} returns an unspecified value.

The @code{println} procedure does the same thing as the @code{print}
procedure and then writes an end of line to @var{port}.

For example:

@smallexample
> @b{(println "2*2 is " (* 2 2) " and 2+2 is " (+ 2 2))}
2*2 is 4 and 2+2 is 4
> @b{(define x (list "<i>" (list "<tt>" 123 "</tt>") "</i>"))}
> @b{(println x)}
<i><tt>123</tt></i>
> @b{(define p (open-output-string))}
> @b{(print port: p 1 #\2 "345")}
> @b{(get-output-string p)}
"12345"
@end smallexample

@end deffn

@node Lexical syntax and readtables, C-interface, I/O and ports, Top
@chapter Lexical syntax and readtables

@menu
* Readtables::                        Readtables
* Boolean syntax::                    Boolean syntax
* Character syntax::                  Character syntax
* String syntax::                     String syntax
* Symbol syntax::                     Symbol syntax
* Keyword syntax::                    Keyword syntax
* Box syntax::                        Box syntax
* Number syntax::                     Number syntax
* Homogeneous vector syntax::         Homogeneous vector syntax
* Special #! syntax::                 Special #! syntax
* Multiline comment syntax::          Multiline comment syntax
* Scheme infix syntax extension::     Scheme infix syntax extension
@end menu

@node Readtables, Boolean syntax, Lexical syntax and readtables, Lexical syntax and readtables
@section Readtables

Readtables control the external textual representation of Scheme
objects, that is the encoding of Scheme objects using characters.
Readtables affect the behavior of the reader (i.e. the @code{read}
procedure and the parser used by the @code{load} procedure and the
interpreter and compiler) and the printer (i.e. the procedures
@code{write}, @code{display}, @code{print}, @code{println},
@code{pretty-print}, and @code{pp}, and the procedure used by the REPL
to print results).  To preserve write/read invariance the printer and
reader must be using compatible readtables.  For example a symbol
which contains upper case letters will be printed with special escapes
if the readtable indicates that the reader is case-insensitive.

Readtables are immutable records whose fields specify various textual
representation aspects.  There are accessor procedures to retrieve the
content of specific fields.  There are also functional update
procedures that create a copy of a readtable, with a specific field
set to a new value.

@deffn procedure readtable? @var{obj}

This procedure returns @code{#t} when @var{obj} is a readtable and
@code{#f} otherwise.

For example:

@smallexample
> @b{(readtable? (current-readtable))}
#t
> @b{(readtable? 123)}
#f
@end smallexample

@end deffn

@deffn procedure readtable-case-conversion? @var{readtable}
@deffnx procedure readtable-case-conversion?-set @var{readtable} @var{new-value}

The procedure @code{readtable-case-conversion?} returns the content of
the @samp{case-conversion?} field of @var{readtable}.  When the
content of this field is @code{#f}, the reader preserves the case of
symbols and keyword objects that are read (i.e. @code{Ice} and
@code{ice} are distinct symbols).  When the content of this field is
the symbol @code{upcase}, the reader converts lowercase letters to
uppercase when reading symbols and keywords (i.e. @code{Ice} is read
as the symbol @code{(string->symbol "ICE")}).  Otherwise the reader
converts uppercase letters to lowercase when reading symbols and
keywords (i.e. @code{Ice} is read as the symbol @code{(string->symbol
"ice")}).

The procedure @code{readtable-case-conversion?-set} returns a copy
of @var{readtable} where only the @samp{case-conversion?} field
has been changed to @var{new-value}.

For example:

@smallexample
> @b{(output-port-readtable-set!
    (repl-output-port)
    (readtable-case-conversion?-set
      (output-port-readtable (repl-output-port))
      #f))}
> @b{(input-port-readtable-set!
    (repl-input-port)
    (readtable-case-conversion?-set
      (input-port-readtable (repl-input-port))
      #f))}
> @b{'Ice}
Ice
> @b{(input-port-readtable-set!
    (repl-input-port)
    (readtable-case-conversion?-set
      (input-port-readtable (repl-input-port))
      #t))}
> @b{'Ice}
ice
> @b{(input-port-readtable-set!
    (repl-input-port)
    (readtable-case-conversion?-set
      (input-port-readtable (repl-input-port))
      'upcase))}
> @b{'Ice}
ICE
@end smallexample

@end deffn

@deffn procedure readtable-keywords-allowed? @var{readtable}
@deffnx procedure readtable-keywords-allowed?-set @var{readtable} @var{new-value}

The procedure @code{readtable-keywords-allowed?} returns the content
of the @samp{keywords-allowed?} field of @var{readtable}.  When the
content of this field is @code{#f}, the reader does not recognize
keyword objects (i.e. @code{:foo} and @code{foo:} are read as the
symbols @code{(string->symbol ":foo")} and @code{(string->symbol
"foo:")} respectively).  When the content of this field is the symbol
@code{prefix}, the reader recognizes keyword objects that start with a
colon, as in Common Lisp (i.e. @code{:foo} is read as the keyword
@code{(string->keyword "foo")}).  Otherwise the reader recognizes
keyword objects that end with a colon, as in DSSSL (i.e. @code{foo:}
is read as the symbol @code{(string->symbol "foo")}).

The procedure @code{readtable-keywords-allowed?-set} returns a copy
of @var{readtable} where only the @samp{keywords-allowed?} field
has been changed to @var{new-value}.

For example:

@smallexample
> @b{(input-port-readtable-set!
    (repl-input-port)
    (readtable-keywords-allowed?-set
      (input-port-readtable (repl-input-port))
      #f))}
> @b{(map keyword? '(foo :foo foo:))}
(#f #f #f)
> @b{(input-port-readtable-set!
    (repl-input-port)
    (readtable-keywords-allowed?-set
      (input-port-readtable (repl-input-port))
      #t))}
> @b{(map keyword? '(foo :foo foo:))}
(#f #f #t)
> @b{(input-port-readtable-set!
    (repl-input-port)
    (readtable-keywords-allowed?-set
      (input-port-readtable (repl-input-port))
      'prefix))}
> @b{(map keyword? '(foo :foo foo:))}
(#f #t #f)
@end smallexample

@end deffn

@deffn procedure readtable-sharing-allowed? @var{readtable}
@deffnx procedure readtable-sharing-allowed?-set @var{readtable} @var{new-value}
@cindex serialization
@cindex deserialization

The procedure @code{readtable-sharing-allowed?} returns the content of
the @samp{sharing-allowed?} field of @var{readtable}.  The reader
recognizes the @code{#@var{n}#} and @code{#@var{n}=@var{datum}}
notation for circular structures and the printer uses this notation if
and only if the content of the @samp{sharing-allowed?} field is not
@code{#f}.  Moreover when the content of the @samp{sharing-allowed?}
field is the symbol @code{serialize}, the printer uses a special
external representation that the reader understands and that extends
write/read invariance to the following types: records, procedures and
continuations.  Note that an object can be serialized and deserialized
if and only if all of its components are serializable.

The procedure @code{readtable-sharing-allowed?-set} returns a copy
of @var{readtable} where only the @samp{sharing-allowed?} field
has been changed to @var{new-value}.

Here is a simple example:

@smallexample
> @b{(define (wr obj allow?)
    (call-with-output-string
      '()
      (lambda (p)
        (output-port-readtable-set!
          p
          (readtable-sharing-allowed?-set
            (output-port-readtable p)
            allow?))
        (write obj p))))}
> @b{(define (rd str allow?)
    (call-with-input-string
      str
      (lambda (p)
        (input-port-readtable-set!
          p
          (readtable-sharing-allowed?-set
            (input-port-readtable p)
            allow?))
        (read p))))}
> @b{(define x (list 1 2 3))}
> @b{(set-car! (cdr x) (cddr x))}
> @b{(wr x #f)}
"(1 (3) 3)"
> @b{(wr x #t)}
"(1 #0=(3) . #0#)"
> @b{(define y (rd (wr x #t) #t))}
> @b{y}
(1 (3) 3)
> @b{(eq? (cadr y) (cddr y))}
#t
> @b{(define f #f)}
> @b{(let ((free (expt 2 10)))
  (set! f (lambda (x) (+ x free))))}
> @b{(define s (wr f 'serialize))}
> @b{(string-length s)}
4196
> @b{(define g (rd s 'serialize))}
> @b{(eq? f g)}
#f
> @b{(g 4)}
1028
@end smallexample

Continuations are tricky to serialize because they contain a dynamic
environment and this dynamic environment may contain non-serializable
objects, in particular ports attached to operating-system streams such
as files, the console or standard input/output.  Indeed, all dynamic
environments contain a binding for the @code{current-input-port} and
@code{current-output-port}.  Moreover, any thread that has started a
REPL has a continuation which refers to the @dfn{repl-context} object
in its dynamic environment.  A repl-context object contains the
interaction channel, which is typically connected to a
non-serializable port, such as the console.  Another problem is that
the @code{parameterize} form saves the old binding of the parameter in
the continuation, so it is not possible to eliminate the references to
these ports in the continuation by using the @code{parameterize} form
alone.

Serialization of continuations can be achieved dependably by taking
advantage of string-ports, which are serializable objects (unless
there is a blocked thread), and the following features of threads:
they inherit the dynamic environment of the parent thread and they
start with an initial continuation that contains only serializable
objects.  So a thread created in a dynamic environment where
@code{current-input-port} and @code{current-output-port} are bound to
a dummy string-port has a serializable continuation.

Here is an example where continuations are serialized:

@smallexample
> @b{(define (wr obj)
    (call-with-output-string
     '()
     (lambda (p)
       (output-port-readtable-set!
        p
        (readtable-sharing-allowed?-set
         (output-port-readtable p)
         'serialize))
       (write obj p))))}
> @b{(define (rd str)
    (call-with-input-string
     str
     (lambda (p)
       (input-port-readtable-set!
        p
        (readtable-sharing-allowed?-set
         (input-port-readtable p)
         'serialize))
       (read p))))}
> @b{(define fifo (open-vector))}
> @b{(define (suspend-and-die!)
    (call-with-current-continuation
     (lambda (k)
       (write (wr k) fifo)
       (newline fifo)
       (force-output fifo)
       (thread-terminate! (current-thread)))))}
> @b{(let ((dummy-port (open-string)))
    (parameterize ((current-input-port dummy-port)
                   (current-output-port dummy-port))
      (thread-start!
       (make-thread
        (lambda ()
          (* 100
             (suspend-and-die!)))))))}
#<thread #2>
> @b{(define s (read fifo))}
> @b{(thread-join!
    (thread-start!
      (make-thread
        (lambda ()
          ((rd s) 111)))))}
11100
> @b{(thread-join!
    (thread-start!
      (make-thread
        (lambda ()
          ((rd s) 222)))))}
22200
> @b{(string-length s)}
13114
@end smallexample

@end deffn

@deffn procedure readtable-eval-allowed? @var{readtable}
@deffnx procedure readtable-eval-allowed?-set @var{readtable} @var{new-value}

The procedure @code{readtable-eval-allowed?} returns the content of
the @samp{eval-allowed?} field of @var{readtable}.  The reader
recognizes the @code{#.@var{expression}} notation for read-time
evaluation if and only if the content of the @samp{eval-allowed?}
field is not @code{#f}.

The procedure @code{readtable-eval-allowed?-set} returns a copy
of @var{readtable} where only the @samp{eval-allowed?} field
has been changed to @var{new-value}.

For example:

@smallexample
> @b{(input-port-readtable-set!
    (repl-input-port)
    (readtable-eval-allowed?-set
      (input-port-readtable (repl-input-port))
      #t))}
> @b{'(5 plus 7 is #.(+ 5 7))}
(5 plus 7 is 12)
> @b{'(buf = #.(make-u8vector 25))}
(buf = #u8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
@end smallexample

@end deffn

@deffn procedure readtable-write-cdr-read-macros? @var{readtable}
@deffnx procedure readtable-write-cdr-read-macros?-set @var{readtable} @var{new-value}
@deffnx procedure readtable-write-extended-read-macros? @var{readtable}
@deffnx procedure readtable-write-extended-read-macros?-set @var{readtable} @var{new-value}

The procedure @code{readtable-write-cdr-read-macros?} returns the
content of the @samp{write-cdr-read-macros?} field of @var{readtable}.
The procedure @code{readtable-write-extended-read-macros?} returns the
content of the @samp{write-extended-read-macros?} field of
@var{readtable}.

At all times the printer uses read-macros in its output for datums of
the form @code{(quote @var{datum})}, @code{(quasiquote @var{datum})},
@code{(unquote @var{datum})}, and @code{(unquote-splicing
@var{datum})}.  That is the following read-macro notations will be
used respectively: @code{'@var{datum}}, @code{`@var{datum}},
@code{,@var{datum}}, and @code{,@@@var{datum}}.  Moreover, normally
the read-macros will not be used when the form appears in the cdr of a
list, for example @code{(foo quote bar)}, @code{(foo . (quote bar))}
and @code{(foo . 'bar)} will all be printed as @code{(foo quote bar)}.

When the content of the @samp{write-cdr-read-macros?} field is not
@code{#f}, the printer will use read-macros when the forms appear in
the cdr of a list.  For example @code{(foo quote bar)} will be printed
as @code{(foo . 'bar)}.  When the content of the
@samp{write-extended-read-macros?} field is not @code{#f}, the printer
will also use extended read-macros, for example @code{#'@var{datum}}
in place of @code{(syntax @var{datum})}.

The procedure @code{readtable-write-cdr-read-macros?-set} returns a
copy of @var{readtable} where only the @samp{write-cdr-read-macros?}
field has been changed to @var{new-value}.  The procedure
@code{readtable-write-extended-read-macros?-set} returns a copy of
@var{readtable} where only the @samp{write-extended-read-macros?}
field has been changed to @var{new-value}.

For example:

@smallexample
> @b{(output-port-readtable-set!
    (repl-output-port)
    (readtable-write-extended-read-macros?-set
      (output-port-readtable (repl-output-port))
      #t))}
> @b{'(foo (syntax bar))}
(foo #'bar)
> @b{'(foo syntax bar)}
(foo syntax bar)
> @b{(output-port-readtable-set!
    (repl-output-port)
    (readtable-write-cdr-read-macros?-set
      (output-port-readtable (repl-output-port))
      #t))}
> @b{'(foo syntax bar)}
(foo . #'bar)
@end smallexample

@end deffn

@deffn procedure readtable-max-write-level @var{readtable}
@deffnx procedure readtable-max-write-level-set @var{readtable} @var{new-value}

The procedure @code{readtable-max-write-level} returns the content of
the @samp{max-write-level} field of @var{readtable}.  The printer will
display an ellipsis for the elements of lists and vectors that are
nested deeper than this level.

The procedure @code{readtable-max-write-level-set} returns a copy
of @var{readtable} where only the @samp{max-write-level} field
has been changed to @var{new-value}, which must be an nonnegative
fixnum.

For example:

@smallexample
> @b{(define (wr obj n)
    (call-with-output-string
      '()
      (lambda (p)
        (output-port-readtable-set!
          p
          (readtable-max-write-level-set
            (output-port-readtable p)
            n))
        (write obj p))))}
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) a) 3)}
"(a #(b (c c) #u8(9 9 9) b) a)"
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) a) 2)}
"(a #(b (...) #u8(...) b) a)"
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) a) 1)}
"(a #(...) a)"
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) a) 0)}
"(...)"
> @b{(wr 'hello 0)}
"hello"
@end smallexample

@end deffn

@deffn procedure readtable-max-write-length @var{readtable}
@deffnx procedure readtable-max-write-length-set @var{readtable} @var{new-value}
The procedure @code{readtable-max-write-length} returns the content of
the @samp{max-write-length} field of @var{readtable}.  The printer will
display an ellipsis for the elements of lists and vectors that are at
an index beyond that length.

The procedure @code{readtable-max-write-length-set} returns a copy
of @var{readtable} where only the @samp{max-write-length} field
has been changed to @var{new-value}, which must be an nonnegative
fixnum.

For example:

@smallexample
> @b{(define (wr obj n)
    (call-with-output-string
      '()
      (lambda (p)
        (output-port-readtable-set!
          p
          (readtable-max-write-length-set
            (output-port-readtable p)
            n))
        (write obj p))))}
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) . a) 4)}
"(a #(b (c c) #u8(9 9 9) b) . a)"
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) . a) 3)}
"(a #(b (c c) #u8(9 9 9) ...) . a)"
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) . a) 2)}
"(a #(b (c c) ...) . a)"
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) . a) 1)}
"(a ...)"
> @b{(wr '(a #(b (c c) #u8(9 9 9) b) . a) 0)}
"(...)"
@end smallexample

@end deffn

@deffn procedure readtable-max-unescaped-char @var{readtable}
@deffnx procedure readtable-max-unescaped-char-set @var{readtable} @var{new-value}

The procedure @code{readtable-max-unescaped-char} returns the content
of the @samp{max-unescaped-char} field of @var{readtable}.  The
printer will display using an escape sequence any character within
symbols, strings and character objects greater than
@samp{max-unescaped-char}.  When @samp{max-unescaped-char} is
@code{#f}, the default value, the printer will take into account
the output port and use an escape sequence for any character that isn't
supported by the port's character encoding.

The procedure @code{readtable-max-unescaped-char-set} returns a copy
of @var{readtable} where only the @samp{max-unescaped-char} field
has been changed to @var{new-value}, which must be a character or
@code{#f}.

For example:

@smallexample
> @b{(define rt (output-port-readtable (repl-output-port)))}
> @b{(readtable-max-unescaped-char rt)}
#\delete
> @b{(string (integer->char 233))}
"\351"
> @b{(define (f c)
    (with-output-to-string
     (list readtable: (readtable-max-unescaped-char-set rt c))
     (lambda () (write (string (integer->char 233))))))}
> @b{(f #\delete)}
"\"\\351\""
> @b{(string-length (f #\delete))}
6
> @b{(f #\U0010ffff)}
"\"\351\""
> @b{(string-length (f #\U0010ffff))}
3
> @b{(output-port-readtable-set!
   (repl-output-port)
   (readtable-max-unescaped-char-set rt #\U0010ffff))}
> @b{(string (integer->char 233))}
"é"
@end smallexample

@end deffn

@deffn procedure readtable-start-syntax @var{readtable}
@deffnx procedure readtable-start-syntax-set @var{readtable} @var{new-value}

The procedure @code{readtable-start-syntax} returns the content of the
@samp{start-syntax} field of @var{readtable}.  The reader uses this
field to determine in which syntax to start parsing the input.  When
the content of this field is the symbol @code{six}, the reader starts
in the infix syntax.  Otherwise the reader starts in the prefix
syntax.

The procedure @code{readtable-start-syntax-set} returns a copy
of @var{readtable} where only the @samp{start-syntax} field
has been changed to @var{new-value}.

For example:

@smallexample
> @b{(+ 2 3)}
5
> @b{(input-port-readtable-set!
   (repl-input-port)
   (readtable-start-syntax-set
     (input-port-readtable (repl-input-port))
     'six))}
> @b{2+3;}
5
> @b{exit();}
@end smallexample

@end deffn

@node Boolean syntax, Character syntax, Readtables, Lexical syntax and readtables
@section Boolean syntax

Booleans are required to be followed by a delimiter
(i.e. @code{#f64()} is not the boolean @code{#f} followed by the
number @code{64} and the empty list).

@node Character syntax, String syntax, Boolean syntax, Lexical syntax and readtables
@section Character syntax

Characters are required to be followed by a delimiter
(i.e. @code{#\spaceballs} is not the character @code{#\space} followed
by the symbol @code{balls}).  The lexical syntax of characters is
extended to allow the following:

@table @code
@item #\nul
Unicode character 0
@item #\alarm
Unicode character 7
@item #\backspace
Unicode character 8
@item #\tab
Unicode character 9
@item #\newline
Unicode character 10 (newline character)
@item #\linefeed
Unicode character 10
@item #\vtab
Unicode character 11
@item #\page
Unicode character 12
@item #\return
Unicode character 13
@item #\esc
Unicode character 27
@item #\space
Unicode character 32 (space character)
@item #\delete
Unicode character 127
@item #\x@var{hh}
character encoded in hexadecimal (>= 1 hexadecimal digit)
@item #\u@var{hhhh}
character encoded in hexadecimal (exactly 4 hexadecimal digits)
@item #\U@var{hhhhhhhh}
character encoded in hexadecimal (exactly 8 hexadecimal digits)
@end table

@node String syntax, Symbol syntax, Character syntax, Lexical syntax and readtables
@section String syntax

The lexical syntax of quoted strings is extended to allow the following
escape codes:

@table @code
@item \a
Unicode character 7
@item \b
Unicode character 8
@item \t
Unicode character 9
@item \n
Unicode character 10 (newline character)
@item \v
Unicode character 11
@item \f
Unicode character 12
@item \r
Unicode character 13
@item \"
@code{"}
@item \\
@code{\}
@item \|
@code{|}
@item \?
@code{?}
@item \@var{ooo}
character encoded in octal (1 to 3 octal digits, first digit must be less
than 4 when there are 3 octal digits)
@item \x@var{hh}
character encoded in hexadecimal (>= 1 hexadecimal digit)
@item \u@var{hhhh}
character encoded in hexadecimal (exactly 4 hexadecimal digits)
@item \U@var{hhhhhhhh}
character encoded in hexadecimal (exactly 8 hexadecimal digits)
@item \<space>
Unicode character 32 (space character)
@item \<newline><whitespace-except-newline>*
This sequence expands to nothing (it is useful for splitting a long
string literal on multiple lines while respecting proper indentation
of the source code)
@end table

Gambit also supports a ``here string'' syntax that is similar
to shell ``here documents''.  For example:

@smallexample
> @b{(pretty-print #<<THE-END
hello
world
THE-END
)}
"hello\nworld"
@end smallexample

The here string starts with the sequence @samp{#<<}.  The part of the
line after the @samp{#<<} up to and including the newline character is
the key. The first line afterward that matches the key marks the end
of the here string.  The string contains all the characters between
the start key and the end key, with the exception of the newline
character before the end key.

@node Symbol syntax, Keyword syntax, String syntax, Lexical syntax and readtables
@section Symbol syntax

The lexical syntax of symbols is extended to allow a leading and
trailing vertical bar (e.g. @code{|a\|b"c:|}).  The symbol's name
corresponds verbatim to the characters between the vertical bars
except for escaped characters.  The same escape sequences as for
strings are permitted except that @samp{"} does not need to be escaped
and @samp{|} needs to be escaped.

For example:

@smallexample
> @b{(symbol->string '|a\|b"c:|)}
"a|b\"c:"
@end smallexample

@node Keyword syntax, Box syntax, Symbol syntax, Lexical syntax and readtables
@section Keyword syntax

The lexical syntax of keywords is like symbols, but with a colon at
the end (note that this can be changed to a leading colon by setting
the @samp{keywords-allowed?} field of the readtable to the symbol
@code{prefix}).  A colon by itself is not a keyword, it is a symbol.
Vertical bars can be used like symbols but the colon must be outside
the vertical bars.  Note that the string returned by the
@code{keyword->string} procedure does not include the colon.

For example:

@smallexample
> @b{(keyword->string 'foo:)}
"foo"
> @b{(map keyword? '(|ab()cd:| |ab()cd|: : ||:))}
(#f #t #f #t)
@end smallexample

@node Box syntax, Number syntax, Keyword syntax, Lexical syntax and readtables
@section Box syntax

The lexical syntax of boxes is @code{#&@var{obj}} where @var{obj} is the
content of the box.

For example:

@smallexample
> @b{(list '#&"hello" '#&123)}
(#&"hello" #&123)
> @b{(box (box (+ 10 20)))}
#&#&30
@end smallexample

@node Number syntax, Homogeneous vector syntax, Box syntax, Lexical syntax and readtables
@section Number syntax

The lexical syntax of the special inexact real numbers is as follows:

@table @code
@item +inf.0
positive infinity
@item -inf.0
negative infinity
@item +nan.0
``not a number''
@item -0.
negative zero (@samp{0.} is the positive zero)
@end table

@node Homogeneous vector syntax, Special #! syntax, Number syntax, Lexical syntax and readtables
@section Homogeneous vector syntax
@cindex homogeneous vectors

Homogeneous vectors are vectors containing raw numbers of the same
type (signed or unsigned exact integers or inexact reals).  There are
10 types of homogeneous vectors:
@samp{s8vector} (vector of 8 bit signed integers),
@samp{u8vector} (vector of 8 bit unsigned integers),
@samp{s16vector} (vector of 16 bit signed integers),
@samp{u16vector} (vector of 16 bit unsigned integers),
@samp{s32vector} (vector of 32 bit signed integers),
@samp{u32vector} (vector of 32 bit unsigned integers),
@samp{s64vector} (vector of 64 bit signed integers),
@samp{u64vector} (vector of 64 bit unsigned integers),
@samp{f32vector} (vector of 32 bit floating point numbers),
and @samp{f64vector} (vector of 64 bit floating point numbers).

The external representation of homogeneous vectors is similar to
normal vectors but with the @samp{#(} prefix replaced respectively
with
@samp{#s8(}, @samp{#u8(},
@samp{#s16(}, @samp{#u16(},
@samp{#s32(}, @samp{#u32(},
@samp{#s64(}, @samp{#u64(},
@samp{#f32(}, and @samp{#f64(}.

The elements of the integer homogeneous vectors must be exact integers
fitting in the given precision.  The elements of the floating point
homogeneous vectors must be inexact reals.

@node Special #! syntax, Multiline comment syntax, Homogeneous vector syntax, Lexical syntax and readtables
@section Special @code{#!} syntax

The lexical syntax of the special @code{#!} objects is as follows:

@table @code
@item #!eof
end-of-file object
@item #!void
void object
@item #!optional
optional object
@item #!rest
rest object
@item #!key
key object
@end table

@node Multiline comment syntax, Scheme infix syntax extension, Special #! syntax, Lexical syntax and readtables
@section Multiline comment syntax

Multiline comments are delimited by the tokens @samp{#|} and @samp{|#}.
These comments can be nested.

@node Scheme infix syntax extension, , Multiline comment syntax, Lexical syntax and readtables
@section Scheme infix syntax extension

The reader supports an infix syntax extension which is called SIX
(Scheme Infix eXtension).  This extension is both supported by the
@samp{read} procedure and in program source code.

The backslash character is a delimiter that marks the beginning of a
single datum expressed in the infix syntax (the details are given
below).  One way to think about it is that the backslash character
escapes the prefix syntax temporarily to use the infix syntax.  For
example a three element list could be written as @samp{(@var{X}
\@var{Y} @var{Z})}, the elements @var{X} and @var{Z} are expressed
using the normal prefix syntax and @var{Y} is expressed using the
infix syntax.

When the reader encounters an infix datum, it constructs a syntax tree
for that particular datum.  Each node of this tree is represented with
a list whose first element is a symbol indicating the type of node.
For example, @samp{(six.identifier abc)} is the representation of the
infix identifier @samp{abc} and @samp{(six.index (six.identifier abc)
(six.identifier i))} is the representation of the infix datum
@samp{abc[i];}.

@subsection SIX grammar

The SIX grammar is given below.  On the left hand side are the
production rules.  On the right hand side is the datum that is
constructed by the reader.  The notation @var{$i} denotes the datum
that is constructed by the reader for the @var{i}th part of the
production rule.

@macro meta{name}
@math{<}\name\@math{>}
@end macro

@macro syntaxdef{}
::=
@end macro

@macro syntaxspc{}
@asis{@ @ @ @ }
@end macro

@macro syntaxbar{}
@asis{@ @ |@ }
@end macro

@multitable @columnfractions .60 .40

@item
@meta{infix datum} @syntaxdef{}
@item
@syntaxspc{}@meta{stat} @tab @var{$1}

@item
@meta{stat} @syntaxdef{}
@item
@syntaxspc{}@meta{if stat} @tab @var{$1}
@item
@syntaxbar{}@meta{for stat} @tab @var{$1}
@item
@syntaxbar{}@meta{while stat} @tab @var{$1}
@item
@syntaxbar{}@meta{do stat} @tab @var{$1}
@item
@syntaxbar{}@meta{switch stat} @tab @var{$1}
@item
@syntaxbar{}@meta{case stat} @tab @var{$1}
@item
@syntaxbar{}@meta{break stat} @tab @var{$1}
@item
@syntaxbar{}@meta{continue stat} @tab @var{$1}
@item
@syntaxbar{}@meta{label stat} @tab @var{$1}
@item
@syntaxbar{}@meta{goto stat} @tab @var{$1}
@item
@syntaxbar{}@meta{return stat} @tab @var{$1}
@item
@syntaxbar{}@meta{expression stat} @tab @var{$1}
@item
@syntaxbar{}@meta{procedure definition} @tab @var{$1}
@item
@syntaxbar{}@meta{variable definition} @code{;} @tab @var{$1}
@item
@syntaxbar{}@meta{clause stat} @tab @var{$1}
@item
@syntaxbar{}@meta{compound stat} @tab @var{$1}
@item
@syntaxbar{}@code{;} @tab @code{(six.compound)}

@item
@meta{if stat} @syntaxdef{}
@item
@syntaxspc{}@code{if} @code{(} @meta{pexpr} @code{)} @meta{stat} @tab @code{(six.if @var{$3} @var{$5})}
@item
@syntaxbar{}@code{if} @code{(} @meta{pexpr} @code{)} @meta{stat} @code{else} @meta{stat} @tab @code{(six.if @var{$3} @var{$5} @var{$7})}

@item
@meta{for stat} @syntaxdef{}
@item
@syntaxspc{}@code{for} @code{(} @meta{stat} @code{;} @meta{oexpr} @code{;} @meta{oexpr} @code{)} @meta{stat} @tab @code{(six.for @var{$3} @var{$5} @var{$7} @var{$9})}

@item
@meta{while stat} @syntaxdef{}
@item
@syntaxspc{}@code{while} @code{(} @meta{pexpr} @code{)} @meta{stat} @tab @code{(six.while @var{$3} @var{$5})}

@item
@meta{do stat} @syntaxdef{}
@item
@syntaxspc{}@code{do} @meta{stat} @code{while} @code{(} @meta{pexpr} @code{)} @code{;} @tab @code{(six.do-while @var{$2} @var{$5})}

@item
@meta{switch stat} @syntaxdef{}
@item
@syntaxspc{}@code{switch} @code{(} @meta{pexpr} @code{)} @meta{stat} @tab @code{(six.switch @var{$3} @var{$5})}

@item
@meta{case stat} @syntaxdef{}
@item
@syntaxspc{}@code{case} @meta{expr} @code{:} @meta{stat} @tab @code{(six.case @var{$2} @var{$4})}

@item
@meta{break stat} @syntaxdef{}
@item
@syntaxspc{}@code{break} @code{;} @tab @code{(six.break)}

@item
@meta{continue stat} @syntaxdef{}
@item
@syntaxspc{}@code{continue} @code{;} @tab @code{(six.continue)}

@item
@meta{label stat} @syntaxdef{}
@item
@syntaxspc{}@meta{identifier} @code{:} @meta{stat} @tab @code{(six.label @var{$1} @var{$3})}

@item
@meta{goto stat} @syntaxdef{}
@item
@syntaxspc{}@code{goto} @meta{expr} @code{;} @tab @code{(six.goto @var{$2})}

@item
@meta{return stat} @syntaxdef{}
@item
@syntaxspc{}@code{return} @code{;} @tab @code{(six.return)}
@item
@syntaxbar{}@code{return} @meta{expr} @code{;} @tab @code{(six.return @var{$2})}

@item
@meta{expression stat} @syntaxdef{}
@item
@syntaxspc{}@meta{expr} @code{;} @tab @var{$1}

@item
@meta{clause stat} @syntaxdef{}
@item
@syntaxspc{}@meta{expr} @code{.} @tab @code{(six.clause @var{$1})}

@item
@meta{pexpr} @syntaxdef{}
@item
@syntaxspc{}@meta{procedure definition} @tab @var{$1}
@item
@syntaxbar{}@meta{variable definition} @tab @var{$1}
@item
@syntaxbar{}@meta{expr} @tab @var{$1}

@item
@meta{procedure definition} @syntaxdef{}
@item
@syntaxspc{}@meta{type} @meta{id-or-prefix} @code{(} @meta{parameters} @code{)} @meta{body} @tab @code{(six.define-procedure @var{$2} (six.procedure @var{$1} @var{$4} @var{$6}))}

@item
@meta{variable definition} @syntaxdef{}
@item
@syntaxspc{}@meta{type} @meta{id-or-prefix} @meta{dimensions} @meta{iexpr} @tab @code{(six.define-variable @var{$2} @var{$1} @var{$3} @var{$4})}

@item
@meta{iexpr} @syntaxdef{}
@item
@syntaxspc{}@code{=} @meta{expr} @tab @var{$2}
@item
@syntaxbar{}@tab @code{#f}

@item
@meta{dimensions} @syntaxdef{}
@item
@syntaxbar{}@code{[} @meta{expr} @code{]} @meta{dimensions} @tab @code{(@var{$2} . @var{$4})}
@item
@syntaxbar{}@tab @code{()}

@item
@meta{oexpr} @syntaxdef{}
@item
@syntaxspc{}@meta{expr} @tab @var{$1}
@item
@syntaxbar{}@tab @code{#f}

@item
@meta{expr} @syntaxdef{}
@item
@syntaxspc{}@meta{expr18} @tab @var{$1}

@item
@meta{expr18} @syntaxdef{}
@item
@syntaxspc{}@meta{expr17} @code{:-} @meta{expr18} @tab @code{(six.x:-y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr17} @tab @var{$1}

@item
@meta{expr17} @syntaxdef{}
@item
@syntaxspc{}@meta{expr17} @code{,} @meta{expr16} @tab @code{(|six.x,y| @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr16} @tab @var{$1}

@item
@meta{expr16} @syntaxdef{}
@item
@syntaxspc{}@meta{expr15} @code{:=} @meta{expr16} @tab @code{(six.x:=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr15} @tab @var{$1}

@item
@meta{expr15} @syntaxdef{}
@item
@syntaxspc{}@meta{expr14} @code{%=} @meta{expr15} @tab @code{(six.x%=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{&=} @meta{expr15} @tab @code{(six.x&=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{*=} @meta{expr15} @tab @code{(six.x*=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{+=} @meta{expr15} @tab @code{(six.x+=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{-=} @meta{expr15} @tab @code{(six.x-=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{/=} @meta{expr15} @tab @code{(six.x/=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{<<=} @meta{expr15} @tab @code{(six.x<<=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{=} @meta{expr15} @tab @code{(six.x=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{>>=} @meta{expr15} @tab @code{(six.x>>=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{^=} @meta{expr15} @tab @code{(six.x^=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @code{|=} @meta{expr15} @tab @code{(|six.x\|=y| @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr14} @tab @var{$1}

@item
@meta{expr14} @syntaxdef{}
@item
@syntaxspc{}@meta{expr13} @code{:} @meta{expr14} @tab @code{(six.x:y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr13} @tab @var{$1}

@item
@meta{expr13} @syntaxdef{}
@item
@syntaxspc{}@meta{expr12} @code{?} @meta{expr} @code{:} @meta{expr13} @tab @code{(six.x?y:z @var{$1} @var{$3} @var{$5})}
@item
@syntaxbar{}@meta{expr12} @tab @var{$1}

@item
@meta{expr12} @syntaxdef{}
@item
@syntaxspc{}@meta{expr12} @code{||} @meta{expr11} @tab @code{(|six.x\|\|y| @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr11} @tab @var{$1}

@item
@meta{expr11} @syntaxdef{}
@item
@syntaxspc{}@meta{expr11} @code{&&} @meta{expr10} @tab @code{(six.x&&y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr10} @tab @var{$1}

@item
@meta{expr10} @syntaxdef{}
@item
@syntaxspc{}@meta{expr10} @code{|} @meta{expr9} @tab @code{(|six.x\|y| @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr9} @tab @var{$1}

@item
@meta{expr9} @syntaxdef{}
@item
@syntaxspc{}@meta{expr9} @code{^} @meta{expr8} @tab @code{(six.x^y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr8} @tab @var{$1}

@item
@meta{expr8} @syntaxdef{}
@item
@syntaxspc{}@meta{expr8} @code{&} @meta{expr7} @tab @code{(six.x&y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr7} @tab @var{$1}

@item
@meta{expr7} @syntaxdef{}
@item
@syntaxspc{}@meta{expr7} @code{!=} @meta{expr6} @tab @code{(six.x!=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr7} @code{==} @meta{expr6} @tab @code{(six.x==y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr6} @tab @var{$1}

@item
@meta{expr6} @syntaxdef{}
@item
@syntaxspc{}@meta{expr6} @code{<} @meta{expr5} @tab @code{(six.x<y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr6} @code{<=} @meta{expr5} @tab @code{(six.x<=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr6} @code{>} @meta{expr5} @tab @code{(six.x>y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr6} @code{>=} @meta{expr5} @tab @code{(six.x>=y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr5} @tab @var{$1}

@item
@meta{expr5} @syntaxdef{}
@item
@syntaxspc{}@meta{expr5} @code{<<} @meta{expr4} @tab @code{(six.x<<y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr5} @code{>>} @meta{expr4} @tab @code{(six.x>>y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr4} @tab @var{$1}

@item
@meta{expr4} @syntaxdef{}
@item
@syntaxspc{}@meta{expr4} @code{+} @meta{expr3} @tab @code{(six.x+y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr4} @code{-} @meta{expr3} @tab @code{(six.x-y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr3} @tab @var{$1}

@item
@meta{expr3} @syntaxdef{}
@item
@syntaxspc{}@meta{expr3} @code{%} @meta{expr2} @tab @code{(six.x%y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr3} @code{*} @meta{expr2} @tab @code{(six.x*y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr3} @code{/} @meta{expr2} @tab @code{(six.x/y @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr2} @tab @var{$1}

@item
@meta{expr2} @syntaxdef{}
@item
@syntaxspc{}@code{&} @meta{expr2} @tab @code{(six.&x @var{$2})}
@item
@syntaxbar{}@code{+} @meta{expr2} @tab @code{(six.+x @var{$2})}
@item
@syntaxbar{}@code{-} @meta{expr2} @tab @code{(six.-x @var{$2})}
@item
@syntaxbar{}@code{*} @meta{expr2} @tab @code{(six.*x @var{$2})}
@item
@syntaxbar{}@code{!} @meta{expr2} @tab @code{(six.!x @var{$2})}
@item
@syntaxbar{}@code{!} @tab @code{(six.!)}
@item
@syntaxbar{}@code{++} @meta{expr2} @tab @code{(six.++x @var{$2})}
@item
@syntaxbar{}@code{--} @meta{expr2} @tab @code{(six.--x @var{$2})}
@item
@syntaxbar{}@code{~} @meta{expr2} @tab @code{(six.~x @var{$2})}
@item
@syntaxbar{}@code{new} @meta{id-or-prefix} @code{(} @meta{arguments} @code{)} @tab @code{(six.new @var{$2} . @var{$4})}
@item
@syntaxbar{}@meta{expr1} @tab @var{$1}

@item
@meta{expr1} @syntaxdef{}
@item
@syntaxspc{}@meta{expr1} @code{++} @tab @code{(six.x++ @var{$1})}
@item
@syntaxbar{}@meta{expr1} @code{--} @tab @code{(six.x-- @var{$1})}
@item
@syntaxbar{}@meta{expr1} @code{(} @meta{arguments} @code{)} @tab @code{(six.call @var{$1} . @var{$3})}
@item
@syntaxbar{}@meta{expr1} @code{[} @meta{expr} @code{]} @tab @code{(six.index @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr1} @code{->} @meta{id-or-prefix} @tab @code{(six.arrow @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr1} @code{.} @meta{id-or-prefix} @tab @code{(six.dot @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr0} @tab @var{$1}

@item
@meta{expr0} @syntaxdef{}
@item
@syntaxspc{}@meta{id-or-prefix} @tab @var{$1}
@item
@syntaxbar{}@meta{string} @tab @code{(six.literal @var{$1})}
@item
@syntaxbar{}@meta{char} @tab @code{(six.literal @var{$1})}
@item
@syntaxbar{}@meta{number} @tab @code{(six.literal @var{$1})}
@item
@syntaxbar{}@code{(} @meta{expr} @code{)} @tab @var{$2}
@item
@syntaxbar{}@code{(} @meta{block stat} @code{)} @tab @var{$2}
@item
@syntaxbar{}@meta{datum-starting-with-#-or-backquote}  @tab @code{(six.prefix @var{$1})}
@item
@syntaxbar{}@code{[} @meta{elements} @code{]} @tab @var{$2}
@item
@syntaxbar{}@meta{type} @code{(} @meta{parameters} @code{)} @meta{body} @tab @code{(six.procedure @var{$1} @var{$3} @var{$5})}

@item
@meta{block stat} @syntaxdef{}
@item
@syntaxspc{}@code{@{} @meta{stat list} @code{@}} @tab @code{(six.compound . @var{$2})}

@item
@meta{body} @syntaxdef{}
@item
@syntaxspc{}@code{@{} @meta{stat list} @code{@}} @tab @code{(six.procedure-body . @var{$2})}

@item
@meta{stat list} @syntaxdef{}
@item
@syntaxspc{}@meta{stat} @meta{stat list} @tab @code{(@var{$1} . @var{$2})}
@item
@syntaxbar{}@tab @code{()}

@item
@meta{parameters} @syntaxdef{}
@item
@syntaxspc{}@meta{nonempty parameters} @tab @var{$1}
@item
@syntaxbar{}@tab @code{()}

@item
@meta{nonempty parameters} @syntaxdef{}
@item
@syntaxspc{}@meta{parameter} @code{,} @meta{nonempty parameters} @tab @code{(@var{$1} . @var{$3})}
@item
@syntaxbar{}@meta{parameter} @tab @code{(@var{$1})}

@item
@meta{parameter} @syntaxdef{}
@item
@syntaxspc{}@meta{type} @meta{id-or-prefix} @tab @code{(@var{$2} @var{$1})}

@item
@meta{arguments} @syntaxdef{}
@item
@syntaxspc{}@meta{nonempty arguments} @tab @var{$1}
@item
@syntaxbar{}@tab @code{()}

@item
@meta{nonempty arguments} @syntaxdef{}
@item
@syntaxspc{}@meta{expr} @code{,} @meta{nonempty arguments} @tab @code{(@var{$1} . @var{$3})}
@item
@syntaxbar{}@meta{expr} @tab @code{(@var{$1})}

@item
@meta{elements} @syntaxdef{}
@item
@syntaxspc{}@meta{nonempty elements} @tab @var{$1}
@item
@syntaxbar{}@tab @code{(six.null)}

@item
@meta{nonempty elements} @syntaxdef{}
@item
@syntaxspc{}@meta{expr} @tab @code{(six.list @var{$1} (six.null))}
@item
@syntaxbar{}@meta{expr} @code{,} @meta{nonempty elements} @tab @code{(six.list @var{$1} @var{$3})}
@item
@syntaxbar{}@meta{expr} @code{|} @meta{expr} @tab @code{(six.cons @var{$1} @var{$3})}

@item
@meta{id-or-prefix} @syntaxdef{}
@item
@syntaxspc{}@meta{identifier} @tab @code{(six.identifier @var{$1})}
@item
@syntaxbar{}@code{\} @meta{datum} @tab @code{(six.prefix @var{$2})}

@item
@meta{type} @syntaxdef{}
@item
@syntaxspc{}@code{int} @tab @code{int}
@item
@syntaxbar{}@code{char} @tab @code{char}
@item
@syntaxbar{}@code{bool} @tab @code{bool}
@item
@syntaxbar{}@code{void} @tab @code{void}
@item
@syntaxbar{}@code{float} @tab @code{float}
@item
@syntaxbar{}@code{double} @tab @code{double}
@item
@syntaxbar{}@code{obj} @tab @code{obj}

@end multitable

@subsection SIX semantics

The semantics of SIX depends on the definition of the
@code{six.@var{XXX}} identifiers (as functions and macros).  Many of
these identifiers are predefined macros which give SIX a semantics
that is close to C's.  The user may override these definitions to
change the semantics either globally or locally.  For example,
@code{six.x^y} is a predefined macro that expands @code{(six.x^y x y)}
into @code{(bitwise-xor x y)}.  If the user prefers the @samp{^}
operator to express exponentiation in a specific function, then in
that function @code{six.x^y} can be redefined as a macro that expands
@code{(six.x^y x y)} into @code{(expt x y)}.  Note that the
associativity and precedence of operators cannot be changed as that is
a syntactic issue.

Note that the following identifiers are not predefined, and
consequently they do not have a predefined semantics:
@code{six.label}, @code{six.goto}, @code{six.switch}, @code{six.case},
@code{six.break}, @code{six.continue}, @code{six.return},
@code{six.clause}, @code{six.x:-y}, and @code{six.!}.

The following is an example showing some of the predefined semantics
of SIX:

@smallexample
> @b{(list (+ 1 2) \3+4; (+ 5 6))}
(3 7 11)
> @b{\[ 1+2, \(+ 3 4), 5+6 ];}
(3 7 11)
> @b{(map (lambda (x) \(x*x-1)/log(x+1);) '(1 2 3 4))}
(0 2.730717679880512 5.7707801635558535 9.320024018394177)
> @b{\obj n = expt(10,5);}
> @b{n}
100000
> @b{\obj t[3][10] = 88;}
> @b{\t[0][9] = t[2][1] = 11;}
11
> @b{t}
#(#(88 88 88 88 88 88 88 88 88 11)
  #(88 88 88 88 88 88 88 88 88 88)
  #(88 11 88 88 88 88 88 88 88 88))
> @b{\obj radix = new parameter (10);}
> @b{\radix(2);}
> @b{\radix();}
2
> @b{\for (int i=0; i<5; i++) pp(1<<i*8);}
1
256
65536
16777216
4294967296
> @b{\obj \make-adder (obj x) @{ obj (obj y) @{ x+y; @}; @}}
> @b{\map (new adder (100), [1,2,3,4]);}
(101 102 103 104)
> @b{(map (make-adder 100) (list 1 2 3 4))}
(101 102 103 104)
@end smallexample

@node C-interface, System limitations, Lexical syntax and readtables, Top
@chapter C-interface
@cindex FFI
@cindex foreign function interface

The Gambit Scheme system offers a mechanism for interfacing Scheme code
and C code called the ``C-interface''.  A Scheme program indicates which
C functions it needs to have access to and which Scheme procedures can
be called from C, and the C interface automatically constructs the
corresponding Scheme procedures and C functions.  The conversions needed
to transform data from the Scheme representation to the C representation
(and back), are generated automatically in accordance with the argument
and result types of the C function or Scheme procedure.

The C-interface places some restrictions on the types of data that can
be exchanged between C and Scheme.  The mapping of data types between C
and Scheme is discussed in the next section.  The remaining sections of
this chapter describe each special form of the C-interface.

@menu
* mapping of types::                The mapping of types between C and Scheme
* c-declare::                       The @code{c-declare} special form
* c-initialize::                    The @code{c-initialize} special form
* c-lambda::                        The @code{c-lambda} special form
* c-define::                        The @code{c-define} special form
* c-define-type::                   The @code{c-define-type} special form
* continuations::                   Continuations and the C-interface
@end menu

@node mapping of types, c-declare, C-interface, C-interface
@section The mapping of types between C and Scheme

Scheme and C do not provide the same set of built-in data types so it is
important to understand which Scheme type is compatible with which C
type and how values get mapped from one environment to the other.  To
improve compatibility a new type is added to Scheme, the @samp{foreign}
object type, and the following data types are added to C:

@table @code
@item scheme-object
denotes the universal type of Scheme objects
(type @code{___SCMOBJ} defined in @samp{gambit.h})
@item bool
denotes the C++ @samp{bool} type or the C @samp{int} type
(type @code{___BOOL} defined in @samp{gambit.h})
@item int8
8 bit signed integer (type @code{___S8} defined in @samp{gambit.h})
@item unsigned-int8
8 bit unsigned integer (type @code{___U8} defined in @samp{gambit.h})
@item int16
16 bit signed integer (type @code{___S16} defined in @samp{gambit.h})
@item unsigned-int16
16 bit unsigned integer (type @code{___U16} defined in @samp{gambit.h})
@item int32
32 bit signed integer (type @code{___S32} defined in @samp{gambit.h})
@item unsigned-int32
32 bit unsigned integer (type @code{___U32} defined in @samp{gambit.h})
@item int64
64 bit signed integer (type @code{___S64} defined in @samp{gambit.h})
@item unsigned-int64
64 bit unsigned integer (type @code{___U64} defined in @samp{gambit.h})
@item float32
32 bit floating point number (type @code{___F32} defined in @samp{gambit.h})
@item float64
64 bit floating point number (type @code{___F64} defined in @samp{gambit.h})
@item ISO-8859-1
denotes ISO-8859-1 encoded characters
(8 bit unsigned integer, type @code{___ISO_8859_1} defined in @samp{gambit.h})
@item UCS-2
denotes UCS-2 encoded characters
(16 bit unsigned integer, type @code{___UCS_2} defined in @samp{gambit.h})
@item UCS-4
denotes UCS-4 encoded characters
(32 bit unsigned integer, type @code{___UCS_4} defined in @samp{gambit.h})
@item char-string
denotes the C @samp{char*} type when used as a null terminated string
@item nonnull-char-string
denotes the nonnull C @samp{char*} type when used as a null terminated string
@item nonnull-char-string-list
denotes an array of nonnull C @samp{char*} terminated with a null pointer
@item ISO-8859-1-string
denotes ISO-8859-1 encoded strings
(null terminated string of 8 bit unsigned integers, i.e. @code{___ISO_8859_1*})
@item nonnull-ISO-8859-1-string
denotes nonnull ISO-8859-1 encoded strings
(null terminated string of 8 bit unsigned integers, i.e. @code{___ISO_8859_1*})
@item nonnull-ISO-8859-1-stringlist
denotes an array of nonnull ISO-8859-1 encoded strings terminated with a null pointer
@item UTF-8-string
denotes UTF-8 encoded strings
(null terminated string of @code{char}, i.e. @code{char*})
@item nonnull-UTF-8-string
denotes nonnull UTF-8 encoded strings
(null terminated string of @code{char}, i.e. @code{char*})
@item nonnull-UTF-8-string-list
denotes an array of nonnull UTF-8 encoded strings terminated with a null pointer
@item UTF-16-string
denotes UTF-16 encoded strings
(null terminated string of @code{char}, i.e. @code{char*})
@item nonnull-UTF-16-string
denotes nonnull UTF-16 encoded strings
(null terminated string of @code{char}, i.e. @code{char*})
@item nonnull-UTF-16-string-list
denotes an array of nonnull UTF-16 encoded strings terminated with a null pointer
@item UCS-2-string
denotes UCS-2 encoded strings
(null terminated string of 16 bit unsigned integers, i.e. @code{___UCS_2*})
@item nonnull-UCS-2-string
denotes nonnull UCS-2 encoded strings
(null terminated string of 16 bit unsigned integers, i.e. @code{___UCS_2*})
@item nonnull-UCS-2-string-list
denotes an array of nonnull UCS-2 encoded strings terminated with a null pointer
@item UCS-4-string
denotes UCS-4 encoded strings
(null terminated string of 32 bit unsigned integers, i.e. @code{___UCS_4*})
@item nonnull-UCS-4-string
denotes nonnull UCS-4 encoded strings
(null terminated string of 32 bit unsigned integers, i.e. @code{___UCS_4*})
@item nonnull-UCS-4-string-list
denotes an array of nonnull UCS-4 encoded strings terminated with a null pointer
@item wchar_t-string
denotes @code{wchar_t} encoded strings
(null terminated string of @code{wchar_t}, i.e. @code{wchar_t*})
@item nonnull-wchar_t-string
denotes nonnull @code{wchar_t} encoded strings
(null terminated string of @code{wchar_t}, i.e. @code{wchar_t*})
@item nonnull-wchar_t-string-list
denotes an array of nonnull @code{wchar_t} encoded strings terminated with a null pointer
@end table

To specify a particular C type inside the @code{c-lambda},
@code{c-define} and @code{c-define-type} forms, the following ``Scheme
notation'' is used:

@table @code
@item @r{Scheme notation}
C type
@item void
@code{void}
@item bool
@code{bool}
@item char
@code{char}  (may be signed or unsigned depending on the C compiler)
@item signed-char
@code{signed char}
@item unsigned-char
@code{unsigned char}
@item ISO-8859-1
@code{ISO-8859-1}
@item UCS-2
@code{UCS-2}
@item UCS-4
@code{UCS-4}
@item wchar_t
@code{wchar_t}
@item size_t
@code{size_t} (type @code{___SIZE_T} defined in @samp{gambit.h})
@item ssize_t
@code{ssize_t} (type @code{___SSIZE_T} defined in @samp{gambit.h})
@item ptrdiff_t
@code{ptrdiff_t} (type @code{___PTRDIFF_T} defined in @samp{gambit.h})
@item short
@code{short}
@item unsigned-short
@code{unsigned short}
@item int
@code{int}
@item unsigned-int
@code{unsigned int}
@item long
@code{long}
@item unsigned-long
@code{unsigned long}
@item long-long
@code{long long}
@item unsigned-long-long
@code{unsigned long long}
@item float
@code{float}
@item double
@code{double}
@item int8
@code{int8}
@item unsigned-int8
@code{unsigned-int8}
@item int16
@code{int16}
@item unsigned-int16
@code{unsigned-int16}
@item int32
@code{int32}
@item unsigned-int32
@code{unsigned-int32}
@item int64
@code{int64}
@item unsigned-int64
@code{unsigned-int64}
@item float32
@code{float32}
@item float64
@code{float64}
@item (struct "@var{c-struct-id}" @r{[}@var{tags} @r{[}@var{release-function}@r{]}@r{]})
@code{struct @var{c-struct-id}}  (where @var{c-struct-id} is the name of a
C structure; see below for the meaning of @var{tags} and @var{release-function})
@item (union "@var{c-union-id}" @r{[}@var{tags} @r{[}@var{release-function}@r{]}@r{]})
@code{union @var{c-union-id}}  (where @var{c-union-id} is the name of a
C union; see below for the meaning of @var{tags} and @var{release-function})
@item (type "@var{c-type-id}" @r{[}@var{tags} @r{[}@var{release-function}@r{]}@r{]})
@code{@var{c-type-id}}  (where @var{c-type-id} is an identifier naming a
C type; see below for the meaning of @var{tags} and @var{release-function})
@item (pointer @var{type} @r{[}@var{tags} @r{[}@var{release-function}@r{]}@r{]})
@code{@var{T}*}  (where @var{T} is the C equivalent of @var{type}
which must be the Scheme notation of a C type; see below for the meaning
of @var{tags} and @var{release-function})
@item (nonnull-pointer @var{type} @r{[}@var{tags} @r{[}@var{release-function}@r{]}@r{]})
same as @code{(pointer @var{type} @r{[}@var{tags} @r{[}@var{release-function}@r{]}@r{]})}
except the @code{NULL} pointer is not allowed
@item (function (@var{type1}@dots{}) @var{result-type})
function with the given argument types and result type
@item (nonnull-function (@var{type1}@dots{}) @var{result-type})
same as @code{(function (@var{type1}@dots{}) @var{result-type})}
except the @code{NULL} pointer is not allowed
@item char-string
@code{char-string}
@item nonnull-char-string
@code{nonnull-char-string}
@item nonnull-char-string-list
@code{nonnull-char-string-list}
@item ISO-8859-1-string
@code{ISO-8859-1-string}
@item nonnull-ISO-8859-1-string
@code{nonnull-ISO-8859-1-string}
@item nonnull-ISO-8859-1-string-list
@code{nonnull-ISO-8859-1-string-list}
@item UTF-8-string
@code{UTF-8-string}
@item nonnull-UTF-8-string
@code{nonnull-UTF-8-string}
@item nonnull-UTF-8-string-list
@code{nonnull-UTF-8-string-list}
@item UTF-16-string
@code{UTF-16-string}
@item nonnull-UTF-16-string
@code{nonnull-UTF-16-string}
@item nonnull-UTF-16-string-list
@code{nonnull-UTF-16-string-list}
@item UCS-2-string
@code{UCS-2-string}
@item nonnull-UCS-2-string
@code{nonnull-UCS-2-string}
@item nonnull-UCS-2-string-list
@code{nonnull-UCS-2-string-list}
@item UCS-4-string
@code{UCS-4-string}
@item nonnull-UCS-4-string
@code{nonnull-UCS-4-string}
@item nonnull-UCS-4-string-list
@code{nonnull-UCS-4-string-list}
@item wchar_t-string
@code{wchar_t-string}
@item nonnull-wchar_t-string
@code{nonnull-wchar_t-string}
@item nonnull-wchar_t-string-list
@code{nonnull-wchar_t-string-list}
@item scheme-object
@code{scheme-object}
@item @var{name}
appropriate translation of @var{name} (where @var{name}
is a C type defined with @code{c-define-type})
@item "@var{c-type-id}"
@var{c-type-id} (this form is equivalent to @code{(type "@var{c-type-id}")})
@end table

The @code{struct}, @code{union}, @code{type}, @code{pointer} and
@code{nonnull-pointer} types are ``foreign types'' and they are
represented on the Scheme side as ``foreign objects''.  A foreign object
is internally represented as a pointer.  This internal pointer is
identical to the C pointer being represented in the case of the
@code{pointer} and @code{nonnull-pointer} types.

In the case of the @code{struct}, @code{union} and @code{type} types,
the internal pointer points to a copy of the C data type being
represented.  When an instance of one of these types is converted from C
to Scheme, a block of memory is allocated from the C heap and
initialized with the instance and then a foreign object is allocated
from the Scheme heap and initialized with the pointer to this copy.
This approach may appear overly complex, but it allows the conversion of
C++ classes that do not have a zero parameter constructor or an
assignment method (i.e. when compiling with a C++ compiler an instance
is copied using @samp{new @var{type} (@var{instance})}, which calls the
copy-constructor of @var{type} if it is a class; @var{type}'s assignment
operator is never used).  Conversion from Scheme to C simply
dereferences the internal pointer (no allocation from the C heap is
performed).  Deallocation of the copy on the C heap is under the control
of the release function attached to the foreign object (see below).

The optional @var{tags} field of foreign type specifications is used
for type checking on the Scheme side.  The @var{tags} field must be
@code{#f}, a symbol or a non-empty list of symbols.  When it is not
specified the @var{tags} field defaults to a symbol whose name, as
returned by @code{symbol->string}, is the C type declaration for that
type.  For example the symbol @samp{char**} is the default for the
type @samp{(pointer (pointer char))}.  A @var{tags} field that is a
single symbol is equivalent to a list containing only that symbol.
The first symbol in the list of tags is the primary tag.  For example
the primary tag of the type @samp{(pointer char)} is @samp{char*} and
the primary tag of the type @samp{(pointer char (foo bar))} is
@samp{foo}.

Type compatibility between two foreign types depends on their tags.
An instance of a foreign type @var{T} can be used where a foreign type
@var{E} is expected if and only if

@itemize @bullet{}

@item
@var{T}'s @var{tags} field is @code{#f}, or

@item
@var{E}'s @var{tags} field is @code{#f}, or

@item
@var{T}'s primary tag is a member of @var{E}'s tags.

@end itemize

For the safest code a @var{tags} field of @code{#f} should be used
sparingly, as it completely bypasses type checking.  The external
representation of Scheme foreign objects (used by the @code{write}
procedure) contains the primary tag (if the @var{tags} field is not
@code{#f}), and the hexadecimal address denoted by the internal
pointer, for example @samp{#<char** #2 0x2AAC535C>}.  Note that the
hexadecimal address is in C notation, which can be easily transferred
to a C debugger with a ``cut-and-paste''.

A @var{release-function} can also be specified within a foreign type
specification.  The @var{release-function} must be @code{#f} or a string
naming a C function with a single parameter of type @samp{void*} (in
which the internal pointer is passed) and with a result of type
@samp{___SCMOBJ} (for returning an error code).  When the
@var{release-function} is not specified or is @code{#f} a default
function is constructed by the C-interface.  This default function does
nothing in the case of the @code{pointer} and @code{nonnull-pointer}
types (deallocation is not the responsibility of the C-interface) and
returns the fixnum @samp{___FIX(___NO_ERR)} to indicate no error.  In
the case of the @code{struct}, @code{union} and @code{type} types, the
default function reclaims the copy on the C heap referenced by the
internal pointer (when using a C++ compiler this is done using
@samp{delete (@var{type}*)@var{internal-pointer}}, which calls the
destructor of @var{type} if it is a class) and returns
@samp{___FIX(___NO_ERR)}.  In many situations the default
@var{release-function} will perform the appropriate cleanup for the
foreign type.  However, in certain cases special operations (such as
decrementing a reference count, removing the object from a table, etc)
must be performed.  For such cases a user supplied
@var{release-function} is needed.

The @var{release-function} is invoked at most once for any foreign
object.  After the @var{release-function} is invoked, the foreign
object is considered ``released'' and can no longer be used in a
foreign type conversion.  When the garbage collector detects that a
foreign object is no longer reachable by the program, it will invoke
the @var{release-function} if the foreign object is not yet released.
When there is a need to release the foreign object promptly, the
program can explicitly call @code{(foreign-release! @var{obj})} which
invokes the @var{release-function} if the foreign object is not yet
released, and does nothing otherwise.  The call
@code{(foreign-released? @var{obj})} returns a boolean indicating
whether the foreign object @var{obj} has been released yet or not.
The call @code{(foreign-address @var{obj})} returns the address
denoted by the internal pointer of foreign object @var{obj} or 0 if it
has been released.  The call @code{(foreign? @var{obj})} tests that
@var{obj} is a foreign object.  Finally the call @code{(foreign-tags
@var{obj})} returns the list of tags of foreign object @var{obj}, or
@code{#f}.

The following table gives the C types to which each Scheme type
can be converted:

@table @asis
@item Scheme type
Allowed target C types
@item boolean @code{#f}
@code{scheme-object}; @code{bool};
@code{pointer};
@code{function};
@code{char-string};
@code{ISO-8859-1-string};
@code{UTF-8-string};
@code{UTF-16-string};
@code{UCS-2-string};
@code{UCS-4-string};
@code{wchar_t-string}
@item boolean @code{#t}
@code{scheme-object}; @code{bool}
@item character
@code{scheme-object}; @code{bool};
@r{[}@code{@r{[}un@r{]}signed}@r{]} @code{char}; @code{ISO-8859-1}; @code{UCS-2};
@code{UCS-4}; @code{wchar_t}
@item exact integer
@code{scheme-object}; @code{bool}; @r{[}@code{unsigned-}@r{]}
@code{int8}/@code{int16}/@code{int32}/@code{int64}; @r{[}@code{unsigned}@r{]}
@code{short}/@code{int}/@code{long}; @code{size_t}/@code{ssize_t}/@code{ptrdiff_t}
@item inexact real
@code{scheme-object}; @code{bool}; @code{float}; @code{double}; @code{float32}; @code{float64}
@item string
@code{scheme-object}; @code{bool};
@code{char-string};
@code{nonnull-char-string};
@code{ISO-8859-1-string};
@code{nonnull-ISO-8859-1-string};
@code{UTF-8-string};
@code{nonnull-UTF-8-string};
@code{UTF-16-string};
@code{nonnull-UTF-16-string};
@code{UCS-2-string};
@code{nonnull-UCS-2-string};
@code{UCS-4-string};
@code{nonnull-UCS-4-string};
@code{wchar_t-string};
@code{nonnull-wchar_t-string}
@item foreign object
@code{scheme-object}; @code{bool}; @code{struct}/@code{union}/@code{type}/@code{pointer}/@code{nonnull-pointer} with the appropriate tags
@item vector
@code{scheme-object}; @code{bool}
@item symbol
@code{scheme-object}; @code{bool}
@item procedure
@code{scheme-object}; @code{bool};
@code{function};
@code{nonnull-function}
@item other objects
@code{scheme-object}; @code{bool}
@end table

The following table gives the Scheme types to which each C type
will be converted:

@table @asis
@item C type
Resulting Scheme type
@item scheme-object
the Scheme object encoded
@item bool
boolean
@item @r{[}@code{@r{[}un@r{]}signed}@r{]} @code{char}; @code{ISO-8859-1}; @code{UCS-2}; @code{UCS-4}; @code{wchar_t}
character
@item @r{[}@code{unsigned-}@r{]} @code{int8}/@code{int16}/@code{int32}/@code{int64}; @r{[}@code{unsigned}@r{]} @code{short}/@code{int}/@code{long}; @code{size_t}/@code{ssize_t}/@code{ptrdiff_t}
exact integer
@item @code{float}; @code{double}; @code{float32}; @code{float64}
inexact real
@item @code{char-string}; @code{ISO-8859-1-string}; @code{UTF-8-string}; @code{UTF-16-string}; @code{UCS-2-string}; @code{UCS-4-string}; @code{wchar_t-string}
string or @code{#f} if it is equal to @samp{NULL}
@item @code{nonnull-char-string}; @code{nonnull-ISO-8859-1-string}; @code{nonnull-UTF-8-string}; @code{nonnull-UTF-16-string}; @code{nonnull-UCS-2-string}; @code{nonnull-UCS-4-string}; @code{nonnull-wchar_t-string}
string
@item @code{struct}/@code{union}/@code{type}/@code{pointer}/@code{nonnull-pointer}
foreign object with the appropriate tags
or @code{#f} in the case of a @code{pointer} equal to @samp{NULL}
@item @code{function}
procedure or @code{#f} if it is equal to @samp{NULL}
@item @code{nonnull-function}
procedure
@item @code{void}
void object
@end table

All Scheme types are compatible with the C types @code{scheme-object}
and @code{bool}.  Conversion to and from the C type
@code{scheme-object} is the identity function on the object encoding.
This provides a low-level mechanism for accessing Scheme's object
representation from C (with the help of the macros in the
@samp{gambit.h} header file).  When a C @code{bool} type is expected,
an extended Scheme boolean can be passed (@code{#f} is converted to 0
and all other values are converted to 1).

The Scheme boolean @code{#f} can be passed to the C environment where
a @code{char-string}, @code{ISO-8859-1-string}, @code{UTF-8-string},
@code{UTF-16-string}, @code{UCS-2-string}, @code{UCS-4-string},
@code{wchar_t-string}, @code{pointer} or @code{function} type is
expected.  In this case, @code{#f} is converted to the @samp{NULL}
pointer.  C @code{bool}s are extended booleans so any value different
from 0 represents true.  Thus, a C @code{bool} passed to the Scheme
environment is mapped as follows: 0 to @code{#f} and all other values
to @code{#t}.

A Scheme character passed to the C environment where any C character
type is expected is converted to the corresponding character in the C
environment.  An error is signaled if the Scheme character does not fit
in the C character.  Any C character type passed to Scheme is converted
to the corresponding Scheme character.  An error is signaled if the C
character does not fit in the Scheme character.

A Scheme exact integer passed to the C environment where a C integer
type (other than @code{char}) is expected is converted to the
corresponding integral value.  An error is signaled if the value falls
outside of the range representable by that integral type.  C integer
values passed to the Scheme environment are mapped to the same Scheme
exact integer.  If the value is outside the fixnum range, a bignum is
created.

A Scheme inexact real passed to the C environment is converted to the
corresponding @code{float}, @code{double}, @code{float32} or
@code{float64} value.  C @code{float}, @code{double}, @code{float32} and
@code{float64} values passed to the Scheme environment are mapped to the
closest Scheme inexact real.

Scheme's rational numbers and complex numbers are not compatible with
any C numeric type.

A Scheme string passed to the C environment where any C string type is
expected is converted to a null terminated string using the appropriate
encoding.  The C string is a fresh copy of the Scheme string.  If the C
string was created for an argument of a @code{c-lambda}, the C string
will be reclaimed when the @code{c-lambda} returns.  If the C string was
created for returning the result of a @code{c-define} to C, the caller
is responsible for reclaiming the C string with a call to the
@code{___release_string} function (see below for an example).  Any C
string type passed to the Scheme environment causes the creation of a
fresh Scheme string containing a copy of the C string (unless the C
string is equal to @code{NULL}, in which case it is converted to
@code{#f}).

A foreign type passed to the Scheme environment causes the creation
and initialization of a Scheme foreign object with the appropriate
tags (except for the case of a @code{pointer} equal to @code{NULL}
which is converted to @code{#f}).  A Scheme foreign object can be
passed where a foreign type is expected, on the condition that the
tags are compatible and the Scheme foreign object is not yet released.
The value @code{#f} is also acceptable for a @code{pointer} type, and
is converted to @code{NULL}.

Scheme procedures defined with the @code{c-define} special form can be
passed where the @code{function} and @code{nonnull-function} types are
expected.  The value @code{#f} is also acceptable for a @code{function}
type, and is converted to @code{NULL}.  No other Scheme procedures are
acceptable.  Conversion from the @code{function} and
@code{nonnull-function} types to Scheme procedures is not currently
implemented.

@node c-declare, c-initialize, mapping of types, C-interface
@section The @code{c-declare} special form
@findex c-declare

@deffn {special form} c-declare @r{@i{c-declaration}}

Initially, the C file produced by @code{gsc} contains only an
@samp{#include} of @samp{gambit.h}.  This header file provides a
number of macro and procedure declarations to access the Scheme object
representation.  The special form @code{c-declare} adds
@i{c-declaration} (which must be a string containing the C
declarations) to the C file.  This string is copied to the C file on a
new line so it can start with preprocessor directives.  All types of C
declarations are allowed (including type declarations, variable
declarations, function declarations, @samp{#include} directives,
@samp{#define}s, and so on).  These declarations are visible to
subsequent @code{c-declare}s, @code{c-initialize}s, and
@code{c-lambda}s, and @code{c-define}s in the same module.  The most
common use of this special form is to declare the external functions
that are referenced in @code{c-lambda} special forms.  Such functions
must either be declared explicitly or by including a header file which
contains the appropriate C declarations.

The @code{c-declare} special form does not return a value.
It can only appear at top level.

For example:

@smallexample
@b{}(c-declare #<<c-declare-end

#include <stdio.h>

extern char *getlogin ();

#ifdef sparc
char *host = "sparc";
#else
char *host = "unknown";
#endif

FILE *tfile;

c-declare-end
)
@end smallexample

@end deffn

@node c-initialize, c-lambda, c-declare, C-interface
@section The @code{c-initialize} special form
@findex c-initialize

@deffn {special form} c-initialize @r{@i{c-code}}

Just after the program is loaded and before control is passed to the
Scheme code, each C file is initialized by calling its associated
initialization function.  The body of this function is normally empty
but it can be extended by using the @code{c-initialize} form.  Each
occurence of the @code{c-initialize} form adds code to the body of the
initialization function in the order of appearance in the source file.
@i{c-code} must be a string containing the C code to execute.  This
string is copied to the C file on a new line so it can start with
preprocessor directives.

The @code{c-initialize} special form does not return a value.
It can only appear at top level.

For example:

@smallexample
@b{}(c-initialize "tfile = tmpfile ();")
@end smallexample

@end deffn

@node c-lambda, c-define, c-initialize, C-interface
@section The @code{c-lambda} special form
@findex c-lambda

@deffn {special form} c-lambda (@r{@i{type1}}@dots{}) @r{@i{result-type}} @r{@i{c-name-or-code}}

The @code{c-lambda} special form makes it possible to create a Scheme
procedure that will act as a representative of some C function or C code
sequence.  The first subform is a list containing the type of each
argument.  The type of the function's result is given next.  Finally,
the last subform is a string that either contains the name of the C
function to call or some sequence of C code to execute.  Variadic C
functions are not supported.  The resulting Scheme procedure takes
exactly the number of arguments specified and delivers them in the same
order to the C function.  When the Scheme procedure is called, the
arguments will be converted to their C representation and then the C
function will be called.  The result returned by the C function will be
converted to its Scheme representation and this value will be returned
from the Scheme procedure call.  An error will be signaled if some
conversion is not possible.  The temporary memory allocated from the C
heap for the conversion of the arguments and result will be reclaimed
whether there is an error or not.

When @i{c-name-or-code} is not a valid C identifier, it is treated
as an arbitrary piece of C code.  Within the C code the variables
@samp{___arg1}, @samp{___arg2}, etc. can be referenced to access the
converted arguments.  Similarly, the result to be returned from the
call should be assigned to the variable @samp{___result} except when
the result is of type @code{struct}, @code{union}, @code{type},
@code{pointer}, @code{nonnull-pointer}, @code{function} or
@code{nonnull-function} in which case a pointer must be assigned to
the variable @samp{___result_voidstar} which is of type @samp{void*}.
For results of type @code{pointer}, @code{nonnull-pointer},
@code{function} and @code{nonnull-function}, the value assigned to the
variable @samp{___result_voidstar} must be the pointer or function
cast to @samp{void*}.  For results of type @code{struct},
@code{union}, and @code{type}, the value assigned to the variable
@samp{___result_voidstar} must be a pointer to a memory allocated
block containing a copy of the result.  Note that this block will be
reclaimed by the @var{release-function} associated with the type.
If no result needs to be returned, the @i{result-type} should be
@code{void} and no assignment to the variable @samp{___result} or
@samp{___result_voidstar} should take place.  Note that the C code
should not contain @code{return} statements as this is meaningless.
Control must always fall off the end of the C code.  The C code is
copied to the C file on a new line so it can start with preprocessor
directives.  Moreover the C code is always placed at the head of a
compound statement whose lifetime encloses the C to Scheme conversion of
the result.  Consequently, temporary storage (strings in particular)
declared at the head of the C code can be returned by assigning them to
@samp{___result} or @samp{___result_voidstar}.  In the
@i{c-name-or-code}, the macro @samp{___AT_END} may be defined as the
piece of C code to execute before control is returned to Scheme but
after the result is converted to its Scheme representation.  This is
mainly useful to deallocate temporary storage contained in the result.

When passed to the Scheme environment, the C @code{void} type is
converted to the void object.

For example:

@smallexample
@b{}(define fopen
  (c-lambda (nonnull-char-string nonnull-char-string)
            (pointer "FILE")
   "fopen"))

(define fgetc
  (c-lambda ((pointer "FILE"))
            int
   "fgetc"))

(let ((f (fopen "datafile" "r")))
  (if f (write (fgetc f))))

(define char-code
  (c-lambda (char) int "___result = ___arg1;"))

(define host
  ((c-lambda () nonnull-char-string "___result = host;")))

(define stdin
  ((c-lambda () (pointer "FILE") "___result_voidstar = stdin;")))

((c-lambda () void
#<<c-lambda-end
  printf( "hello\n" );
  printf( "world\n" );
c-lambda-end
))

(define pack-1-char
  (c-lambda (char)
            nonnull-char-string
#<<c-lambda-end
   ___result = malloc (2);
   if (___result != NULL) @{ ___result[0] = ___arg1; ___result[1] = 0; @}
   #define ___AT_END if (___result != NULL) free (___result);
c-lambda-end
))

(define pack-2-chars
  (c-lambda (char char)
            nonnull-char-string
#<<c-lambda-end
   char s[3];
   s[0] = ___arg1;
   s[1] = ___arg2;
   s[2] = 0;
   ___result = s;
c-lambda-end
))
@end smallexample

@end deffn

@node c-define, c-define-type, c-lambda, C-interface
@section The @code{c-define} special form
@findex c-define

@deffn {special form} c-define (@r{@i{variable}} @r{@i{define-formals}}) (@r{@i{type1}}@dots{}) @r{@i{result-type}} @r{@i{c-name}} @r{@i{scope}} @r{@i{body}}
  
The @code{c-define} special form makes it possible to create a C
function that will act as a representative of some Scheme procedure.  A
C function named @i{c-name} as well as a Scheme procedure bound to the
variable @i{variable} are defined.  The parameters of the Scheme
procedure are @i{define-formals} and its body is at the end of the
form.  The type of each argument of the C function, its result type and
@i{c-name} (which must be a string) are specified after the parameter
specification of the Scheme procedure.  When the C function @i{c-name}
is called from C, its arguments are converted to their Scheme
representation and passed to the Scheme procedure.  The result of the
Scheme procedure is then converted to its C representation and the C
function @i{c-name} returns it to its caller.

The scope of the C function can be changed with the @i{scope}
parameter, which must be a string.  This string is placed immediately
before the declaration of the C function.  So if @i{scope} is the
string @code{"static"}, the scope of @i{c-name} is local to the module
it is in, whereas if @i{scope} is the empty string, @i{c-name} is
visible from other modules.

The @code{c-define} special form does not return a value.
It can only appear at top level.

For example:

@smallexample
@b{}(c-define (proc x #!optional (y x) #!rest z) (int int char float) int "f" ""
  (write (cons x (cons y z)))
  (newline)
  (+ x y))

(proc 1 2 #\x 1.5) => 3 and prints (1 2 #\x 1.5)
(proc 1)           => 2 and prints (1 1)

; if f is called from C with the call  f (1, 2, 'x', 1.5)
; the value 3 is returned and (1 2 #\x 1.5) is printed.
; f has to be called with 4 arguments.
@end smallexample

@findex ___setup
@findex ___cleanup
The @code{c-define} special form is particularly useful when the
driving part of an application is written in C and Scheme procedures
are called directly from C.  The Scheme part of the application is in
a sense a ``server'' that is providing services to the C part.  The
Scheme procedures that are to be called from C need to be defined
using the @code{c-define} special form.  Before it can be used, the
Scheme part must be initialized with a call to the function
@samp{___setup}.  Before the program terminates, it must call the
function @samp{___cleanup} so that the Scheme part may do final
cleanup.  A sample application is given in the file
@samp{tests/server.scm}.

@end deffn

@node c-define-type, continuations, c-define, C-interface
@section The @code{c-define-type} special form
@findex c-define-type

@deffn {special form} c-define-type @r{@i{name}} @r{@i{type}} @r{[}@r{@i{c-to-scheme}} @r{@i{scheme-to-c}} @r{[}@r{@i{cleanup}}@r{]}@r{]}

This form associates the type identifier @i{name} to the C type
@i{type}.  The @i{name} must not clash with predefined types
(e.g. @code{char-string}, @code{ISO-8859-1}, etc.) or with types previously
defined with @code{c-define-type} in the same file.  The
@code{c-define-type} special form does not return a value.  It can only
appear at top level.

If only the two parameters @i{name} and @i{type} are supplied then
after this definition, the use of @i{name} in a type specification is
synonymous to @i{type}.

For example:

@smallexample
@b{}(c-define-type FILE "FILE")
(c-define-type FILE* (pointer FILE))
(c-define-type time-struct-ptr (pointer (struct "tms")))
(define fopen (c-lambda (char-string char-string) FILE* "fopen"))
(define fgetc (c-lambda (FILE*) int "fgetc"))
@end smallexample

Note that identifiers are not case-sensitive in standard Scheme but it
is good programming practice to use a @i{name} with the same case as
in C.

If four or more parameters are supplied, then @i{type} must be a
string naming the C type, @i{c-to-scheme} and @i{scheme-to-c} must
be strings suffixing the C macros that convert data of that type between
C and Scheme.  If @i{cleanup} is supplied it must be a boolean
indicating whether it is necessary to perform a cleanup operation (such
as freeing memory) when data of that type is converted from Scheme to C
(it defaults to @code{#t}).  The cleanup information is used when the C
stack is unwound due to a continuation invocation (see
@ref{continuations}).  Although it is safe to always specify @code{#t},
it is more efficient in time and space to specify @code{#f} because the
unwinding mechanism can skip C-interface frames which only contain
conversions of data types requiring no cleanup.  Two pairs of C macros
need to be defined for conversions performed by @code{c-lambda} forms
and two pairs for conversions performed by @code{c-define} forms:

@smallexample
@b{}___BEGIN_CFUN_@r{@i{scheme-to-c}}(___SCMOBJ, @r{@i{type}}, int)
___END_CFUN_@r{@i{scheme-to-c}}(___SCMOBJ, @r{@i{type}}, int)

___BEGIN_CFUN_@r{@i{c-to-scheme}}(@r{@i{type}}, ___SCMOBJ)
___END_CFUN_@r{@i{c-to-scheme}}(@r{@i{type}}, ___SCMOBJ)

___BEGIN_SFUN_@r{@i{c-to-scheme}}(@r{@i{type}}, ___SCMOBJ, int)
___END_SFUN_@r{@i{c-to-scheme}}(@r{@i{type}}, ___SCMOBJ, int)

___BEGIN_SFUN_@r{@i{scheme-to-c}}(___SCMOBJ, @r{@i{type}})
___END_SFUN_@r{@i{scheme-to-c}}(___SCMOBJ, @r{@i{type}})
@end smallexample

The macros prefixed with @code{___BEGIN} perform the conversion and
those prefixed with @code{___END} perform any cleanup necessary (such as
freeing memory temporarily allocated for the conversion).  The macro
@code{___END_CFUN_@r{@i{scheme-to-c}}} must free the result of the
conversion if it is memory allocated, and
@code{___END_SFUN_@r{@i{scheme-to-c}}} must not (i.e. it is the
responsibility of the caller to free the result).

The first parameter of these macros is the C variable that contains the
value to be converted, and the second parameter is the C variable in
which to store the converted value.  The third parameter, when present,
is the index (starting at 1) of the parameter of the @code{c-lambda} or
@code{c-define} form that is being converted (this is useful for
reporting precise error information when a conversion is impossible).

To allow for type checking, the first three @code{___BEGIN} macros must
expand to an unterminated compound statement prefixed by an @code{if},
conditional on the absence of type check error:

@smallexample
@b{}if ((___err = @var{conversion_operation}) == ___FIX(___NO_ERR)) @{
@end smallexample

The last @code{___BEGIN} macro must expand to an unterminated compound
statement:

@smallexample
@b{}@{ ___err = @var{conversion_operation};
@end smallexample

If type check errors are impossible then a @code{___BEGIN} macro can
simply expand to an unterminated compound statement performing the
conversion:

@smallexample
@b{}@{ @var{conversion_operation};
@end smallexample

The @code{___END} macros must expand to a statement, or to nothing if no
cleanup is required, followed by a closing brace (to terminate the
compound statement started at the corresponding @code{___BEGIN} macro).

The @var{conversion_operation} is typically a function call that returns
an error code value of type @code{___SCMOBJ} (the error codes are defined in
@samp{gambit.h}, and the error code @code{___FIX(___UNKNOWN_ERR)} is available
for generic errors).  @var{conversion_operation} can also set the
variable @code{___errmsg} of type @code{___SCMOBJ} to a specific Scheme
string error message.

Below is a simple example showing how to interface to an @samp{EBCDIC}
character type.  Memory allocation is not needed for conversion and type
check errors are impossible when converting EBCDIC to Scheme characters,
but they are possible when converting from Scheme characters to EBCDIC
since Gambit supports Unicode characters.

@smallexample
@b{}(c-declare #<<c-declare-end

typedef char EBCDIC; /* EBCDIC encoded characters */

void put_char (EBCDIC c) @{ ... @} /* EBCDIC I/O functions */
EBCDIC get_char (void) @{ ... @}

char EBCDIC_to_ISO_8859_1[256] = @{ ... @}; /* conversion tables */
char ISO_8859_1_to_EBCDIC[256] = @{ ... @};

___SCMOBJ SCMOBJ_to_EBCDIC (___SCMOBJ src, EBCDIC *dst)
@{
  int x = ___INT(src); /* convert from Scheme character to int */
  if (x > 255) return ___FIX(___UNKNOWN_ERR);
  *dst = ISO_8859_1_to_EBCDIC[x];
  return ___FIX(___NO_ERR);
@}

#define ___BEGIN_CFUN_SCMOBJ_to_EBCDIC(src,dst,i) \
if ((___err = SCMOBJ_to_EBCDIC (src, &dst)) == ___FIX(___NO_ERR)) @{
#define ___END_CFUN_SCMOBJ_to_EBCDIC(src,dst,i) @}

#define ___BEGIN_CFUN_EBCDIC_to_SCMOBJ(src,dst) \
@{ dst = ___CHR(EBCDIC_to_ISO_8859_1[src]);
#define ___END_CFUN_EBCDIC_to_SCMOBJ(src,dst) @}

#define ___BEGIN_SFUN_EBCDIC_to_SCMOBJ(src,dst,i) \
@{ dst = ___CHR(EBCDIC_to_ISO_8859_1[src]);
#define ___END_SFUN_EBCDIC_to_SCMOBJ(src,dst,i) @}

#define ___BEGIN_SFUN_SCMOBJ_to_EBCDIC(src,dst) \
@{ ___err = SCMOBJ_to_EBCDIC (src, &dst);
#define ___END_SFUN_SCMOBJ_to_EBCDIC(src,dst) @}

c-declare-end
)

(c-define-type EBCDIC "EBCDIC" "EBCDIC_to_SCMOBJ" "SCMOBJ_to_EBCDIC" #f)

(define put-char (c-lambda (EBCDIC) void "put_char"))
(define get-char (c-lambda () EBCDIC "get_char"))

(c-define (write-EBCDIC c) (EBCDIC) void "write_EBCDIC" ""
  (write-char c))

(c-define (read-EBCDIC) () EBCDIC "read_EBCDIC" ""
  (read-char))
@end smallexample

Below is a more complex example that requires memory allocation when
converting from C to Scheme.  It is an interface to a 2D @samp{point}
type which is represented in Scheme by a pair of integers. The
conversion of the @code{x} and @code{y} components is done by calls to
the conversion macros for the @code{int} type (defined in
@samp{gambit.h}).  Note that no cleanup is necessary when converting
from Scheme to C (i.e. the last parameter of the @code{c-define-type} is
@code{#f}).

@smallexample
@b{}(c-declare #<<c-declare-end

typedef struct @{ int x, y; @} point;

void line_to (point p) @{ ... @}
point get_mouse (void) @{ ... @}
point add_points (point p1, point p2) @{ ... @}

___SCMOBJ SCMOBJ_to_POINT (___PSD ___SCMOBJ src, point *dst, int arg_num)
@{
  ___SCMOBJ ___err = ___FIX(___NO_ERR);
  if (!___PAIRP(src))
    ___err = ___FIX(___UNKNOWN_ERR);
  else
    @{
      ___SCMOBJ car = ___CAR(src);
      ___SCMOBJ cdr = ___CDR(src);
      ___BEGIN_CFUN_SCMOBJ_TO_INT(car,dst->x,arg_num)
      ___BEGIN_CFUN_SCMOBJ_TO_INT(cdr,dst->y,arg_num)
      ___END_CFUN_SCMOBJ_TO_INT(cdr,dst->y,arg_num)
      ___END_CFUN_SCMOBJ_TO_INT(car,dst->x,arg_num)
    @}
  return ___err;
@}

___SCMOBJ POINT_to_SCMOBJ (___processor_state ___ps, point src, ___SCMOBJ *dst, int arg_num)
@{
  ___SCMOBJ ___err = ___FIX(___NO_ERR);
  ___SCMOBJ x_scmobj;
  ___SCMOBJ y_scmobj;
  ___BEGIN_SFUN_INT_TO_SCMOBJ(src.x,x_scmobj,arg_num)
  ___BEGIN_SFUN_INT_TO_SCMOBJ(src.y,y_scmobj,arg_num)
  *dst = ___EXT(___make_pair) (___ps, x_scmobj, y_scmobj);
  if (___FIXNUMP(*dst))
    ___err = *dst; /* return allocation error */
  ___END_SFUN_INT_TO_SCMOBJ(src.y,y_scmobj,arg_num)
  ___END_SFUN_INT_TO_SCMOBJ(src.x,x_scmobj,arg_num)
  return ___err;
@}

#define ___BEGIN_CFUN_SCMOBJ_to_POINT(src,dst,i) \
if ((___err = SCMOBJ_to_POINT (___PSP src, &dst, i)) == ___FIX(___NO_ERR)) @{
#define ___END_CFUN_SCMOBJ_to_POINT(src,dst,i) @}

#define ___BEGIN_CFUN_POINT_to_SCMOBJ(src,dst) \
if ((___err = POINT_to_SCMOBJ (___ps, src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) @{
#define ___END_CFUN_POINT_to_SCMOBJ(src,dst) \
___EXT(___release_scmobj) (dst); @}

#define ___BEGIN_SFUN_POINT_to_SCMOBJ(src,dst,i) \
if ((___err = POINT_to_SCMOBJ (___ps, src, &dst, i)) == ___FIX(___NO_ERR)) @{
#define ___END_SFUN_POINT_to_SCMOBJ(src,dst,i) \
___EXT(___release_scmobj) (dst); @}

#define ___BEGIN_SFUN_SCMOBJ_to_POINT(src,dst) \
@{ ___err = SCMOBJ_to_POINT (___PSP src, &dst, ___RETURN_POS);
#define ___END_SFUN_SCMOBJ_to_POINT(src,dst) @}

c-declare-end
)

(c-define-type point "point" "POINT_to_SCMOBJ" "SCMOBJ_to_POINT" #f)

(define line-to (c-lambda (point) void "line_to"))
(define get-mouse (c-lambda () point "get_mouse"))
(define add-points (c-lambda (point point) point "add_points"))

(c-define (write-point p) (point) void "write_point" ""
  (write p))

(c-define (read-point) () point "read_point" ""
  (read))
@end smallexample

Note that the pair is allocated using the @code{___make_pair} runtime
library function.  The prototype of this function is

@smallexample
@b{}___SCMOBJ ___make_pair(___processor_state ___ps, ___SCMOBJ car, ___SCMOBJ cdr);
@end smallexample

The fields of the pair are initialized to the @code{car} and
@code{cdr} parameters.  The @code{___ps} parameter indicates how the
pair is allocated.  A @code{NULL} @code{___ps} parameter will allocate
the pair permanently (i.e. the pair will only be deallocated when
@code{___cleanup} is called).  Otherwise a ``still'' object is
allocated and the @code{___ps} parameter indicates the processor in
whose heap the object is allocated (this is to support multithreaded
execution).  Still objects are reference counted and initially have a
reference count equal to 1.  The call to @code{___release_scmobj} in
the macros @code{___END_CFUN_POINT_to_SCMOBJ} and
@code{___END_SFUN_POINT_to_SCMOBJ} decrement this reference count.  A
still object whose reference count is zero will be deallocated when a
garbage collection is performed and there are no references to it from
the Scheme world.  Note that the use of the @code{___PSD} macro
in the parameter list of @code{SCMOBJ_to_POINT} and the @code{___PSP} macro
in the calls of @code{SCMOBJ_to_POINT}, are necessary to propagate the
current processor state to that function.

An example that requires memory allocation when converting from C to
Scheme and Scheme to C is shown below.  It is an interface to a
``null-terminated array of strings'' type which is represented in Scheme
by a list of strings.  Note that some cleanup is necessary when
converting from Scheme to C.

@smallexample
@b{}(c-declare #<<c-declare-end

#include <stdlib.h>
#include <unistd.h>

extern char **environ;

char **get_environ (void) @{ return environ; @}

void free_strings (char **strings)
@{
  char **ptr = strings;
  while (*ptr != NULL)
    @{
      ___EXT(___release_string) (*ptr);
      ptr++;
    @}
  free (strings);
@}

___SCMOBJ SCMOBJ_to_STRINGS (___PSD ___SCMOBJ src, char ***dst, int arg_num)
@{
  /*
   * Src is a list of Scheme strings.  Dst will be a null terminated
   * array of C strings.
   */

  int i;
  ___SCMOBJ lst = src;
  int len = 4; /* start with a small result array */
  char **result = (char**) malloc (len * sizeof (char*));

  if (result == NULL)
    return ___FIX(___HEAP_OVERFLOW_ERR);

  i = 0;
  result[i] = NULL; /* always keep array null terminated */

  while (___PAIRP(lst))
    @{
      ___SCMOBJ scm_str = ___CAR(lst);
      char *c_str;
      ___SCMOBJ ___err;

      if (i >= len-1) /* need to grow the result array? */
        @{
          char **new_result;
          int j;

          len = len * 3 / 2;
          new_result = (char**) malloc (len * sizeof (char*));
          if (new_result == NULL)
            @{
              free_strings (result);
              return ___FIX(___HEAP_OVERFLOW_ERR);
            @}
          for (j=i; j>=0; j--)
            new_result[j] = result[j];
          free (result);
          result = new_result;
        @}

      ___err = ___EXT(___SCMOBJ_to_CHARSTRING) (___PSP scm_str, &c_str, arg_num);

      if (___err != ___FIX(___NO_ERR))
        @{
          free_strings (result);
          return ___err;
        @}

      result[i++] = c_str;
      result[i] = NULL;
      lst = ___CDR(lst);
    @}

  if (!___NULLP(lst))
    @{
      free_strings (result);
      return ___FIX(___UNKNOWN_ERR);
    @}

  /*
   * Note that the caller is responsible for calling free_strings
   * when it is done with the result.
   */

  *dst = result;
  return ___FIX(___NO_ERR);
@}

___SCMOBJ STRINGS_to_SCMOBJ (___processor_state ___ps, char **src, ___SCMOBJ *dst, int arg_num)
@{
  ___SCMOBJ ___err = ___FIX(___NO_ERR);
  ___SCMOBJ result = ___NUL; /* start with the empty list */
  int i = 0;

  while (src[i] != NULL)
    i++;

  /* build the list of strings starting at the tail */

  while (--i >= 0)
    @{
      ___SCMOBJ scm_str;
      ___SCMOBJ new_result;

      /*
       * Invariant: result is either the empty list or a ___STILL pair
       * with reference count equal to 1.  This is important because
       * it is possible that ___CHARSTRING_to_SCMOBJ and ___make_pair
       * will invoke the garbage collector and we don't want the
       * reference in result to become invalid (which would be the
       * case if result was a ___MOVABLE pair or if it had a zero
       * reference count).
       */

      ___err = ___EXT(___CHARSTRING_to_SCMOBJ) (___ps, src[i], &scm_str, arg_num);

      if (___err != ___FIX(___NO_ERR))
        @{
          ___EXT(___release_scmobj) (result); /* allow GC to reclaim result */
          return ___FIX(___UNKNOWN_ERR);
        @}

      /*
       * Note that scm_str will be a ___STILL object with reference
       * count equal to 1, so there is no risk that it will be
       * reclaimed or moved if ___make_pair invokes the garbage
       * collector.
       */

      new_result = ___EXT(___make_pair) (___ps, scm_str, result);

      /*
       * We can zero the reference count of scm_str and result (if
       * not the empty list) because the pair now references these
       * objects and the pair is reachable (it can't be reclaimed
       * or moved by the garbage collector).
       */

      ___EXT(___release_scmobj) (scm_str);
      ___EXT(___release_scmobj) (result);

      result = new_result;

      if (___FIXNUMP(result))
        return result; /* allocation failed */
    @}

  /*
   * Note that result is either the empty list or a ___STILL pair
   * with a reference count equal to 1.  There will be a call to
   * ___release_scmobj later on (in ___END_CFUN_STRINGS_to_SCMOBJ
   * or ___END_SFUN_STRINGS_to_SCMOBJ) that will allow the garbage
   * collector to reclaim the whole list of strings when the Scheme
   * world no longer references it.
   */

  *dst = result;
  return ___FIX(___NO_ERR);
@}

#define ___BEGIN_CFUN_SCMOBJ_to_STRINGS(src,dst,i) \
if ((___err = SCMOBJ_to_STRINGS (___PSP src, &dst, i)) == ___FIX(___NO_ERR)) @{
#define ___END_CFUN_SCMOBJ_to_STRINGS(src,dst,i) \
free_strings (dst); @}

#define ___BEGIN_CFUN_STRINGS_to_SCMOBJ(src,dst) \
if ((___err = STRINGS_to_SCMOBJ (___ps, src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) @{
#define ___END_CFUN_STRINGS_to_SCMOBJ(src,dst) \
___EXT(___release_scmobj) (dst); @}

#define ___BEGIN_SFUN_STRINGS_to_SCMOBJ(src,dst,i) \
if ((___err = STRINGS_to_SCMOBJ (___ps, src, &dst, i)) == ___FIX(___NO_ERR)) @{
#define ___END_SFUN_STRINGS_to_SCMOBJ(src,dst,i) \
___EXT(___release_scmobj) (dst); @}

#define ___BEGIN_SFUN_SCMOBJ_to_STRINGS(src,dst) \
@{ ___err = SCMOBJ_to_STRINGS (___PSP src, &dst, ___RETURN_POS);
#define ___END_SFUN_SCMOBJ_to_STRINGS(src,dst) @}

c-declare-end
)

(c-define-type char** "char**" "STRINGS_to_SCMOBJ" "SCMOBJ_to_STRINGS" #t)

(define execv (c-lambda (char-string char**) int "execv"))
(define get-environ (c-lambda () char** "get_environ"))

(c-define (write-strings x) (char**) void "write_strings" ""
  (write x))

(c-define (read-strings) () char** "read_strings" ""
  (read))
@end smallexample

@end deffn

@node continuations, , c-define-type, C-interface
@section Continuations and the C-interface
@cindex continuations

The C-interface allows C to Scheme calls to be nested.  This means
that during a call from C to Scheme another call from C to Scheme
can be performed.  This case occurs in the following program:

@smallexample
@b{}(c-declare #<<c-declare-end

int p (char *); /* forward declarations */
int q (void);

int a (char *x) @{ return 2 * p (x+1); @}
int b (short y) @{ return y + q (); @}

c-declare-end
)

(define a (c-lambda (char-string) int "a"))
(define b (c-lambda (short) int "b"))

(c-define (p z) (char-string) int "p" ""
  (+ (b 10) (string-length z)))

(c-define (q) () int "q" ""
  123)

(write (a "hello"))
@end smallexample

In this example, the main Scheme program calls the C function @samp{a}
which calls the Scheme procedure @samp{p} which in turn calls the C
function @samp{b} which finally calls the Scheme procedure @samp{q}.

Gambit-C maintains the Scheme continuation separately from the C stack,
thus allowing the Scheme continuation to be unwound independently from
the C stack.  The C stack frame created for the C function @samp{f} is
only removed from the C stack when control returns from @samp{f} or when
control returns to a C function ``above'' @samp{f}.  Special care is
required for programs which escape to Scheme (using first-class
continuations) from a Scheme to C (to Scheme) call because the C stack
frame will remain on the stack.  The C stack may overflow if this
happens in a loop with no intervening return to a C function.  To avoid
this problem make sure the C stack gets cleaned up by executing a normal
return from a Scheme to C call.

@node System limitations, Copyright and license, C-interface, Top
@chapter System limitations
@cindex limitations

@itemize @bullet{}

@item
@cindex floating point overflow
@cindex overflow, floating point
On some systems floating point overflows will cause the program to
terminate with a floating point exception.

@item
On some systems floating point operations involving @samp{+nan.0}
@samp{+inf.0}, @samp{-inf.0}, or @samp{-0.} do not return the
value required by the IEEE 754 floating point standard.

@item
@findex define
@findex set!
The compiler will not properly compile files with more than one
definition (with @code{define}) of the same procedure.  Replace all
but the first @code{define} with assignments (@code{set!}).

@item
The maximum number of arguments that can be passed to a procedure by
the @code{apply} procedure is 8192.

@end itemize

@node Copyright and license, General index, System limitations, Top
@chapter Copyright and license

The Gambit-C system release @value{VERSION} is Copyright @copyright{}
1994-2009 by Marc Feeley, all rights reserved.  The Gambit-C system
release @value{VERSION} is licensed under two licenses: the Apache
License, Version 2.0, and the GNU LESSER GENERAL PUBLIC LICENSE,
Version 2.1.  You have the option to choose which of these two
licenses to abide by.  The licenses are copied below.

@page

@smallexample
@b{}
                              Apache License
                        Version 2.0, January 2004
                     http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

   "License" shall mean the terms and conditions for use, reproduction,
   and distribution as defined by Sections 1 through 9 of this document.

   "Licensor" shall mean the copyright owner or entity authorized by
   the copyright owner that is granting the License.

   "Legal Entity" shall mean the union of the acting entity and all
   other entities that control, are controlled by, or are under common
   control with that entity. For the purposes of this definition,
   "control" means (i) the power, direct or indirect, to cause the
   direction or management of such entity, whether by contract or
   otherwise, or (ii) ownership of fifty percent (50%) or more of the
   outstanding shares, or (iii) beneficial ownership of such entity.

   "You" (or "Your") shall mean an individual or Legal Entity
   exercising permissions granted by this License.

   "Source" form shall mean the preferred form for making modifications,
   including but not limited to software source code, documentation
   source, and configuration files.

   "Object" form shall mean any form resulting from mechanical
   transformation or translation of a Source form, including but
   not limited to compiled object code, generated documentation,
   and conversions to other media types.

   "Work" shall mean the work of authorship, whether in Source or
   Object form, made available under the License, as indicated by a
   copyright notice that is included in or attached to the work
   (an example is provided in the Appendix below).

   "Derivative Works" shall mean any work, whether in Source or Object
   form, that is based on (or derived from) the Work and for which the
   editorial revisions, annotations, elaborations, or other modifications
   represent, as a whole, an original work of authorship. For the purposes
   of this License, Derivative Works shall not include works that remain
   separable from, or merely link (or bind by name) to the interfaces of,
   the Work and Derivative Works thereof.

   "Contribution" shall mean any work of authorship, including
   the original version of the Work and any modifications or additions
   to that Work or Derivative Works thereof, that is intentionally
   submitted to Licensor for inclusion in the Work by the copyright owner
   or by an individual or Legal Entity authorized to submit on behalf of
   the copyright owner. For the purposes of this definition, "submitted"
   means any form of electronic, verbal, or written communication sent
   to the Licensor or its representatives, including but not limited to
   communication on electronic mailing lists, source code control systems,
   and issue tracking systems that are managed by, or on behalf of, the
   Licensor for the purpose of discussing and improving the Work, but
   excluding communication that is conspicuously marked or otherwise
   designated in writing by the copyright owner as "Not a Contribution."

   "Contributor" shall mean Licensor and any individual or Legal Entity
   on behalf of whom a Contribution has been received by Licensor and
   subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   copyright license to reproduce, prepare Derivative Works of,
   publicly display, publicly perform, sublicense, and distribute the
   Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   (except as stated in this section) patent license to make, have made,
   use, offer to sell, sell, import, and otherwise transfer the Work,
   where such license applies only to those patent claims licensable
   by such Contributor that are necessarily infringed by their
   Contribution(s) alone or by combination of their Contribution(s)
   with the Work to which such Contribution(s) was submitted. If You
   institute patent litigation against any entity (including a
   cross-claim or counterclaim in a lawsuit) alleging that the Work
   or a Contribution incorporated within the Work constitutes direct
   or contributory patent infringement, then any patent licenses
   granted to You under this License for that Work shall terminate
   as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
   Work or Derivative Works thereof in any medium, with or without
   modifications, and in Source or Object form, provided that You
   meet the following conditions:

   (a) You must give any other recipients of the Work or
       Derivative Works a copy of this License; and

   (b) You must cause any modified files to carry prominent notices
       stating that You changed the files; and

   (c) You must retain, in the Source form of any Derivative Works
       that You distribute, all copyright, patent, trademark, and
       attribution notices from the Source form of the Work,
       excluding those notices that do not pertain to any part of
       the Derivative Works; and

   (d) If the Work includes a "NOTICE" text file as part of its
       distribution, then any Derivative Works that You distribute must
       include a readable copy of the attribution notices contained
       within such NOTICE file, excluding those notices that do not
       pertain to any part of the Derivative Works, in at least one
       of the following places: within a NOTICE text file distributed
       as part of the Derivative Works; within the Source form or
       documentation, if provided along with the Derivative Works; or,
       within a display generated by the Derivative Works, if and
       wherever such third-party notices normally appear. The contents
       of the NOTICE file are for informational purposes only and
       do not modify the License. You may add Your own attribution
       notices within Derivative Works that You distribute, alongside
       or as an addendum to the NOTICE text from the Work, provided
       that such additional attribution notices cannot be construed
       as modifying the License.

   You may add Your own copyright statement to Your modifications and
   may provide additional or different license terms and conditions
   for use, reproduction, or distribution of Your modifications, or
   for any such Derivative Works as a whole, provided Your use,
   reproduction, and distribution of the Work otherwise complies with
   the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
   any Contribution intentionally submitted for inclusion in the Work
   by You to the Licensor shall be under the terms and conditions of
   this License, without any additional terms or conditions.
   Notwithstanding the above, nothing herein shall supersede or modify
   the terms of any separate license agreement you may have executed
   with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
   names, trademarks, service marks, or product names of the Licensor,
   except as required for reasonable and customary use in describing the
   origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
   agreed to in writing, Licensor provides the Work (and each
   Contributor provides its Contributions) on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   implied, including, without limitation, any warranties or conditions
   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
   PARTICULAR PURPOSE. You are solely responsible for determining the
   appropriateness of using or redistributing the Work and assume any
   risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
   whether in tort (including negligence), contract, or otherwise,
   unless required by applicable law (such as deliberate and grossly
   negligent acts) or agreed to in writing, shall any Contributor be
   liable to You for damages, including any direct, indirect, special,
   incidental, or consequential damages of any character arising as a
   result of this License or out of the use or inability to use the
   Work (including but not limited to damages for loss of goodwill,
   work stoppage, computer failure or malfunction, or any and all
   other commercial damages or losses), even if such Contributor
   has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
   the Work or Derivative Works thereof, You may choose to offer,
   and charge a fee for, acceptance of support, warranty, indemnity,
   or other liability obligations and/or rights consistent with this
   License. However, in accepting such obligations, You may act only
   on Your own behalf and on Your sole responsibility, not on behalf
   of any other Contributor, and only if You agree to indemnify,
   defend, and hold each Contributor harmless for any liability
   incurred by, or claims asserted against, such Contributor by reason
   of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

   To apply the Apache License to your work, attach the following
   boilerplate notice, with the fields enclosed by brackets "[]"
   replaced with your own identifying information. (Don't include
   the brackets!)  The text should be enclosed in the appropriate
   comment syntax for the file format. We also recommend that a
   file or class name and description of purpose be included on the
   same "printed page" as the copyright notice for easier
   identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@end smallexample

@page

@smallexample
@b{}                  GNU LESSER GENERAL PUBLIC LICENSE
                       Version 2.1, February 1999

 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
 as the successor of the GNU Library Public License, version 2, hence
 the version number 2.1.]

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.

  This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it.  You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.

  When we speak of free software, we are referring to freedom of use,
not price.  Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.

  To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights.  These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.

  For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you.  You must make sure that they, too, receive or can get the source
code.  If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it.  And you must show them these terms so they know their rights.

  We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.

  To protect each distributor, we want to make it very clear that
there is no warranty for the free library.  Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
@end smallexample

@page

@smallexample
@b{}  Finally, software patents pose a constant threat to the existence of
any free program.  We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder.  Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.

  Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License.  This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License.  We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.

  When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library.  The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom.  The Lesser General
Public License permits more lax criteria for linking other code with
the library.

  We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License.  It also provides other free software developers Less
of an advantage over competing non-free programs.  These disadvantages
are the reason we use the ordinary General Public License for many
libraries.  However, the Lesser license provides advantages in certain
special circumstances.

  For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard.  To achieve this, non-free programs must be
allowed to use the library.  A more frequent case is that a free
library does the same job as widely used non-free libraries.  In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.

  In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software.  For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.

  Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.

  The precise terms and conditions for copying, distribution and
modification follow.  Pay close attention to the difference between a
"work based on the library" and a "work that uses the library".  The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
@end smallexample

@page

@smallexample
@b{}                  GNU LESSER GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".

  A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.

  The "Library", below, refers to any such software library or work
which has been distributed under these terms.  A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language.  (Hereinafter, translation is
included without limitation in the term "modification".)

  "Source code" for a work means the preferred form of the work for
making modifications to it.  For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.

  Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it).  Whether that is true depends on what the Library does
and what the program that uses the Library does.
  
  1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.

  You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
@end smallexample

@page

@smallexample
@b{}  2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) The modified work must itself be a software library.

    b) You must cause the files modified to carry prominent notices
    stating that you changed the files and the date of any change.

    c) You must cause the whole of the work to be licensed at no
    charge to all third parties under the terms of this License.

    d) If a facility in the modified Library refers to a function or a
    table of data to be supplied by an application program that uses
    the facility, other than as an argument passed when the facility
    is invoked, then you must make a good faith effort to ensure that,
    in the event an application does not supply such function or
    table, the facility still operates, and performs whatever part of
    its purpose remains meaningful.

    (For example, a function in a library to compute square roots has
    a purpose that is entirely well-defined independent of the
    application.  Therefore, Subsection 2d requires that any
    application-supplied function or table used by this function must
    be optional: if the application does not supply it, the square
    root function must still compute square roots.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.

In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library.  To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License.  (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.)  Do not make any other change in
these notices.
@end smallexample

@page

@smallexample
@b{}  Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.

  This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.

  4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.

  If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.

  5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library".  Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.

  However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library".  The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.

  When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library.  The
threshold for this to be true is not precisely defined by law.

  If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work.  (Executables containing this object code plus portions of the
Library will still fall under Section 6.)

  Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
@end smallexample

@page

@smallexample
@b{}  6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.

  You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License.  You must supply a copy of this License.  If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License.  Also, you must do one
of these things:

    a) Accompany the work with the complete corresponding
    machine-readable source code for the Library including whatever
    changes were used in the work (which must be distributed under
    Sections 1 and 2 above); and, if the work is an executable linked
    with the Library, with the complete machine-readable "work that
    uses the Library", as object code and/or source code, so that the
    user can modify the Library and then relink to produce a modified
    executable containing the modified Library.  (It is understood
    that the user who changes the contents of definitions files in the
    Library will not necessarily be able to recompile the application
    to use the modified definitions.)

    b) Use a suitable shared library mechanism for linking with the
    Library.  A suitable mechanism is one that (1) uses at run time a
    copy of the library already present on the user's computer system,
    rather than copying library functions into the executable, and (2)
    will operate properly with a modified version of the library, if
    the user installs one, as long as the modified version is
    interface-compatible with the version that the work was made with.

    c) Accompany the work with a written offer, valid for at
    least three years, to give the same user the materials
    specified in Subsection 6a, above, for a charge no more
    than the cost of performing this distribution.

    d) If distribution of the work is made by offering access to copy
    from a designated place, offer equivalent access to copy the above
    specified materials from the same place.

    e) Verify that the user has already received a copy of these
    materials or that you have already sent this user a copy.

  For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it.  However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.

  It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system.  Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.

  7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:

    a) Accompany the combined library with a copy of the same work
    based on the Library, uncombined with any other library
    facilities.  This must be distributed under the terms of the
    Sections above.

    b) Give prominent notice with the combined library of the fact
    that part of it is a work based on the Library, and explaining
    where to find the accompanying uncombined form of the same work.

  8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License.  Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License.  However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.

  9. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Library or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.

  10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
@end smallexample

@page

@smallexample
@b{}  11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all.  For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.

If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded.  In such case, this License incorporates the limitation as if
written in the body of this License.

  13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number.  If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation.  If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
@end smallexample

@page

@smallexample
@b{}  14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission.  For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this.  Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.

                            NO WARRANTY

  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

                     END OF TERMS AND CONDITIONS
@end smallexample

@page

@smallexample
@b{}           How to Apply These Terms to Your New Libraries

  If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change.  You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).

  To apply these terms, attach the following notices to the library.  It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.

    <one line to give the library's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the
  library `Frob' (a library for tweaking knobs) written by James Random Hacker.

  <signature of Ty Coon>, 1 April 1990
  Ty Coon, President of Vice

That's all there is to it!
@end smallexample

@page

@node General index, , Copyright and license, Top
@unnumbered General index

@printindex cp
@contents

@bye

@c Local variables:
@c texinfo-column-for-description: 32
@c End:
