\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-2008 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-2008 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
@ifinfo
@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
* General index:: General index
--- The Detailed Node Listing ---
Gambit-C: a portable version of Gambit
* 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 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://gambit.iro.umontreal.ca}. 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{
}} command line option to
indicate where to find header files and a @code{-L@var{}} 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
This may have been done by the installation process. Alternatively
these files can be copied or linked in the directory where the C
compiler is invoked (this requires no special privileges).
@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
@node GSI, GSC, The Gambit-C system, Top
@chapter The Gambit Scheme interpreter
@cindex interpreter
Synopsis:
@example
@b{}gsi @r{[}-:@var{runtimeoption},@dots{}@r{]} @r{[}-i@r{]} @r{[}-f@r{]} @r{[}-v@r{]} @r{[}@r{[}-@r{]} @r{[}-e @var{expressions}@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 and time stamp on standard output and exits
(e.g. @code{@value{VERSION}} for Gambit @value{VERSION}). 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 completes the file name with a
@samp{.o@var{n}} extension with the highest consecutive version number
starting with 1, and loads that file as an object file. If that file
doesn't exist the file extensions @samp{.scm} and @samp{.six} will be
tried in that order. 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}. In addition to indicating that the file is a
script, the first 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 first 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 first 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 first 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 dynamically loadable object file or into a
standalone executable. The first line of the script will provide
information to the compiler on which language to use. The first line
also provides information on which runtime options to use when
executing the script. 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
(define (main arg)
(pretty-print (expt (string->number arg) 2)))
$ @b{gsi square 30 @r{@i{# will load square.scm}}}
900
$ @b{gsc square}
$ @b{gsi square 30 @r{@i{# will load square.o1}}}
900
@end smallexample
@node GSC, Runtime options, GSI, Top
@chapter The Gambit Scheme compiler
@cindex compiler
@cindex interpreter
Synopsis:
@example
@b{}gsc @r{[}-:@var{runtimeoption},@dots{}@r{]} @r{[}-i@r{]} @r{[}-f@r{]} @r{[}-v@r{]}
@r{[}-prelude @var{expressions}@r{]} @r{[}-postlude @var{expressions}@r{]}
@r{[}-dynamic@r{]} @r{[}-cc-options @var{options}@r{]}
@r{[}-ld-options-prelude @var{options}@r{]} @r{[}-ld-options @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 @var{output}@r{]} @r{[}-c@r{]} @r{[}-keep-c@r{]} @r{[}-link@r{]} @r{[}-flat@r{]} @r{[}-l @var{base}@r{]}
@r{[}@r{[}-@r{]} @r{[}-e @var{expressions}@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-c}, 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 @samp{.c} extension, or some other extension) on the
command line and compiles each Scheme file into a C file.
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 @samp{.c} extension must
have been previously produced by @code{gsc} 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
The linker is only invoked when the @samp{-link}
option appears 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 and time stamp 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 -keep-c
Keep the intermediate @samp{.c} file that is generated when
compiling to a dynamically loadable object file.
@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
The @samp{-debug} option causes debugging information to be saved in
the code generated. It is equivalent to the combination of the
@samp{-debug-location} option, the @samp{-debug-source} option and the
@samp{-debug-environments} option. Note that the debugging
information will substantially increase 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.
@opindex -debug-location
The @samp{-debug-location} option causes source code location
debugging information to be saved in the code generated. With this
option run time error messages indicate the location of the error in
the source code file. 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.
@opindex -debug-source
The @samp{-debug-source} option causes source code debugging
information to be saved in the code generated. With this option 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. 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.
@opindex -debug-environments
The @samp{-debug-environments} option causes environment debugging
information to be saved in the code generated. With this option 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. 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.
@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 -link
@opindex -keep-c
@flindex @var{last}_.c
If the @samp{-link} option appears 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. If
neither the @samp{-link} or @samp{-c} options appear on the command
line, the Scheme source files are compiled to dynamically loadable
object files (@samp{.o@var{n}} extension). When a dynamically
loadable object file is generated the @samp{-keep-c} option will
prevent the deletion of the 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} option also appears 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} option appears 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 call up
@code{gsc} to compile each Scheme module into a C file and 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< /dev/null}
m2:
m3:
$ @b{gcc -bundle -D___DYNAMIC m1.c m2.c m3.c foo.o1.c -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{gcc -shared -D___DYNAMIC m1.c m2.c m3.c foo.o1.c -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{gcc -fPIC -c -D___DYNAMIC mymod.o1.c m4.c m5.c x.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 #<
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{gcc -shared -fPIC -D___LIBRARY -D___SHARED m1.c m2.c mylib.c -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{gcc m3.c m3_.c 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-c @var{file} @r{[}@code{options:} @var{options}@r{]} @r{[}@code{output:} @var{output}@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}.
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}.
@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-c} 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 into an
object file by first generating a C file and then compiling it with
the C compiler. The C file is always generated in the same directory
as @var{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}. The name of
the generated 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}.
Object files can be loaded dynamically by using the @code{load}
procedure. The @samp{.o@var{n}} extension can be specified (to select
a particular version) or omitted (to load the highest numbered
version). When 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 this procedure is only available on host operating systems
that support dynamic loading.
@end deffn
@deffn procedure link-incremental @var{module-list} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{base:} @var{base}@r{]}
@pindex gsc
The first parameter must be a non empty list of strings naming Scheme
modules to link (extensions must 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. 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 the base link file is named @samp{@var{base}.c}.
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-c "h")}
#t
> @b{(compile-file-to-c "w")}
#t
> @b{(link-incremental '("h" "w") "hello.c")}
> @b{,q}
$ @b{gcc h.c w.c hello.c -lgambc -o hello}
$ @b{./hello}
hello
world
@end smallexample
@end deffn
@deffn procedure link-flat @var{module-list} @r{[}@code{output:} @var{output}@r{]}
@pindex gsc
The first parameter must be a non empty list of strings naming Scheme
modules to link. 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 (in all cases extensions must be omitted). 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 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-c "m6")}
#t
> @b{(compile-file-to-c "m7")}
#t
> @b{(link-flat '("m6" "m7") "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")
> @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 for all programs
@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
When a user interrupt occurs a new REPL will be started. User
interrupts are typically obtained by typing @key{^C}.
@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.
@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
@cindex GAMBCOPT, environment variable
When the environment variable @samp{GAMBCOPT} is defined, the runtime
system will take its options from that environment variable. A
@samp{-:} option can be used to override some or all of the
runtime system options. 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{,+}, @samp{,-} and
@samp{,@var{n}} commands (where @var{n} is the frame number).
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 ,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 ,+
@cmindex ,+
Move to the next frame 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 ,-
@cmindex ,-
Move to the previous frame in the chain of continuation frames (i.e.
towards more recently created 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 ,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
@samp{-debug} or @samp{-debug-location} options, and the last field is
missing when the frame was created by a compiled procedure not
compiled with the @samp{-debug} or @samp{-debug-source} options.
@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 @samp{-debug} or @samp{-debug-source}
options.
@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 @samp{-debug} or
@samp{-debug-environments} options. 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}}
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}
# =
(lambda (x) (/ 1 (expt x 2)))
1> @b{,e}
x = 'hello
1> @b{,b}
0 invsqr (console)@@1:25 (expt x 2)
1 # (console)@@6:17 (fn (car in))
2 # (console)@@6:31 (mm (cdr in))
3 # (console)@@6:31 (mm (cdr in))
4 (interaction) (console)@@8:1 (mymap invsqr '(5 2 hel...
1> @b{,+}
1 # (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}
#
1\1> @b{(pp fn)}
(lambda (x) (/ 1 (expt x 2)))
1\1> @b{,+}
2 # (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 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)}
(# # #)
> @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)}
(# #)
> @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 #, (console)@@2.47 -- Unbound variable: oops
1> @b{,b}
0 # (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 #, (console)@@6.47 -- Unbound variable: oops
1> @b{,b}
0 # (console)@@6:47 oops
1 # (console)@@6:32 (loop (* i 2))
2 # (console)@@6:32 (loop (* i 2))
3 # (console)@@6:32 (loop (* i 2))
4 # (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?}
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 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 @samp{-debug} or
@samp{-debug-source} options, 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 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-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-C-f @r{or @code{M-}@i{right-arrow}}
Move cursor right one S-expression.
@item C-p @r{or @i{up-arrow}}
Move to previous line in history.
@item C-n @r{or @i{down-arrow}}
Move to next line in history.
@item C-t
Transpose character at cursor with previous character.
@item M-C-t
Transpose S-expression at 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.
@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.
@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).
@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 make-uninterned-symbol @var{name} @r{[}@var{hash}@r{]}
@deffnx procedure uninterned-symbol? @var{obj}
The procedure @code{make-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{(make-uninterned-symbol "foo")}
#:foo:
> @b{(uninterned-symbol? (make-uninterned-symbol "foo"))}
#t
> @b{(uninterned-symbol? 'hello)}
#f
> @b{(uninterned-symbol? 123)}
#f
@end smallexample
@end deffn
@deffn procedure make-uninterned-keyword @var{name} @r{[}@var{hash}@r{]}
@deffnx procedure uninterned-keyword? @var{obj}
The procedure @code{make-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{(make-uninterned-keyword "foo")}
#:foo:
> @b{(uninterned-keyword? (make-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{]} 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 (@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)
(proper-tail-calls)
(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{}
@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 print @r{[}@code{port:} @var{port}@r{]} @var{obj}@dots{}
@deffnx procedure println @r{[}@code{port:} @var{port}@r{]} @var{obj}@dots{}
@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{thread-group} @r{[}@var{port}@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 process-pid @var{process-port}
@end deffn
@deffn procedure process-status @var{process-port} @r{[}@var{timeout} @r{[}@var{timeout-val}@r{]}@r{]}
@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}
@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 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{]}
@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 six.make-array @dots{}
@end deffn
@deffn procedure system-version
@deffnx procedure system-version-string
@end deffn
@deffn procedure system-type
@deffnx procedure system-type-string
@end deffn
@deffn procedure system-stamp
@end deffn
@deffn 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
@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)))}
(# (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} and @code{random-u8vector} 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 this number. 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 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}
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.
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
@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 s8vector-copy @var{s8vector}
@deffnx procedure s8vector-append @var{s8vector}@dots{}
@deffnx procedure subs8vector @var{s8vector} @var{start} @var{end}
@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 u8vector-copy @var{u8vector}
@deffnx procedure u8vector-append @var{u8vector}@dots{}
@deffnx procedure subu8vector @var{u8vector} @var{start} @var{end}
@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 s16vector-copy @var{s16vector}
@deffnx procedure s16vector-append @var{s16vector}@dots{}
@deffnx procedure subs16vector @var{s16vector} @var{start} @var{end}
@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 u16vector-copy @var{u16vector}
@deffnx procedure u16vector-append @var{u16vector}@dots{}
@deffnx procedure subu16vector @var{u16vector} @var{start} @var{end}
@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 s32vector-copy @var{s32vector}
@deffnx procedure s32vector-append @var{s32vector}@dots{}
@deffnx procedure subs32vector @var{s32vector} @var{start} @var{end}
@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 u32vector-copy @var{u32vector}
@deffnx procedure u32vector-append @var{u32vector}@dots{}
@deffnx procedure subu32vector @var{u32vector} @var{start} @var{end}
@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 s64vector-copy @var{s64vector}
@deffnx procedure s64vector-append @var{s64vector}@dots{}
@deffnx procedure subs64vector @var{s64vector} @var{start} @var{end}
@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 u64vector-copy @var{u64vector}
@deffnx procedure u64vector-append @var{u64vector}@dots{}
@deffnx procedure subu64vector @var{u64vector} @var{start} @var{end}
@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 f32vector-copy @var{f32vector}
@deffnx procedure f32vector-append @var{f32vector}@dots{}
@deffnx procedure subf32vector @var{f32vector} @var{start} @var{end}
@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 f64vector-copy @var{f64vector}
@deffnx procedure f64vector-append @var{f64vector}@dots{}
@deffnx procedure subf64vector @var{f64vector} @var{start} @var{end}
@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)
@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}
(# #)
> @b{(#3 10)}
1/10
> @b{'(#3 10)}
((serial-number->object 3) 10)
> @b{car}
#
> @b{(#4 z)}
#
@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)))}
(#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 '#
'(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 '#
'(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))))}
(# (#
(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}
#
> @b{(point-x p)}
3
> @b{(point-color p)}
red
> @b{(point-color-set! p 'black)}
> @b{p}
#
@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)}
#
> @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)))}
#
> @b{(make-root-thread (lambda () (write 'world)) '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)))}
(# (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)}
#
> @b{(make-mutex '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)}
#
@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)}
#
> @b{(current-exception-handler (lambda (exc) (pp exc) 999))}
> @b{(/ 1 0)}
#
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)))}
#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)))}
#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 '# 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"
#
("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 '())))}
#
@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)))}
#
@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")))}
(# ("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)))}
(# ("nofile" #))
@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")))}
(# ("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))))}
#
@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))))}
#
@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)))}
(# (# 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))))}
(# (#))
@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))))))))}
(# (#))
@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)))))))}
(#
(#)
#)
@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)))}
(#
(not-a-string)
"(Argument 1) Can't convert to C char-string"
#f)
> @b{(with-exception-catcher
handler
(lambda () (weird #f)))}
(#
(#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)}
(#
()
"(Argument 1) Can't convert from C nonnull-char-string"
#f)
> @b{(with-exception-catcher handler t3)}
(# () "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= #)
#
(exit k= 999)
#
@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{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)))}
(# (#(a b c) foo) 2 exact-integer)
> @b{(with-exception-catcher
handler
(lambda () (time->seconds 'foo)))}
(#seconds> (foo) 1 #)
@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)))}
(# ("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)))}
(# (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))))}
(# (# (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)))}
(# ("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))))}
(# 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)))}
(# (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)))}
(# (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}
The procedure @code{shell-command} calls up the shell to execute
@var{command} which must be a string. This procedure returns
the exit status of the shell in the form that the C library's
@code{system} routine returns.
For example under UNIX:
@smallexample
> @b{(shell-command "ls -sk f*.scm")}
4 fact.scm 4 fib.scm
0
@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)}
#