Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

16565 lines (13552 sloc) 594.046 kb
\input texinfo
@c %**start of header
@setfilename gambit-c.info
@settitle Gambit-C, a portable implementation of Scheme
@finalout
@c %**end of header
@include version.txi
@iftex
@tableindent=1.3in
@end iftex
@ifinfo
@format
START-INFO-DIR-ENTRY
* Gambit-C: (gambit-c). A portable implementation of Scheme.
* gsi: (gambit-c) interpreter. Gambit interpreter.
* gsc: (gambit-c) compiler. Gambit compiler.
END-INFO-DIR-ENTRY
@end format
@end ifinfo
@c Define new indices for commands, file names, and options.
@defcodeindex cm
@defcodeindex fl
@defcodeindex op
@c Put everything in one index (arbitrarily chosen to be the concept index).
@syncodeindex cm cp
@syncodeindex fl cp
@syncodeindex fn cp
@syncodeindex ky cp
@syncodeindex op cp
@syncodeindex pg cp
@syncodeindex vr cp
@ifinfo
This file documents Gambit-C, a portable implementation of Scheme.
Copyright (C) 1994-2009 Marc Feeley.
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).
@end ignore
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.
Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the copyright holder.
@end ifinfo
@titlepage
@title Gambit-C @value{VERSION}
@subtitle A portable implementation of Scheme
@subtitle Edition @value{EDITION}, @value{UPDATED}
@author Marc Feeley
@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1994-2009 Marc Feeley.
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.
Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the copyright holder.
@end titlepage
@ifnottex
@node Top, , (dir), (dir)
@top Gambit-C
@cindex Gambit-C
@cindex Scheme, implementation of
This manual documents Gambit-C. It covers release @value{VERSION}.
@menu
* The Gambit-C system:: The Gambit-C system
* Accessing the system files:: Accessing the system files
* GSI:: The Gambit Scheme interpreter
* GSC:: The Gambit Scheme compiler
* Runtime options:: Runtime options
* Debugging:: Debugging
* Scheme extensions:: Scheme extensions
* Namespaces:: Namespaces
* Characters and strings:: Characters and strings
* Numbers:: Numbers
* Homogeneous vectors:: Homogeneous vectors
* Hashing and weak references:: Hashing and weak references
* Records:: Records
* Threads:: Threads
* Dynamic environment:: Dynamic environment
* Exceptions:: Exceptions
* Host environment:: Host environment
* I/O and ports:: I/O and ports
* Lexical syntax and readtables:: Lexical syntax and readtables
* C-interface:: C-interface
* System limitations:: System limitations
* Copyright and license:: Copyright and license
* General index:: General index
@end menu
@end ifnottex
@node The Gambit-C system, GSI, Top, Top
@chapter The Gambit-C system
@cindex Gambit
@cindex Gambit-C
@cindex Scheme
@pindex gsi
@pindex gsc
The Gambit programming system is a full implementation of the Scheme
language which conforms to the R4RS, R5RS and IEEE Scheme standards. It
consists of two main programs: @code{gsi}, the Gambit Scheme
interpreter, and @code{gsc}, the Gambit Scheme compiler.
Gambit-C is a version of the Gambit programming system in which the
compiler generates portable C code, making the whole Gambit-C system and
the programs compiled with it easily portable to many computer
architectures for which a C compiler is available. With appropriate
declarations in the source code the executable programs generated by
the compiler run roughly as fast as equivalent C programs.
For the most up to date information on Gambit and add-on packages
please check the Gambit web page at
@uref{http://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{<dir>}} command line option to
indicate where to find header files and a @code{-L@var{<dir>}} command
line option to indicate where to find libraries.
Access to both of these files can be simplified by creating a link to
them in the appropriate system directories (special privileges may
however be required):
@smallexample
@b{}$ @b{ln -s /usr/local/Gambit-C/lib/libgambc.a /usr/lib} @r{@i{# name may vary}}
$ @b{ln -s /usr/local/Gambit-C/include/gambit.h /usr/include}
@end smallexample
Alternatively these files can be copied or linked in the directory
where the C compiler is invoked (this requires no special privileges).
Another approach is to set some environment variables which
are used to tell the C compiler where to find header files
and libraries. For example, the following settings can be
used for the @code{gcc} C compiler:
@smallexample
@b{}$ @b{export LIBRARY_PATH=/usr/local/Gambit-C/lib}
$ @b{export CPATH=/usr/local/Gambit-C/include}
@end smallexample
Note that this may have been done by the installation process. In
particular, the Mac OS X and Microsoft Windows prebuilt installers set
up the environment so that the @code{gcc} compiler finds these files
automatically.
@ifinfo
@menu
* GSI:: The Gambit Scheme interpreter
* GSC:: The Gambit Scheme compiler
* Runtime options:: Runtime options
* Debugging:: Debugging
* Scheme extensions:: Scheme extensions
* Namespaces:: Namespaces
* Characters and strings:: Characters and strings
* Numbers:: Numbers
* Homogeneous vectors:: Homogeneous vectors
* Hashing and weak references:: Hashing and weak references
* Records:: Records
* Threads:: Threads
* Dynamic environment:: Dynamic environment
* Exceptions:: Exceptions
* Host environment:: Host environment
* I/O and ports:: I/O and ports
* Lexical syntax and readtables:: Lexical syntax and readtables
* C-interface:: C-interface
* System limitations:: System limitations
* Copyright and license:: Copyright and license
@end menu
@end ifinfo
@node GSI, GSC, The Gambit-C system, Top
@chapter The Gambit Scheme interpreter
@cindex interpreter
Synopsis:
@example
@b{}gsi @r{[}-:@r{@var{runtimeoption}},@dots{}@r{]} @r{[}-i@r{]} @r{[}-f@r{]} @r{[}-v@r{]} @r{[}@r{[}-@r{]} @r{[}-e @r{@var{expressions}}@r{]} @r{[}@r{@var{file}}@r{]}@r{]}@dots{}
@end example
@pindex gsi
The interpreter is executed in @dfn{interactive mode} when no file or
@samp{-} or @samp{-e} option is given on the command line. Otherwise
the interpreter is executed in @dfn{batch mode}. The @samp{-i} option
is ignored by the interpreter. The initialization file will be
examined unless the @samp{-f} option is present (@pxref{GSI
customization}). The @samp{-v} option prints the system version
string, system time stamp, operating system type, and configure script
options on standard output and exits. Runtime options are explained
in @ref{Runtime options}.
@menu
* GSI interactive mode:: Interactive mode
* GSI batch mode:: Batch mode
* GSI customization:: Customization
* GSI exit status:: Process exit status
* Scheme scripts:: Scheme scripts
@end menu
@node GSI interactive mode, GSI batch mode, GSI, GSI
@section Interactive mode
In interactive mode a read-eval-print loop (REPL) is started for the
user to interact with the interpreter. At each iteration of this loop
the interpreter displays a prompt, reads a command and executes it.
The commands can be expressions to evaluate (the typical case)
or special commands related to debugging, for example @samp{,q} to
terminate the process (for a complete list of commands see
@ref{Debugging}). Most commands produce some output, such as the
value or error message resulting from an evaluation.
The input and output of the interaction is done on the
@dfn{interaction channel}. The interaction channel can be specified
through the runtime options but if none is specified the system uses a
reasonable default that depends on the system's configuration. When
the system's runtime library was built with support for GUIDE, the
Gambit Universal IDE (with the command @samp{configure
--enable-guide}) the interaction channel corresponds to the
@dfn{console window} of the primordial thread (for details see
@ref{GUIDE}), otherwise the interaction channel is the user's
@dfn{console}, also known as the @dfn{controlling terminal} in the
UNIX world. When the REPL starts, the ports associated with
@samp{(current-input-port)}, @samp{(current-output-port)} and
@samp{(current-error-port)} all refer to the interaction channel.
Expressions are evaluated in the global @dfn{interaction environment}.
The interpreter adds to this environment any definition entered using
the @code{define} and @code{define-macro}
special forms. Once the evaluation of an expression is completed, the
value or values resulting from the evaluation are output to the
interaction channel by the pretty printer. The special ``void''
object is not output. This object is returned by most procedures and
special forms which the Scheme standard defines as returning an
unspecified value (e.g. @code{write}, @code{set!}, @code{define}).
Here is a sample interaction with @code{gsi}:
@smallexample
$ @b{gsi}
Gambit @value{VERSION}
> @b{(define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))}
> @b{(map fact '(1 2 3 4 5 6))}
(1 2 6 24 120 720)
> @b{(values (fact 10) (fact 40))}
3628800
815915283247897734345611269596115894272000000000
> @b{,q}
@end smallexample
What happens when errors occur is explained in @ref{Debugging}.
@node GSI batch mode, GSI customization, GSI interactive mode, GSI
@section Batch mode
In batch mode the command line arguments denote files to be loaded,
REPL interactions to start (@samp{-} option), and expressions to be
evaluated (@samp{-e} option). Note that the @samp{-} and @samp{-e}
options can be interspersed with the files on the command line and can
occur multiple times. The interpreter processes the command line
arguments from left to right, loading files with the @code{load}
procedure and evaluating expressions with the @code{eval} procedure in
the global interaction environment. After this processing the
interpreter exits.
When the file name has no extension the @code{load} procedure first
attempts to load the file with no extension as a Scheme source file.
If that file doesn't exist it will search for both a source file and
an object file. The object file's name is obtained by adding to the
file name a @samp{.o@var{n}} extension with the highest consecutive
version number starting with 1. The source file's name is obtained by
adding to the file name the file extensions @samp{.scm} and
@samp{.six} (the first found is the source file). If both a source
file and an object file exist, then the one with the latest
modification time is loaded. Otherwise the file that is found is
loaded. When the file name has an extension, the @code{load}
procedure will only attempt to load the file with that specific name.
When the extension of the file loaded is @samp{.scm} the content of
the file will be parsed using the normal Scheme prefix syntax. When
the extension of the file loaded is @samp{.six} the content of the
file will be parsed using the Scheme infix syntax extension (see
@ref{Scheme infix syntax extension}). Otherwise, @code{gsi} will
parse the file using the normal Scheme prefix syntax.
The ports associated with @samp{(current-input-port)},
@samp{(current-output-port)} and @samp{(current-error-port)} initially
refer respectively to the standard input (@samp{stdin}), standard
output (@samp{stdout}) and the standard error (@samp{stderr}) of the
interpreter. This is true even in REPLs started with the @samp{-}
option. The usual interaction channel (console or IDE's console
window) is still used to read expressions and commands and to display
results. This makes it possible to use REPLs to debug programs which
read the standard input and write to the standard output, even when
these have been redirected.
Here is a sample use of the interpreter in batch mode, under UNIX:
@smallexample
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{cat w.six}
display("world"); newline();
$ @b{gsi h.scm - w.six -e "(pretty-print 1)(pretty-print 2)"}
hello
> @b{(define (display x) (write (reverse (string->list x))))}
> @b{,(c 0)}
(#\d #\l #\r #\o #\w)
1
2
@end smallexample
@node GSI customization, GSI exit status, GSI batch mode, GSI
@section Customization
There are two ways to customize the interpreter. When the interpreter
starts off it tries to execute a @samp{(load "~~lib/gambcext")} (for an
explanation of how file names are interpreted see @ref{Host environment}).
An error is not signaled when the file does not exist. Interpreter
extensions and patches that are meant to apply to all users and all
modes should go in that file.
Extensions which are meant to apply to a single user or to a specific
working directory are best placed in the @dfn{initialization file},
which is a file containing Scheme code. In all modes, the interpreter
first tries to locate the initialization file by searching the following
locations: @file{.gambcini} and @file{~/.gambcini} (with no extension, a
@samp{.scm} extension, and a @samp{.six} extension in that order). The
first file that is found is examined as though the expression
@code{(include @var{initialization-file})} had been entered at the
read-eval-print loop where @var{initialization-file} is the file that
was found. Note that by using an @code{include} the macros defined in
the initialization file will be visible from the read-eval-print loop
(this would not have been the case if @code{load} had been used). The
initialization file is not searched for or examined when the @samp{-f}
option is specified.
@node GSI exit status, Scheme scripts, GSI customization, GSI
@section Process exit status
The status is zero when the interpreter exits normally and is nonzero
when the interpreter exits due to an error. Here is the meaning of
the exit statuses:
@table @code
@item 0
The execution of the primordial thread (i.e. the main thread) did not
encounter any error. It is however possible that other threads
terminated abnormally (by default threads other than the primordial
thread terminate silently when they raise an exception that is not
handled).
@item 64
The runtime options or the environment variable @samp{GAMBCOPT}
contained a syntax error or were invalid.
@item 70
This normally indicates that an exception was raised in the primordial
thread and the exception was not handled.
@item 71
There was a problem initializing the runtime system, for example
insufficient memory to allocate critical tables.
@end table
For example, if the shell is @code{sh}:
@smallexample
$ @b{gsi -:d0 -e "(pretty-print (expt 2 100))"}
1267650600228229401496703205376
$ @b{echo $?}
0
$ @b{gsi -:d0,unknown @r{@i{# try to use an unknown runtime option}}}
$ @b{echo $?}
64
$ @b{gsi -:d0 nonexistent.scm @r{@i{# try to load a file that does not exist}}}
$ @b{echo $?}
70
$ @b{gsi nonexistent.scm}
*** ERROR IN ##main -- No such file or directory
(load "nonexistent.scm")
$ @b{echo $?}
70
@end smallexample
@smallexample
@b{}$ @b{gsi -:m4000000 @r{@i{# ask for a 4 gigabyte heap}}}
*** malloc: vm_allocate(size=528384) failed (error code=3)
*** malloc[15068]: error: Can't allocate region
$ @b{echo $?}
71
@end smallexample
Note the use of the runtime option @samp{-:d0} that prevents error
messages from being output, and the runtime option @samp{-:m4000000}
which sets the minimum heap size to 4 gigabytes.
@node Scheme scripts, , GSI exit status, GSI
@section Scheme scripts
The @code{load} procedure treats specially files that begin with the
two characters @samp{#!} and @samp{@@;}. Such files are called
@dfn{script files} and the first line is called the @dfn{script line}.
In addition to indicating that the file is a script, the script line
provides information about the source code language to be used by the
@code{load} procedure. After the two characters @samp{#!} and
@samp{@@;} the system will search for the first substring matching one
of the following language specifying tokens:
@table @code
@item scheme-r4rs
@pindex scheme-r4rs
R4RS language with prefix syntax, case-insensitivity, keyword syntax
not supported
@item scheme-r5rs
@pindex scheme-r5rs
R5RS language with prefix syntax, case-insensitivity, keyword syntax
not supported
@item scheme-ieee-1178-1990
@pindex scheme-ieee-1178-1990
IEEE 1178-1990 language with prefix syntax, case-insensitivity, keyword
syntax not supported
@item scheme-srfi-0
@pindex scheme-srfi-0
R5RS language with prefix syntax and SRFI 0 support
(i.e. @code{cond-expand} special form), case-insensitivity, keyword
syntax not supported
@item gsi-script
@pindex gsi-script
Full Gambit Scheme language with prefix syntax, case-sensitivity, keyword
syntax supported
@item gsc-script
@pindex gsc-script
Full Gambit Scheme language with prefix syntax, case-sensitivity, keyword
syntax supported
@item six-script
@pindex six-script
Full Gambit Scheme language with infix syntax, case-sensitivity, keyword
syntax supported
@end table
If a language specifying token is not found, @code{load} will use the
same language as a nonscript file (i.e. it uses the file extension and
runtime system options to determine the language).
After processing the script line, @code{load} will parse the rest of
the file (using the syntax of the language indicated) and then execute
it. When the file is being loaded because it is an argument on the
interpreter's command line, the interpreter will:
@itemize @bullet{}
@item
@findex command-line
Setup the @code{command-line} procedure so that it returns a list
containing the expanded file name of the script file and the
arguments following the script file on the command line.
This is done before the script is executed. The expanded file name
of the script file can be used to determine the directory that
contains the script (i.e. @code{(path-directory (car (command-line)))}).
@item
After the script is loaded the procedure @code{main} is called with
the command-line arguments. The way this is done depends on the
language specifying token. For @code{scheme-r4rs},
@code{scheme-r5rs}, @code{scheme-ieee-1178-1990}, and
@code{scheme-srfi-0}, the @code{main} procedure is called with the
equivalent of @code{(main (cdr (command-line)))} and @code{main} is
expected to return a process exit status code in the range 0 to 255.
This conforms to the ``Running Scheme Scripts on Unix SRFI'' (SRFI
22). For @code{gsi-script} and @code{six-script} the @code{main}
procedure is called with the equivalent of @code{(apply main (cdr
(command-line)))} and the process exit status code is 0 (@code{main}'s
result is ignored). The Gambit-C system has a predefined @code{main}
procedure which accepts any number of arguments and returns 0, so it
is perfectly valid for a script to not define @code{main} and to do
all its processing with top-level expressions (examples are given in
the next section).
@item
When @code{main} returns, the interpreter exits. The command-line
arguments after a script file are consequently not processed (however
they do appear in the list returned by the @code{command-line}
procedure, after the script file's expanded file name, so it is up to
the script to process them).
@end itemize
@menu
* Scripts under UNIX and Mac OS X:: Scripts under UNIX and Mac OS X
* Scripts under Microsoft Windows:: Scripts under Microsoft Windows
* Compiling scripts:: Compiling scripts
@end menu
@node Scripts under UNIX and Mac OS X, Scripts under Microsoft Windows, Scheme scripts, Scheme scripts
@subsection Scripts under UNIX and Mac OS X
Under UNIX and Mac OS X, the Gambit-C installation process creates the
executable @samp{gsi} and also the executables @samp{six},
@samp{gsi-script}, @samp{six-script}, @samp{scheme-r5rs},
@samp{scheme-srfi-0}, etc as links to @samp{gsi}. A Scheme script
need only start with the name of the desired Scheme language variant
prefixed with @samp{#!} and the directory where the Gambit-C
executables are stored. This script should be made executable by
setting the execute permission bits (with a @samp{chmod +x
@var{script}}). Here is an example of a script which lists on standard
output the files in the current directory:
@smallexample
@b{}#!/usr/local/Gambit-C/bin/gsi-script
(for-each pretty-print (directory-files))
@end smallexample
Here is another UNIX script, using the Scheme infix syntax extension,
which takes a single integer argument and prints on standard output the
numbers from 1 to that integer:
@smallexample
@b{}#!/usr/local/Gambit-C/bin/six-script
void main (obj n_str)
@{
int n = \string->number(n_str);
for (int i=1; i<=n; i++)
\pretty-print(i);
@}
@end smallexample
For maximal portability it is a good idea to start scripts indirectly
through the @samp{/usr/bin/env} program, so that the executable of the
interpreter will be searched in the user's @samp{PATH}. This is what
SRFI 22 recommends. For example here is a script that mimics the UNIX
@samp{cat} utility for text files:
@smallexample
@b{}#!/usr/bin/env gsi-script
(define (display-file filename)
(display (call-with-input-file filename
(lambda (port)
(read-line port #f)))))
(for-each display-file (cdr (command-line)))
@end smallexample
@node Scripts under Microsoft Windows, Compiling scripts, Scripts under UNIX and Mac OS X, Scheme scripts
@subsection Scripts under Microsoft Windows
Under Microsoft Windows, the Gambit-C installation process creates the
executable @samp{gsi.exe} and @samp{six.exe} and also the batch files
@samp{gsi-script.bat}, @samp{six-script.bat}, @samp{scheme-r5rs.bat},
@samp{scheme-srfi-0.bat}, etc which simply invoke @samp{gsi.exe} with
the same command line arguments. A Scheme script need only start with
the name of the desired Scheme language variant prefixed with
@samp{@@;}. A UNIX script can be converted to a Microsoft Windows
script simply by changing the script line and storing the script in a
file whose name has a @samp{.bat} or @samp{.cmd} extension:
@smallexample
@b{}@@;gsi-script %~f0 %*
(display "files:\n")
(pretty-print (directory-files))
@end smallexample
Note that Microsoft Windows always searches executables in the user's
@samp{PATH}, so there is no need for an indirection such as the UNIX
@samp{/usr/bin/env}. However the script line must end with @samp{%~f0
%*} to pass the expanded filename of the script and command line
arguments to the interpreter.
@node Compiling scripts, , Scripts under Microsoft Windows, Scheme scripts
@subsection Compiling scripts
A script file can be compiled using the Gambit Scheme compiler
(@pxref{GSC}) into a standalone executable. The script line will
provide information to the compiler on which language to use. The
script line also provides information on which runtime options to use
when executing the compiled script. This is useful to set the default
runtime options of an executable program.
The compiled script will be executed similarly to an interpreted
script (i.e. the list of command line arguments returned by the
@code{command-line} procedure and the invocation of the @code{main}
procedure).
For example:
@smallexample
$ @b{cat square.scm}
#!/usr/local/Gambit-C/bin/gsi-script -:d0
(define (main arg)
(pretty-print (expt (string->number arg) 2)))
$ @b{gsi square 30 @r{@i{# gsi will load square.scm}}}
900
$ @b{gsc -exe square @r{@i{# compile the script to a standalone program}}}
$ @b{./square 30}
900
$ @b{./square 1 2 3 @r{@i{# too many arguments to main}}}
$ @b{echo $?}
70
$ @b{./square -:d1 1 2 3 @r{@i{# ask for error message}}}
*** ERROR -- Wrong number of arguments passed to procedure
(main "1" "2" "3")
@end smallexample
@node GSC, Runtime options, GSI, Top
@chapter The Gambit Scheme compiler
@cindex compiler
@cindex interpreter
Synopsis:
@example
@b{}gsc @r{[}-:@r{@var{runtimeoption}},@dots{}@r{]} @r{[}-i@r{]} @r{[}-f@r{]} @r{[}-v@r{]}
@r{[}-prelude @r{@var{expressions}}@r{]} @r{[}-postlude @r{@var{expressions}}@r{]}
@r{[}-dynamic@r{]} @r{[}-exe@r{]} @r{[}-obj@r{]} @r{[}-cc-options @r{@var{options}}@r{]}
@r{[}-ld-options-prelude @r{@var{options}}@r{]} @r{[}-ld-options @r{@var{options}}@r{]}
@r{[}-warnings@r{]} @r{[}-verbose@r{]} @r{[}-report@r{]} @r{[}-expansion@r{]} @r{[}-gvm@r{]}
@r{[}-debug@r{]} @r{[}-debug-location@r{]} @r{[}-debug-source@r{]}
@r{[}-debug-environments@r{]} @r{[}-track-scheme@r{]}
@r{[}-o @r{@var{output}}@r{]} @r{[}-c@r{]} @r{[}-keep-c@r{]} @r{[}-link@r{]} @r{[}-flat@r{]} @r{[}-l @r{@var{base}}@r{]}
@r{[}@r{[}-@r{]} @r{[}-e @r{@var{expressions}}@r{]} @r{[}@r{@var{file}}@r{]}@r{]}@dots{}
@end example
@menu
* GSC interactive mode:: Interactive mode
* GSC customization:: Customization
* GSC batch mode:: Batch mode
* Link files:: Link files
* Procedures specific to compiler:: Procedures specific to compiler
@end menu
@node GSC interactive mode, GSC customization, GSC, GSC
@section Interactive mode
When no command line argument is present other than options the
compiler behaves like the interpreter in interactive mode. The only
difference with the interpreter is that the compilation related
procedures listed in this chapter are also available
(i.e. @code{compile-file}, @code{compile-file-to-target}, etc).
@node GSC customization, GSC batch mode, GSC interactive mode, GSC
@section Customization
Like the interpreter, the compiler will examine the initialization
file unless the @samp{-f} option is specified.
@node GSC batch mode, Link files, GSC customization, GSC
@section Batch mode
@pindex gsc
@flindex .scm
@flindex .six
@flindex .c
@flindex @var{file}.scm
@flindex @var{file}.six
@flindex @var{file}.c
In batch mode @code{gsc} takes a set of file names (with either no
extension, or a C file extension, or some other extension) on the
command line and compiles each Scheme file into a C file.
The recognized C file extensions are @samp{.c}, @samp{.C}, @samp{.cc},
@samp{.cp}, @samp{.cpp}, @samp{.CPP}, @samp{.cxx}, @samp{.c++},
@samp{.m}, @samp{.M}, and @samp{.mm}.
The extension can be omitted from @var{file} when the Scheme file has a
@samp{.scm} or @samp{.six} extension. When the extension of the
Scheme file is @samp{.six} the content of the file will be parsed
using the Scheme infix syntax extension (see @ref{Scheme infix syntax
extension}). Otherwise, @code{gsc} will parse the Scheme file using the
normal Scheme prefix syntax. Files with a C file extension must
have been previously produced by @code{gsc}, with the @samp{-c} option,
and are used by Gambit's linker.
For each Scheme file a C file @samp{@var{file}.c} will be produced.
The C file's name is the same as the Scheme file, but the extension is
changed to @samp{.c}. By default the C file is created in the same
directory as the Scheme file. This default can be overridden with the
compiler's @samp{-o} option.
The C files produced by the compiler serve two purposes. They will be
processed by a C compiler to generate object files, and they also
contain information to be read by Gambit's linker to generate a
@dfn{link file}. The link file is a C file that collects various
linking information for a group of modules, such as the set of all
symbols and global variables used by the modules.
@opindex -link
@opindex -exe
The linker is only invoked when the @samp{-link} or @samp{-exe}
options appear on the command line.
Compiler options must be specified before the first file name and
after the @samp{-:} runtime option (@pxref{Runtime options}). If
present, the @samp{-i}, @samp{-f}, and @samp{-v} compiler options
must come first. The available options are:
@cindex compiler options
@cindex options, compiler
@table @code
@item -i
Force interpreter mode.
@item -f
Do not examine the initialization file.
@item -v
Print the system version string, system time stamp, operating system
type, and configure script options on standard output and exit.
@item -prelude @var{expressions}
Add expressions to the top of the source code being compiled.
@item -postlude @var{expressions}
Add expressions to the bottom of the source code being compiled.
@item -cc-options @var{options}
Add options to the command that invokes the C compiler.
@item -ld-options-prelude @var{options}
Add options to the command that invokes the C linker.
@item -ld-options @var{options}
Add options to the command that invokes the C linker.
@item -warnings
Display warnings.
@item -verbose
Display a trace of the compiler's activity.
@item -report
Display a global variable usage report.
@item -expansion
Display the source code after expansion.
@item -gvm
Generate a listing of the GVM code.
@item -debug
Include all debugging information in the code generated.
@item -debug-location
Include source code location debugging information in the code generated.
@item -debug-source
Include the source code debugging information in the code generated.
@item -debug-environments
Include environment debugging information in the code generated.
@item -track-scheme
Generate @samp{#line} directives referring back to the Scheme code.
@item -o @var{output}
Set name of output file or directory where output file(s) are written.
@item -dynamic
Compile Scheme source files to dynamically loadable object
files (this is the default).
@item -exe
Compile Scheme source files into an executable program.
@item -obj
Compile Scheme source files to object files.
@item -keep-c
Keep any intermediate @samp{.c} files that are generated.
@item -c
Compile Scheme source files to C without generating link file.
@item -link
Compile Scheme source files to C and generate a link file.
@item -flat
Generate a flat link file instead of the default incremental link file.
@item -l @var{base}
Specify the link file of the base library to use for the link.
@item -
Start REPL interaction.
@item -e @var{expressions}
Evaluate expressions in the interaction environment.
@end table
@opindex -i
The @samp{-i} option forces the compiler to process the remaining
command line arguments like the interpreter.
@opindex -prelude
The @samp{-prelude} option adds the specified expressions to the top of
the source code being compiled. The main use of this option is to
supply declarations on the command line. For example the following
invocation of the compiler will compile the file @samp{bench.scm} in
unsafe mode:
@smallexample
$ @b{gsc -prelude "(declare (not safe))" bench.scm}
@end smallexample
@opindex -postlude
The @samp{-postlude} option adds the specified expressions to the bottom
of the source code being compiled. The main use of this option is to
supply the expression that will start the execution of the program. For
example:
@smallexample
$ @b{gsc -postlude "(start-bench)" bench.scm}
@end smallexample
@opindex -cc-options
The @samp{-cc-options} option is only meaningful when a dynamically
loadable object file is being generated (neither the @samp{-c} or
@samp{-link} options are used). The @samp{-cc-options} option adds
the specified options to the command that invokes the C compiler. The
main use of this option is to specify the include path, some symbols
to define or undefine, the optimization level, or any C compiler
option that is different from the default. For example:
@smallexample
$ @b{gsc -cc-options "-U___SINGLE_HOST -O2 -I../include" bench.scm}
@end smallexample
@opindex -ld-options-prelude
@opindex -ld-options
The @samp{-ld-options-prelude} and @samp{-ld-options} options are only
meaningful when a dynamically loadable object file is being generated
(neither the @samp{-c} or @samp{-link} options are used). The
@samp{-ld-options-prelude} and @samp{-ld-options} options add the
specified options to the command that invokes the C linker (the
options in @var{ld-options-prelude} are passed to the C linker before
the input file and the options in @var{ld-options} are passed after).
The main use of this option is to specify additional object files or
libraries that need to be linked, or any C linker option that is
different from the default (such as the library search path and flags
to select between static and dynamic linking). For example:
@smallexample
$ @b{gsc -ld-options "-L/usr/X11R6/lib -lX11 -dynamic" bench.scm}
@end smallexample
@opindex -warnings
The @samp{-warnings} option displays on standard output all warnings
that the compiler may have.
@opindex -verbose
The @samp{-verbose} option displays on standard output a trace of the
compiler's activity.
@opindex -report
The @samp{-report} option displays on standard output a global
variable usage report. Each global variable used in the program is
listed with 4 flags that indicate whether the global variable is
defined, referenced, mutated and called.
@opindex -expansion
The @samp{-expansion} option displays on standard output the source code
after expansion and inlining by the front end.
@opindex -gvm
The @samp{-gvm} option generates a listing of the intermediate code
for the ``Gambit Virtual Machine'' (GVM) of each Scheme file on
@samp{@var{file}.gvm}.
@opindex -debug
@opindex debug
The @samp{-debug} option causes all kinds of debugging information to
be saved in the code generated. See the documentation of the
@samp{debug} declaration for details.
@opindex -debug-location
@opindex debug-location
The @samp{-debug-location} option causes source code location
debugging information to be saved in the code generated. See the
documentation of the @samp{debug-location} declaration for details.
@opindex -debug-source
@opindex debug-source
The @samp{-debug-source} option causes source code debugging
information to be saved in the code generated. See the documentation
of the @samp{debug-source} declaration for details.
@opindex -debug-environments
@opindex debug-environments
The @samp{-debug-environments} option causes environment debugging
information to be saved in the code generated. See the documentation
of the @samp{debug-environments} declaration for details.
@opindex -track-scheme
The @samp{-track-scheme} options causes the generation of @samp{#line}
directives that refer back to the Scheme source code. This allows the
use of a C debugger or profiler to debug Scheme code.
@opindex -o @var{output}
The @samp{-o} option sets the filename of the output file, or the
directory in which the output file(s) generated by the compiler are
written.
@opindex -c
@opindex -dynamic
@opindex -exe
@opindex -obj
@opindex -link
@opindex -keep-c
@flindex @var{last}_.c
If the @samp{-link} or @samp{-exe} options appear on the command line,
the Gambit linker is invoked to generate the link file from the set of
C files specified on the command line or produced by the Gambit
compiler. By default the link file is @samp{@var{last}_.c}, where
@samp{@var{last}.c} is the last file in the set of C files. When the
@samp{-c} option is specified, the Scheme source files are compiled to
C files. When the @samp{-exe} option is specified, the generated C
files and link file are compiled and linked using the C compiler to
produce an executable program whose name defaults to
@samp{@var{last}.exe}. When the @samp{-obj} option is specified, the
generated C files are compiled using the C compiler to produce object
files (@samp{.o} or @samp{.obj} extensions). If neither the
@samp{-link}, @samp{-c}, @samp{-exe}, @samp{-obj} options appear on
the command line, the Scheme source files are compiled to dynamically
loadable object files (@samp{.o@var{n}} extension). The
@samp{-keep-c} option will prevent the deletion of any intermediate
@samp{.c} file that is generated. Note that in this case the
intermediate @samp{.c} file will be generated in the same directory as
the Scheme source file even if the @samp{-o} option is used.
@opindex -flat
The @samp{-flat} option is only meaningful when a link file is being
generated (i.e. the @samp{-link} or @samp{-exe} options also appear on
the command line). The @samp{-flat} option directs the Gambit linker
to generate a flat link file. By default, the linker generates an
incremental link file (see the next section for a description of the
two types of link files).
@opindex -l @var{base}
The @samp{-l} option is only meaningful when an incremental link file
is being generated (i.e. the @samp{-link} or @samp{-exe} options
appear on the command line and the @samp{-flat} option is absent).
The @samp{-l} option specifies the link file (without the @samp{.c}
extension) of the base library to use for the incremental link. By
default the link file of the Gambit runtime library is used
(i.e. @samp{~~lib/_gambc.c}).
@opindex -
The @samp{-} option starts a REPL interaction.
@opindex -e
The @samp{-e} option evaluates the specified expressions in the
interaction environment.
@node Link files, Procedures specific to compiler, GSC batch mode, GSC
@section Link files
Gambit can be used to create programs and libraries of Scheme
modules. This section explains the steps required to do so and the role
played by the link files.
In general, a program is composed of a set of Scheme modules and C
modules. Some of the modules are part of the Gambit runtime library and
the other modules are supplied by the user. When the program is
started it must setup various global tables (including the symbol table
and the global variable table) and then sequentially execute the Scheme
modules (more or less as though they were being loaded one after another).
The information required for this is contained in one or more @dfn{link
files} generated by the Gambit linker from the C files produced by the
Gambit compiler.
The order of execution of the Scheme modules corresponds to the order of
the modules on the command line which produced the link file. The order
is usually important because most modules define variables and
procedures which are used by other modules (for this reason the
program's main computation is normally started by the last module).
When a single link file is used to contain the linking information of
all the Scheme modules it is called a @dfn{flat link file}. Thus a
program built with a flat link file contains in its link file both
information on the user modules and on the runtime library. This is
fine if the program is to be statically linked but is wasteful in
a shared-library context because the linking information of the
runtime library can't be shared and will be duplicated in all
programs (this linking information typically takes hundreds of kilobytes).
Flat link files are mainly useful to bundle multiple Scheme modules to
make a runtime library (such as the Gambit runtime library) or to make a
single file that can be loaded with the @code{load} procedure.
An @dfn{incremental link file} contains only the linking information
that is not already contained in a second link file (the ``base'' link
file). Assuming that a flat link file was produced when the runtime
library was linked, a program can be built by linking the user
modules with the runtime library's link file, producing an incremental
link file. This allows the creation of a shared-library which
contains the modules of the runtime library and its flat link file.
The program is dynamically linked with this shared-library and
only contains the user modules and the incremental link file. For
small programs this approach greatly reduces the size of the
program because the incremental link file is small. A ``hello
world'' program built this way can be as small as 5 Kbytes. Note that
it is perfectly fine to use an incremental link file for statically
linked programs (there is very little loss compared to a single flat
link file).
Incremental link files may be built from other incremental link files.
This allows the creation of shared-libraries which extend the
functionality of the Gambit runtime library.
@menu
* Building an executable program:: Building an executable program
* Building a loadable library:: Building a loadable library
* Building a shared-library:: Building a shared-library
* Other compilation options:: Other compilation options
@end menu
@node Building an executable program, Building a loadable library, Link files, Link files
@subsection Building an executable program
The simplest way to create an executable program is to invoke
@code{gsc} with the @samp{-exe} option. The compiler will
transparently perform all the steps necessary, including compiling
Scheme source files to C files, generating the link file, compiling
the C files generated to object files, and creating the final
executable file using the C linker. The following example shows how
to build the executable program @samp{hello.exe} which contains the
two Scheme modules @samp{h.scm} and @samp{w.six}.
@smallexample
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{cat w.six}
display("world"); newline();
$ @b{gsc -o hello.exe -exe h.scm w.six}
h.scm:
/Users/feeley/gambit/doc/h.c:
w.six:
/Users/feeley/gambit/doc/w.c:
/Users/feeley/gambit/doc/w_.c:
$ @b{./hello.exe}
hello
world
@end smallexample
The detailed steps which are performed can be viewed by setting the
@samp{GAMBC_CC_VERBOSE} environment variable to a nonnull value. For
example:
@smallexample
$ @b{export GAMBC_CC_VERBOSE=yes}
$ @b{gsc -o hello.exe -exe h.scm w.six}
h.scm:
/Users/feeley/gambit/doc/h.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
-fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
-fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "h.o" h.c
w.six:
/Users/feeley/gambit/doc/w.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
-fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
-fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "w.o" w.c
/Users/feeley/gambit/doc/w_.c:
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
-fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
-fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include" -c -o "w_.o" w_.c
gcc -no-cpp-precomp -Wno-unused -O1 -fno-math-errno -fschedule-insns2
-fno-trapping-math -fno-strict-aliasing -fwrapv -fomit-frame-pointer
-fPIC -fno-common -mieee-fp -I"/usr/local/Gambit-C/include"
-o "hello.exe" h.o w.o w_.o "/usr/local/Gambit-C/lib/libgambc.a"
@end smallexample
Using a single invocation of @code{gsc} with the @samp{-exe} option is
sometimes inappropriate when the build process is more complex, for
example when the program is composed of several seperately compiled
modules. In such a case it is useful to decompose the build process
into smaller compilation steps. The @samp{hello.exe} executable
program could have been built by seperating the generation of C files
from the C compilation and linking:
@smallexample
$ @b{gsc -c h.scm}
$ @b{gsc -c w.six}
$ @b{gsc -o hello.exe -exe h.c w.c}
@end smallexample
When even finer control is desired the build process can be decomposed
into smaller steps that invoke the C compiler and linker explicitly.
This is described in the rest of this section.
The @code{gsc} compiler can be invoked to compile each Scheme module
into a C file and to create an incremental link file. The C files and
the link file must then be compiled with a C compiler and linked (at
the object file level) with the Gambit runtime library and possibly
other libraries (such as the math library and the dynamic loading
library).
Here is for example how a program with three modules (one in C and two
in Scheme) can be built. The content of the three source files (@samp{m1.c},
@samp{m2.scm} and @samp{m3.scm}) is:
@smallexample
@b{}/* File: "m1.c" */
int power_of_2 (int x) @{ return 1<<x; @}
; File: "m2.scm"
(c-declare "extern int power_of_2 ();")
(define pow2 (c-lambda (int) int "power_of_2"))
(define (twice x) (cons x x))
; File: "m3.scm"
(write (map twice (map pow2 '(1 2 3 4)))) (newline)
@end smallexample
The compilation of the two Scheme source files can be done with
three invocations of @code{gsc}:
@smallexample
$ @b{gsc -c m2.scm @r{@i{# create m2.c (note: .scm is optional)}}}
$ @b{gsc -c m3.scm @r{@i{# create m3.c (note: .scm is optional)}}}
$ @b{gsc -link m2.c m3.c @r{@i{# create the incremental link file m3_.c}}}
@end smallexample
Alternatively, the three invocations of @code{gsc} can be replaced by a
single invocation:
@smallexample
$ @b{gsc -link m2 m3}
m2:
m3:
@end smallexample
At this point there will be 4 C files: @samp{m1.c}, @samp{m2.c},
@samp{m3.c}, and @samp{m3_.c}. To produce an executable program these
files must be compiled with a C compiler and linked with the Gambit-C
runtime library. The C compiler options needed will depend on the C
compiler and the operating system (in particular it may be necessary
to add the options @samp{-I/usr/local/Gambit-C/include
-L/usr/local/Gambit-C/lib} to access the @samp{gambit.h} header file
and the Gambit-C runtime library).
Here is an example under Mac OS X:
@smallexample
$ @b{uname -srmp}
Darwin 8.1.0 Power Macintosh powerpc
$ @b{gsc -obj m1.c m2.c m3.c m3_.c}
m1.c:
m2.c:
m3.c:
m3_.c:
$ @b{gcc m1.o m2.o m3.o m3_.o -lgambc}
$ @b{./a.out}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample
Here is an example under Linux:
@smallexample
$ @b{uname -srmp}
Linux 2.6.8-1.521 i686 athlon
$ @b{gsc -obj m1.c m2.c m3.c m3_.c}
m1.c:
m2.c:
m3.c:
m3_.c:
$ @b{gcc m1.o m2.o m3.o m3_.o -lgambc -lm -ldl -lutil}
$ @b{./a.out}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample
@node Building a loadable library, Building a shared-library, Building an executable program, Link files
@subsection Building a loadable library
@opindex -D___DYNAMIC
To bundle multiple modules into a single object file that can be
dynamically loaded with the @code{load} procedure, a flat link file is
needed. The compiler's @samp{-o} option must be used to name the C
file generated as follows. If the dynamically loadable object file is
to be named @samp{@var{myfile}.o@var{n}} then the @samp{-o} option
must set the name of the link file generated to
@samp{@var{myfile}.o@var{n}.c} (note that the @samp{.c} extension
could also be @samp{.cc}, @samp{.cpp} or whatever extension is
appropriate for C/C++ source files). The three modules of the
previous example can be bundled by generating a link file in this way:
@smallexample
$ @b{gsc -link -flat -o foo.o1.c m2 m3}
m2:
m3:
*** WARNING -- "cons" is not defined,
*** referenced in: ("m2.c")
*** WARNING -- "map" is not defined,
*** referenced in: ("m3.c")
*** WARNING -- "newline" is not defined,
*** referenced in: ("m3.c")
*** WARNING -- "write" is not defined,
*** referenced in: ("m3.c")
@end smallexample
The warnings indicate that there are no definitions (@code{define}s or
@code{set!}s) of the variables @code{cons}, @code{map}, @code{newline}
and @code{write} in the set of modules being linked. Before
@samp{foo.o1} is loaded, these variables will have to be bound; either
implicitly (by the runtime library) or explicitly.
When compiling the C files and link file generated, the flag
@samp{-D___DYNAMIC} must be passed to the C compiler and the C
compiler and linker must be told to generate a dynamically loadable
shared library.
Here is an example under Mac OS X:
@smallexample
$ @b{uname -srmp}
Darwin 10.5.0 i386 i386
$ @b{gsc -link -flat -o foo.o1.c m2 m3 > /dev/null}
m2:
m3:
$ @b{gsc -cc-options "-D___DYNAMIC" -obj m1.c m2.c m3.c foo.o1.c}
m1.c:
m2.c:
m3.c:
foo.o1.c:
$ @b{gcc -bundle m1.o m2.o m3.o foo.o1.o -o foo.o1}
$ @b{gsi foo.o1}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample
Here is an example under Linux:
@smallexample
$ @b{uname -srmp}
Linux 2.6.8-1.521 i686 athlon
$ @b{gsc -link -flat -o foo.o1.c m2 m3 > /dev/null}
m2:
m3:
$ @b{gsc -cc-options "-D___DYNAMIC" -obj m1.c m2.c m3.c foo.o1.c}
m1.c:
m2.c:
m3.c:
foo.o1.c:
$ @b{gcc -shared m1.o m2.o m3.o foo.o1.o -o foo.o1}
$ @b{gsi foo.o1}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample
Here is a more complex example, under Solaris, which shows how to build
a loadable library @samp{mymod.o1} composed of the files @samp{m4.scm},
@samp{m5.scm} and @samp{x.c} that links to system shared libraries (for
X-windows):
@smallexample
$ @b{uname -srmp}
SunOS ungava 5.6 Generic_105181-05 sun4m sparc SUNW,SPARCstation-20
$ @b{gsc -link -flat -o mymod.o1.c m4 m5}
m4:
m5:
*** WARNING -- "*" is not defined,
*** referenced in: ("m4.c")
*** WARNING -- "+" is not defined,
*** referenced in: ("m5.c")
*** WARNING -- "display" is not defined,
*** referenced in: ("m5.c" "m4.c")
*** WARNING -- "newline" is not defined,
*** referenced in: ("m5.c" "m4.c")
*** WARNING -- "write" is not defined,
*** referenced in: ("m5.c")
$ @b{gsc -cc-options "-D___DYNAMIC" -obj m4.c m5.c x.c mymod.o1.c}
m4.c:
m5.c:
x.c:
mymod.o1.c:
$ @b{/usr/ccs/bin/ld -G -o mymod.o1 mymod.o1.o m4.o m5.o x.o -lX11 -lsocket}
$ @b{gsi mymod.o1}
hello from m4
hello from m5
(f1 10) = 22
$ @b{cat m4.scm}
(define (f1 x) (* 2 (f2 x)))
(display "hello from m4")
(newline)
(c-declare #<<c-declare-end
#include "x.h"
c-declare-end
)
(define x-initialize (c-lambda (char-string) bool "x_initialize"))
(define x-display-name (c-lambda () char-string "x_display_name"))
(define x-bell (c-lambda (int) void "x_bell"))
$ @b{cat m5.scm}
(define (f2 x) (+ x 1))
(display "hello from m5")
(newline)
(display "(f1 10) = ")
(write (f1 10))
(newline)
(x-initialize (x-display-name))
(x-bell 50) ; sound the bell at 50%
$ @b{cat x.c}
#include <X11/Xlib.h>
static Display *display;
int x_initialize (char *display_name)
@{
display = XOpenDisplay (display_name);
return display != NULL;
@}
char *x_display_name (void)
@{
return XDisplayName (NULL);
@}
void x_bell (int volume)
@{
XBell (display, volume);
XFlush (display);
@}
$ @b{cat x.h}
int x_initialize (char *display_name);
char *x_display_name (void);
void x_bell (int);
@end smallexample
@node Building a shared-library, Other compilation options, Building a loadable library, Link files
@subsection Building a shared-library
@opindex -D___PRIMAL
@opindex -D___LIBRARY
@opindex -D___SHARED
A shared-library can be built using an incremental link file or a flat
link file. An incremental link file is normally used when the Gambit
runtime library (or some other library) is to be extended with new
procedures. A flat link file is mainly useful when building a
``primal'' runtime library, which is a library (such as the Gambit
runtime library) that does not extend another library. When compiling
the C files and link file generated, the flags @samp{-D___LIBRARY} and
@samp{-D___SHARED} must be passed to the C compiler. The flag
@samp{-D___PRIMAL} must also be passed to the C compiler when a primal
library is being built.
A shared-library @samp{mylib.so} containing the two first modules of
the previous example can be built this way:
@smallexample
$ @b{uname -srmp}
Linux bailey 1.2.13 #2 Wed Aug 28 16:29:41 GMT 1996 i586
$ @b{gsc -link -o mylib.c m2}
$ @b{gsc -obj -cc-options "-D___SHARED" m1.c m2.c mylib.c}
m1.c:
m2.c:
mylib.c:
$ @b{gcc -shared m1.o m2.o mylib.o -o mylib.so}
@end smallexample
Note that this shared-library is built using an incremental link file
(it extends the Gambit runtime library with the procedures @code{pow2}
and @code{twice}). This shared-library can in turn be used to build
an executable program from the third module of the previous example:
@smallexample
$ @b{gsc -link -l mylib m3}
$ @b{gsc -obj m3.c m3_.c}
m3.c:
m3_.c:
$ @b{gcc m3.o m3_.o mylib.so -lgambc}
$ @b{LD_LIBRARY_PATH=.:/usr/local/lib ./a.out}
((2 . 2) (4 . 4) (8 . 8) (16 . 16))
@end smallexample
@node Other compilation options, , Building a shared-library, Link files
@subsection Other compilation options
@opindex -D___SINGLE_HOST
@opindex -O
The performance of the code can be increased by passing the
@samp{-D___SINGLE_HOST} flag to the C compiler. This will merge all
the procedures of a module into a single C procedure, which reduces
the cost of intra-module procedure calls. In addition the @samp{-O}
option can be passed to the C compiler. For large modules, it will
not be practical to specify both @samp{-O} and @samp{-D___SINGLE_HOST}
for typical C compilers because the compile time will be high and the
C compiler might even fail to compile the program for lack of memory.
It has been observed that lower levels of optimization (e.g. @samp{-O1})
often give faster compilation and also generate faster code. It is
a good idea to experiment.
@opindex -I/usr/local/Gambit-C/include
@opindex -L/usr/local/Gambit-C/lib
Normally C compilers will not automatically search
@samp{/usr/local/Gambit-C/include} for header files so the flag
@samp{-I/usr/local/Gambit-C/include} should be passed to the C
compiler. Similarly, C compilers/linkers will not automatically
search @samp{/usr/local/Gambit-C/lib} for libraries so the flag
@samp{-L/usr/local/Gambit-C/lib} should be passed to the C
compiler/linker. Alternatives are given in @ref{Accessing the system
files}.
@opindex -shared
@opindex -call_shared
@opindex -rdynamic
@opindex -fpic
@opindex -fPIC
@opindex -Kpic
@opindex -KPIC
@opindex -pic
@opindex +z
@opindex -G
A variety of flags are needed by some C compilers when compiling a
shared-library or a dynamically loadable library. Some of these flags
are: @samp{-shared}, @samp{-call_shared}, @samp{-rdynamic},
@samp{-fpic}, @samp{-fPIC}, @samp{-Kpic}, @samp{-KPIC}, @samp{-pic},
@samp{+z}, @samp{-G}. Check your compiler's documentation to see
which flag you need.
@node Procedures specific to compiler, , Link files, GSC
@section Procedures specific to compiler
The Gambit Scheme compiler features the following procedures that
are not available in the Gambit Scheme interpreter.
@deffn procedure compile-file-to-target @var{file} @r{[}@code{options:} @var{options}@r{]} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{module-name:} @var{module-name}@r{]}
@pindex gsc
The @var{file} parameter must be a string naming an existing file
containing Scheme source code. The extension can be omitted from
@var{file} when the Scheme file has a @samp{.scm} or @samp{.six}
extension. This procedure compiles the source file into a file
containing C code. By default, this file is named after @var{file}
with the extension replaced with @samp{.c}. The name of the generated
file can be specified with the @var{output} parameter. If
@var{output} is a string naming a directory then the C file is created
in that directory. Otherwise the name of the C file is @var{output}.
The name of the generated module can be specified with the
@var{module-name} parameter. If @var{module-name} is @code{#f} or is
not specified, then the name of the module is derived from the name of
the C file generated, without the extension.
Compilation options are specified through the @var{options} parameter
which must be a list of symbols. Any combination of the following
options can be used: @samp{verbose}, @samp{report}, @samp{expansion},
@samp{gvm}, and @samp{debug}.
When the compilation is successful, @code{compile-file-to-target} returns
the name of the C file generated. When there is a compilation error,
@code{#f} is returned.
@smallexample
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{gsc}
Gambit @value{VERSION}
> @b{(compile-file-to-target "h")}
"/Users/feeley/gambit/doc/h.c"
@end smallexample
@end deffn
@deffn procedure compile-file @var{file} @r{[}@code{options:} @var{options}@r{]} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{cc-options:} @var{cc-options}@r{]} @r{[}@code{ld-options-prelude:} @var{ld-options-prelude}@r{]} @r{[}@code{ld-options:} @var{ld-options}@r{]}
@pindex gsc
@findex load
@cindex object file
The @var{file}, @var{options}, and @var{output} parameters have the
same meaning as for the @code{compile-file-to-target} procedure, except that
@var{file} may be a Scheme source file or a
C file possibly generated by the Gambit Scheme compiler (for example
with the @code{compile-file-to-target} procedure). The
@var{cc-options} parameter is a string containing the options to pass
to the C compiler and the @var{ld-options-prelude} and
@var{ld-options} parameters are strings containing the options to pass
to the C linker (the options in @var{ld-options-prelude} are passed to
the C linker before the input file and the options in @var{ld-options}
are passed after).
The @code{compile-file} procedure compiles the source file @var{file}
into an object file, which is either a file dynamically loadable using
the @code{load} procedure, or a C linkable object file destined to be
linked with the C linker (for example to create a standalone
executable program). The presence of the
@code{obj} option in @var{options} will cause the creation of a C
linkable object file and therefore the options
@var{ld-options-prelude} and @var{ld-options} are ignored, otherwise a
dynamically loadable file is created. In both cases, if @var{file} is
a Scheme source file, the compiler first compiles @var{file} to a C
file which is created in the same directory as @var{file} regardless
of the @var{output} parameter. Then the C file is compiled with the C
compiler.
When the compilation is successful, @code{compile-file} returns the
name of the object file generated. When there is a compilation error,
@code{#f} is returned.
The name of the object file can be specified with the @var{output}
parameter. If @var{output} is a string naming a directory then the
object file is created in that directory. Otherwise the name of the
object file is @var{output}.
In the case of a dynamically loadable object file, by default the
object file is named after @var{file} with the extension replaced with
@samp{.o@var{n}}, where @var{n} is a positive integer that acts as a
version number. The next available version number is generated
automatically by @code{compile-file}.
When dynamically loaded object files are loaded using the @code{load}
procedure, the @samp{.o@var{n}} extension can be specified (to select
a particular version) or omitted (to load the file with a
@samp{.o@var{n}} extension with the highest @var{n} consecutively from
1). When the @samp{.o@var{n}} extension is not specified and older
versions are no longer needed, all versions must be deleted and the
compilation must be repeated (this is necessary because the file name,
including the extension, is used to name some of the exported symbols
of the object file).
Note that dynamically loadable object files can only be generated on
host operating systems that support dynamic loading.
@smallexample
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{gsc}
Gambit @value{VERSION}
> @b{(compile-file "h")}
"/Users/feeley/gambit/doc/h.o1"
> @b{(load "h")}
hello
"/Users/feeley/gambit/doc/h.o1"
> @b{(compile-file-to-target "h" output: "h.o99.c")}
"/Users/feeley/gambit/doc/h.o99.c"
> @b{(compile-file "h.o99.c")}
"/Users/feeley/gambit/doc/h.o99"
> @b{(load "h.o99")}
hello
"/Users/feeley/gambit/doc/h.o99"
> @b{(compile-file-to-target "h")}
"/Users/feeley/gambit/doc/h.c"
> @b{(compile-file "h.c" options: '(obj))}
"/Users/feeley/gambit/doc/h.o"
@end smallexample
@end deffn
@deffn procedure link-incremental @var{module-list} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{base:} @var{base}@r{]} @r{[}@code{warnings?:} @var{warnings?}@r{]}
@pindex gsc
The first parameter must be a non empty list of strings naming Scheme
modules to link (the file extension may be omitted). An incremental link
file is generated for the modules specified in @var{module-list}. By
default the link file generated is named @samp{@var{last}_.c}, where
@var{last} is the name of the last module, without the file extension.
The name of the generated
link file can be specified with the @var{output} parameter. If
@var{output} is a string naming a directory then the link file is
created in that directory. Otherwise the name of the link file is
@var{output}.
The base link file is specified by the @var{base} parameter, which
must be a string. By default the base link file is the Gambit runtime
library link file @samp{~~lib/_gambc.c}. However, when @var{base} is
supplied it is the name of the base link file (the file extension
may be omitted).
The @var{warnings?} parameter controls whether warnings are
generated for undefined references.
The following example shows how to build the executable program
@samp{hello} which contains the two Scheme modules @samp{h.scm} and
@samp{w.six}.
@smallexample
$ @b{uname -srmp}
Darwin 8.1.0 Power Macintosh powerpc
$ @b{cat h.scm}
(display "hello") (newline)
$ @b{cat w.six}
display("world"); newline();
$ @b{gsc}
Gambit @value{VERSION}
> @b{(compile-file-to-target "h")}
"/Users/feeley/gambit/doc/h.c"
> @b{(compile-file-to-target "w")}
"/Users/feeley/gambit/doc/w.c"
> @b{(link-incremental '("h" "w") output: "hello.c")}
"/Users/feeley/gambit/doc/hello_.c"
> @b{,q}
$ @b{gsc -obj h.c w.c hello.c}
h.c:
w.c:
hello.c:
$ @b{gcc h.o w.o hello.o -lgambc -o hello}
$ @b{./hello}
hello
world
@end smallexample
@end deffn
@deffn procedure link-flat @var{module-list} @r{[}@code{output:} @var{output}@r{]} @r{[}@code{warnings?:} @var{warnings?}@r{]}
@pindex gsc
The first parameter must be a non empty list of strings naming Scheme
modules to link (the file extension may be omitted). The first string
must be the name of a Scheme module
or the name of a link file and the remaining strings must name Scheme
modules. A flat link file
is generated for the modules specified in @var{module-list}. By
default the link file generated is named @samp{@var{last}_.c}, where
@var{last} is the name of the last module. The name of the generated
link file can be specified with the @var{output} parameter. If
@var{output} is a string naming a directory then the link file is
created in that directory. Otherwise the name of the link file is
@var{output}. If a dynamically loadable object file is produced from
the link file @samp{@var{output}}, then the name of the dynamically
loadable object file must be @samp{@var{output}} stripped of its file
extension.
The @var{warnings?} parameter controls whether warnings are
generated for undefined references.
The following example shows how to build the dynamically loadable object
file @samp{lib.o1} which contains the two Scheme modules
@samp{m6.scm} and @samp{m7.scm}.
@smallexample
$ @b{uname -srmp}
Darwin 8.1.0 Power Macintosh powerpc
$ @b{cat m6.scm}
(define (f x) (g (* x x)))
$ @b{cat m7.scm}
(define (g y) (+ n y))
$ @b{gsc}
Gambit @value{VERSION}
> @b{(compile-file-to-target "m6")}
"/Users/feeley/gambit/doc/m6.c"
> @b{(compile-file-to-target "m7")}
"/Users/feeley/gambit/doc/m7.c"
> @b{(link-flat '("m6" "m7") output: "lib.o1.c")}
*** WARNING -- "*" is not defined,
*** referenced in: ("m6.c")
*** WARNING -- "+" is not defined,
*** referenced in: ("m7.c")
*** WARNING -- "n" is not defined,
*** referenced in: ("m7.c")
"/Users/feeley/gambit/doc/lib.o1.c"
> @b{,q}
$ @b{gcc -bundle -D___DYNAMIC m6.c m7.c lib.o1.c -o lib.o1}
$ @b{gsc}
Gambit @value{VERSION}
> @b{(load "lib")}
*** WARNING -- Variable "n" used in module "m7" is undefined
"/Users/feeley/gambit/doc/lib.o1"
> @b{(define n 10)}
> @b{(f 5)}
35
> @b{,q}
@end smallexample
The warnings indicate that there are no definitions (@code{define}s or
@code{set!}s) of the variables @code{*}, @code{+} and @code{n} in the
modules contained in the library. Before the library is used, these
variables will have to be bound; either implicitly (by the runtime
library) or explicitly.
@end deffn
@node Runtime options, Debugging, GSC, Top
@chapter Runtime options
@cindex runtime options
@cindex options, runtime
@pindex gsc
@pindex gsi
Both @code{gsi} and @code{gsc} as well as executable programs compiled
and linked using @code{gsc} take a @samp{-:} option which supplies
parameters to the runtime system. This option must appear first on
the command line. The colon is followed by a comma separated list of
options with no intervening spaces. The available options are:
@table @code
@item m@var{HEAPSIZE}
Set minimum heap size in kilobytes.
@item h@var{HEAPSIZE}
Set maximum heap size in kilobytes.
@item l@var{LIVEPERCENT}
Set heap occupation after garbage collection.
@item s
Select standard Scheme mode.
@item S
Select Gambit Scheme mode.
@item d@r{[}@var{OPT}...@r{]}
Set debugging options.
@item @@@r{[}@var{INTF}@r{]}@r{[}:@var{PORT}@r{]}
Override the configuration of the main RPC server.
@item =@var{DIRECTORY}
Override the central installation directory.
@item ~~@var{DIR}=@var{DIRECTORY}
Override the @var{DIR} installation directory.
@item +@var{ARGUMENT}
Add @var{ARGUMENT} to the command line before other arguments.
@item f@r{[}@var{OPT}...@r{]}
Set file options.
@item t@r{[}@var{OPT}...@r{]}
Set terminal options.
@item -@r{[}@var{OPT}...@r{]}
Set standard input and output options.
@end table
@opindex -:m
The @samp{m} option specifies the minimum size of the heap. The
@samp{m} is immediately followed by an integer indicating the number
of kilobytes of memory. The heap will not shrink lower than this
size. By default, the minimum size is 0.
@opindex -:h
The @samp{h} option specifies the maximum size of the heap. The
@samp{h} is immediately followed by an integer indicating the number
of kilobytes of memory. The heap will not grow larger than this size.
By default, there is no limit (i.e. the heap will grow until the
virtual memory is exhausted).
@opindex -:l
The @samp{l} option specifies the percentage of the heap that will be
occupied with live objects after the heap is resized at the end of a
garbage collection. The @samp{l} is immediately followed by an
integer between 1 and 100 inclusively indicating the desired
percentage. The garbage collector resizes the heap to reach this
percentage occupation. By default, the percentage is 50.
@opindex -:s
@opindex -:S
The @samp{s} option selects standard Scheme mode. In this mode the
reader is case-insensitive and keywords are not recognized. The
@samp{S} option selects Gambit Scheme mode (the reader is case-sensitive
and recognizes keywords which end with a colon). By default Gambit
Scheme mode is used.
@opindex -:d
The @samp{d} option sets various debugging options. The letter
@samp{d} is followed by a sequence of letters indicating suboptions.
@table @code
@item p
@opindex -:dp
Uncaught exceptions will be treated as ``errors'' in the primordial thread
only.
@item a
@opindex -:da
Uncaught exceptions will be treated as ``errors'' in all threads.
@item r
@opindex -:dr
When an ``error'' occurs a new REPL will be started.
@item s
@opindex -:ds
When an ``error'' occurs a new REPL will be started.
Moreover the program starts in single-stepping mode.
@item q
@opindex -:dq
When an ``error'' occurs the program will terminate with a nonzero
exit status.
@item R
@opindex -:dR
@kindex ^C
When a user interrupt occurs a new REPL will be started. User
interrupts are typically obtained by typing @key{^C}. Note that with
some system configurations @key{^C} abruptly terminates the process.
For example, under Microsoft Windows, @key{^C} works fine with the
standard console but with the MSYS terminal window it terminates the
process.
@item D
@opindex -:dD
When a user interrupt occurs it will be deferred until the parameter
@code{current-user-interrupt-handler} is bound.
@item Q
@opindex -:dQ
When a user interrupt occurs the program will terminate with a nonzero
exit status.
@item @var{LEVEL}
@opindex -:d@var{LEVEL}
The verbosity level is set to @var{LEVEL} (a digit from 0 to 9).
At level 0 the runtime system will not display error messages
and warnings.
@item i
@opindex -:di
The REPL interaction channel will be the IDE REPL window (if the IDE
is available).
@item c
@opindex -:dc
The REPL interaction channel will be the console.
@item -
@opindex -:d-
The REPL interaction channel will be standard input and standard output.
@item @@@r{[}@var{HOST}@r{]}@r{[}:@var{PORT}@r{]}
@opindex -:d@@@r{[}@var{HOST}@r{]}@r{[}:@var{PORT}@r{]}
The REPL interaction channel will be connected to the remote debugger
at address @var{HOST}:@var{PORT} (if there is a remote debugger at
that address). The default @var{HOST} is 127.0.0.1 and the default
@var{PORT} is 44555.
THIS OPTION IS NOT YET IMPLEMENTED!
@end table
The default debugging options are equivalent to @code{-:dpqQ1i}
(i.e. an uncaught exception in the primordial thread terminates the
program after displaying an error message). When the letter @samp{d}
is not followed by suboptions, it is equivalent to @code{-:dprR1i}
(i.e. a new REPL is started only when an uncaught exception occurs in
the primordial thread). When @code{gsi} and @code{gsc} are running
the main REPL, the debugging options are changed to cause errors in
the primordial thread and user interrupts to start a nested REPL.
@opindex -:@
The @samp{@@@r{[}@var{INTF}@r{]}@r{[}:@var{PORT}@r{]}} option
overrides the configuration of the main RPC server. The default
@var{INTF} is 127.0.0.1 and the default @var{PORT} is 44556.
THIS OPTION IS NOT YET IMPLEMENTED!
@opindex -:=
The @samp{=@var{DIRECTORY}} option overrides the setting of the
central installation directory.
@opindex -:~~
The @samp{~~@var{DIR}=@var{DIRECTORY}} option overrides the setting of
the @var{DIR} installation directory.
@opindex -:+
The @samp{+} option adds the text that follows to the command line
before other arguments.
@opindex -:f
@opindex -:t
@opindex -:-
The @samp{f}, @samp{t} and @samp{-} options specify the default
settings of the ports created for files, terminals and standard input
and output respectively. The default character encoding, end-of-line
encoding and buffering can be set. Moreover, for terminals the
line-editing feature can be enabled or disabled. The @samp{f},
@samp{t} and @samp{-} must be followed by a sequence of these options:
@table @code
@item A
ASCII character encoding.
@item 1
ISO-8859-1 character encoding.
@item 2
UCS-2 character encoding.
@item 4
UCS-4 character encoding.
@item 6
UTF-16 character encoding.
@item 8
UTF-8 character encoding.
@item U
UTF character encoding with fallback to UTF-8 on input if no BOM is present.
@item UA
UTF character encoding with fallback to ASCII on input if no BOM is present.
@item U1
UTF character encoding with fallback to ISO-8859-1 on input if no BOM is present.
@item U6
UTF character encoding with fallback to UTF-16 on input if no BOM is present.
@item U8
UTF character encoding with fallback to UTF-8 on input if no BOM is present.
@item c
End-of-line is encoded as CR (carriage-return).
@item l
End-of-line is encoded as LF (linefeed)
@item cl
End-of-line is encoded as CR-LF.
@item u
Unbuffered I/O.
@item n
Line buffered I/O (@samp{n} for ``at newline'').
@item f
Fully buffered I/O.
@item r
Illegal character encoding is treated as an error (exception raised).
@item R
Silently replace illegal character encodings with Unicode character #xfffd
(replacement character).
@item e
Enable line-editing (applies to terminals only).
@item E
Disable line-editing (applies to terminals only).
@end table
@opindex -::
@cindex GAMBCOPT, environment variable
When a program's execution starts, the runtime system obtains the
runtime options by processing in turn four sources of runtime options:
the defaults, the environment variable @samp{GAMBCOPT}, the script
line of the source code, and the first command line argument of the
program. Any runtime option can be overriden by a subsequent source
of runtime options. It is sometimes useful to prevent overriding
the runtime options of the script line. This can be achieved by
starting the script line runtime options with @samp{-::}. In
this case the environment variable @samp{GAMBCOPT} is ignored,
and the first command line argument of the program is
not used for runtime options (it is treated like a normal
command line argument).
For example:
@smallexample
$ @b{GAMBCOPT=d0,=~/my-gambit2}
$ @b{export GAMBCOPT}
$ @b{gsi -e '(pretty-print (path-expand "~~")) (/ 1 0)'}
"/Users/feeley/my-gambit2/"
$ @b{echo $?}
70
$ @b{gsi -:d1 -e '(pretty-print (path-expand "~~")) (/ 1 0)'}
"/Users/feeley/my-gambit2/"
*** ERROR IN (string)@@1.3 -- Divide by zero
(/ 1 0)
@end smallexample
@node Debugging, Scheme extensions, Runtime options, Top
@chapter Debugging
@menu
* Debugging model:: Debugging model
* Debugging commands:: Debugging commands
* Debugging example:: Debugging example
* Procedures related to debugging:: Procedures related to debugging
* Console line-editing:: Console line-editing
* Emacs interface:: Emacs interface
* GUIDE:: GUIDE
@end menu
@node Debugging model, Debugging commands, Debugging, Debugging
@section Debugging model
The evaluation of an expression may stop before it is completed for the
following reasons:
@enumerate a
@item An evaluation error has occured, such as attempting to
divide by zero.
@kindex ^C
@item The user has interrupted the evaluation (usually by typing @key{^C}).
@item A breakpoint has been reached or @code{(step)} was evaluated.
@item Single-stepping mode is enabled.
@end enumerate
When an evaluation stops, a message is displayed indicating the reason
and location where the evaluation was stopped. The location
information includes, if known, the name of the procedure where the
evaluation was stopped and the source code location in the format
@samp{@var{stream}@@@var{line}.@var{column}}, where @var{stream} is
either a string naming a file or a symbol within parentheses, such as
@samp{(console)}.
A @dfn{nested REPL} is then initiated in the context of the point of
execution where the evaluation was stopped. The nested REPL's
continuation and evaluation environment are the same as the point where
the evaluation was stopped. For example when evaluating the expression
@samp{(let ((y (- 1 1))) (* (/ x y) 2))}, a ``divide by zero'' error is
reported and the nested REPL's continuation is the one that takes the
result and multiplies it by two. The REPL's lexical environment
includes the lexical variable @samp{y}. This allows the inspection of
the evaluation context (i.e. the lexical and dynamic environments and
continuation), which is particularly useful to determine the exact
location and cause of an error.
@kindex ^D
The prompt of nested REPLs includes the nesting level; @samp{1>} is the
prompt at the first nesting level, @samp{2>} at the second nesting
level, and so on. An end of file (usually @key{^D}) will cause the
current REPL to be terminated and the enclosing REPL (one nesting level
less) to be resumed.
At any time the user can examine the frames in the REPL's
continuation, which is useful to determine which chain of procedure
calls lead to an error. A backtrace that lists the chain of active
continuation frames in the REPL's continuation can be obtained with
the @samp{,b} command. The frames are numbered from 0, that is frame
0 is the most recent frame of the continuation where execution
stopped, frame 1 is the parent frame of frame 0, and so on. It is
also possible to move the REPL to a specific parent continuation
(i.e. a specific frame of the continuation where execution stopped)
with the @samp{,@var{N}}, @samp{,@var{N}+}, @samp{,@var{N}-},
@samp{,+}, @samp{,-}, @samp{,++}, and @samp{,--} commands. When the
frame number of the frame being examined is not zero, it is shown in
the prompt after the nesting level, for example @samp{1\5>} is the
prompt when the REPL nesting level is 1 and the frame number is 5.
Expressions entered at a nested REPL are evaluated in the environment
(both lexical and dynamic) of the continuation frame currently being
examined if that frame was created by interpreted Scheme code. If the
frame was created by compiled Scheme code then expressions get evaluated
in the global interaction environment. This feature may be used in
interpreted code to fetch the value of a variable in the current frame
or to change its value with @code{set!}. Note that some special forms
(@code{define} in particular) can only be evaluated in the global
interaction environment.
@node Debugging commands, Debugging example, Debugging model, Debugging
@section Debugging commands
In addition to expressions, the REPL accepts the following special
``comma'' commands:
@table @code
@item ,?
@cmindex ,?
Give a summary of the REPL commands.
@item ,(h @var{subject})
@cmindex ,(h @var{subject})
This command will show the section of the Gambit manual with the
definition of the procedure or special form @var{subject}, which must
be a symbol. For example @samp{,(h time)} will show the section
documenting the @code{time} special form. Please see the @code{help}
procedure for additional information.
@item ,h
@cmindex ,h
This command will show the section of the Gambit manual with the
definition of the procedure which raised the exception for which this
REPL was started.
@item ,q
@cmindex ,q
Terminate the process with exit status 0. This is equivalent to
calling @code{(exit 0)}.
@item ,qt
@cmindex ,qt
Terminate the current thread (note that terminating the primordial
thread terminates the process).
@item ,t
@cmindex ,t
Return to the outermost REPL, also known as the ``top-level REPL''.
@item ,d
@cmindex ,d
Leave the current REPL and resume the enclosing REPL. This command does
nothing in the top-level REPL.
@item ,(c @var{expr})
@cmindex ,(c @var{expr})
Leave the current REPL and continue the computation that initiated the
REPL with a specific value. This command can only be used to continue
a computation that signaled an error. The expression @var{expr} is
evaluated in the current context and the resulting value is returned
as the value of the expression which signaled the error. For example,
if the evaluation of the expression @samp{(* (/ x y) 2)} signaled an
error because @samp{y} is zero, then in the nested REPL a @samp{,(c (+
4 y))} will resume the computation of @samp{(* (/ x y) 2)} as though
the value of @samp{(/ x y)} was 4. This command must be used
carefully because the context where the error occured may rely on the
result being of a particular type. For instance a @samp{,(c #f)} in
the previous example will cause @samp{*} to signal a type error (this
problem is the most troublesome when debugging Scheme code that was
compiled with type checking turned off so be careful).
@item ,c
@cmindex ,c
Leave the current REPL and continue the computation that initiated the
REPL. This command can only be used to continue a computation that was
stopped due to a user interrupt, breakpoint or a single-step.
@item ,s
@cmindex ,s
Leave the current REPL and continue the computation that initiated the
REPL in single-stepping mode. The computation will perform an
evaluation step (as defined by @code{step-level-set!}) and then stop,
causing a nested REPL to be entered. Just before the evaluation step is
performed, a line is displayed (in the same format as @code{trace})
which indicates the expression that is being evaluated. If the
evaluation step produces a result, the result is also displayed on
another line. A nested REPL is then entered after displaying a message
which describes the next step of the computation. This command can
only be used to continue a computation that was stopped due to a user
interrupt, breakpoint or a single-step.
@item ,l
@cmindex ,l
This command is similar to @samp{,s} except that it ``leaps'' over
procedure calls, that is procedure calls are treated like a single step.
Single-stepping mode will resume when the procedure call returns, or if
and when the execution of the called procedure encounters a breakpoint.
@item ,@var{N}
@cmindex ,@var{N}
Move to frame number @var{N} of the continuation. After changing the
current frame, a one-line summary of the frame is displayed as if the
@samp{,y} command was entered.
@item ,@var{N}+
@cmindex ,@var{N}+
Move forward by @var{N} frames in the chain of continuation frames
(i.e. towards older continuation frames). After changing the current
frame, a one-line summary of the frame is displayed as if the
@samp{,y} command was entered.
@item ,@var{N}-
@cmindex ,@var{N}-
Move backward by @var{N} frames in the chain of continuation frames
(i.e. towards more recent continuation frames). After changing the
current frame, a one-line summary of the frame is displayed as if the
@samp{,y} command was entered.
@item ,+
@cmindex ,+
Equivalent to @samp{,1+}.
@item ,-
@cmindex ,-
Equivalent to @samp{,1-}.
@item ,++
@cmindex ,++
Equivalent to @samp{,@var{N}+} where @var{N} is the number of
continuation frames displayed at the head of a backtrace.
@item ,--
@cmindex ,--
Equivalent to @samp{,@var{N}-} where @var{N} is the number of
continuation frames displayed at the head of a backtrace.
@item ,y
@cmindex ,y
Display a one-line summary of the current frame. The information is
displayed in four fields. The first field is the frame number. The
second field is the procedure that created the frame or
@samp{(interaction)} if the frame was created by an expression entered
at the REPL. The remaining fields describe the subproblem associated
with the frame, that is the expression whose value is being computed.
The third field is the location of the subproblem's source code and
the fourth field is a reproduction of the source code, possibly
truncated to fit on the line. The last two fields may be missing if
that information is not available. In particular, the third field is
missing when the frame was created by a user call to the @samp{eval}
procedure or by a compiled procedure not compiled with the declaration
@samp{debug-location}, and the last field is missing when the frame
was created by a compiled procedure not compiled with the declaration
@samp{debug-source}.
@item ,b
@cmindex ,b
Display a backtrace summarizing each frame in the chain of continuation
frames starting with the current frame. For each frame, the same
information as for the @samp{,y} command is displayed (except that
location information is displayed in the format
@samp{@var{stream}@@@var{line}:@var{column}}). If there are more than 15
frames in the chain of continuation frames, some of the middle frames
will be omitted.
@item ,be
@cmindex ,be
Like the @samp{,b} command but also display the environment.
@item ,bed
@cmindex ,bed
Like the @samp{,be} command but also display the dynamic environment.
@item ,(b @var{expr})
@cmindex ,(b @var{expr})
Display the backtrace of @var{expr}'s value, @var{X}, which is
obtained by evaluating @var{expr} in the current frame. @var{X} must
be a continuation or a thread. When @var{X} is a continuation, the
frames in that continuation are displayed. When @var{X} is a thread,
the backtrace of the current continuation of that thread is displayed.
@item ,(be @var{expr})
@cmindex ,(be @var{expr})
Like the @samp{,(b @var{expr})} command but also display the
environment.
@item ,(bed @var{expr})
@cmindex ,(bed @var{expr})
Like the @samp{,(be @var{expr})} command but also display the dynamic
environment.
@item ,i
@cmindex ,i
Pretty print the procedure that created the current frame or
@samp{(interaction)} if the frame was created by an expression entered
at the REPL. Compiled procedures will only be pretty printed when
they are compiled with the declaration @samp{debug-source}.
@item ,e
@cmindex ,e
Display the environment which is accessible from the current frame.
The lexical environment is displayed, followed by the dynamic
environment if the parameter object
@code{repl-display-dynamic-environment?} is not false. Global lexical
variables are not displayed. Moreover the frame must have been
created by interpreted code or code compiled with the declaration
@samp{debug-environments}. Due to space safety
considerations and compiler optimizations, some of the lexical
variable bindings may be missing. Lexical variable bindings are
displayed using the format @samp{@var{variable} = @var{expression}}
(when @var{variable} is mutable) or @samp{@var{variable} == @var{expression}}
(when @var{variable} is immutable, which may happen in compiled code
due to compiler optimization)
and dynamically-bound parameter bindings are displayed using the
format @samp{(@var{parameter}) = @var{expression}}. Note that
@var{expression} can be a self-evaluating expression (number, string,
boolean, character, ...), a quoted expression, a lambda expression or
a global variable (the last two cases, which are only used when the
value of the variable or parameter is a procedure, simplifies the
debugging of higher-order procedures). A @var{parameter} can be a
quoted expression or a global variable. Lexical bindings are
displayed in inverse binding order (most deeply nested first) and
shadowed variables are included in the list.
@item ,ed
@cmindex ,ed
Like the @samp{,e} command but the dynamic environment is always
displayed.
@item ,(e @var{expr})
@cmindex ,(e @var{expr})
Display the environment of @var{expr}'s value, @var{X}, which is
obtained by evaluating @var{expr} in the current frame. @var{X} must
be a continuation, a thread, a procedure, or a nonnegative integer.
When @var{X} is a continuation, the environment at that point in the
code is displayed. When @var{X} is a thread, the environment of the
current continuation of that thread is displayed. When @var{X} is a
procedure, the lexical environment where @var{X} was created is
combined with the current continuation and this combined environment
is displayed. When @var{X} is an integer, the environment at frame
number @var{X} of the continuation is displayed.
@item ,(ed @var{expr})
@cmindex ,(ed @var{expr})
Like the @samp{,(e @var{expr})} command but the dynamic environment is
always displayed.
@item ,st
@cmindex ,st
Display the state of the threads in the current thread's thread group.
A thread can be: uninitialized, initialized, active, and
terminated (normally or abnormally). Active threads can be
running, sleeping and waiting on a synchronization object
(mutex, condition variable or port) possibly with a timeout.
@item ,(st @var{expr})
@cmindex ,(st @var{expr})
Display the state of a specific thread or thread group.
The value of @var{expr} must be a thread or thread group.
@item ,(v @var{expr})
@cmindex ,(v @var{expr})
Start a new REPL visiting @var{expr}'s value, @var{X}, which is
obtained by evaluating @var{expr} in the current frame. @var{X} must
be a continuation, a thread, a procedure, or a nonnegative integer.
When @var{X} is a continuation, the new REPL's continuation is @var{X}
and evaluations are done in the environment at that point in the code.
When @var{X} is a thread, the thread is interrupted and the new REPL's
continuation is the point where the thread was interrupted. When
@var{X} is a procedure, the lexical environment where @var{X} was
created is combined with the current continuation and evaluations are
done in this combined environment. When @var{X} is an integer, the
REPL is started in frame number @var{X} of the continuation.
@end table
@node Debugging example, Procedures related to debugging, Debugging commands, Debugging
@section Debugging example
Here is a sample interaction with @code{gsi}:
@smallexample
$ @b{gsi}
Gambit @value{VERSION}
> @b{(define (invsqr x) (/ 1 (expt x 2)))}
> @b{(define (mymap fn lst)
(define (mm in)
(if (null? in)
'()
(cons (fn (car in)) (mm (cdr in)))))
(mm lst))}
> @b{(mymap invsqr '(5 2 hello 9 1))}
*** ERROR IN invsqr, (console)@@1.25 -- (Argument 1) NUMBER expected
(expt 'hello 2)
1> @b{,i}
#<procedure #2 invsqr> =
(lambda (x) (/ 1 (expt x 2)))
1> @b{,e}
x = 'hello
1> @b{,b}
0 invsqr (console)@@1:25 (expt x 2)
1 #<procedure #4> (console)@@6:17 (fn (car in))
2 #<procedure #4> (console)@@6:31 (mm (cdr in))
3 #<procedure #4> (console)@@6:31 (mm (cdr in))
4 (interaction) (console)@@8:1 (mymap invsqr '(5 2 hel...
1> @b{,+}
1 #<procedure #4> (console)@@6.17 (fn (car in))
1\1> @b{(pp #4)}
(lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
1\1> @b{,e}
in = '(hello 9 1)
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\1> @b{,(e mm)}
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\1> @b{fn}
#<procedure #2 invsqr>
1\1> @b{(pp fn)}
(lambda (x) (/ 1 (expt x 2)))
1\1> @b{,+}
2 #<procedure #4> (console)@@6.31 (mm (cdr in))
1\2> @b{,e}
in = '(2 hello 9 1)
mm = (lambda (in) (if (null? in) '() (cons (fn (car in)) (mm (cdr in)))))
fn = invsqr
lst = '(5 2 hello 9 1)
1\2> @b{,(c (list 3 4 5))}
(1/25 1/4 3 4 5)
> @b{,q}
@end smallexample
@node Procedures related to debugging, Console line-editing, Debugging example, Debugging
@section Procedures related to debugging
@deffn procedure help @var{subject}
@deffnx procedure help-browser @r{[}@var{new-value}@r{]}
The @code{help} procedure displays the section of the Gambit manual
with the definition of the procedure or special form @var{subject},
which must be a procedure or symbol. For example the call @code{(help
gensym)} will show the section documenting the @code{gensym} procedure
and the call @code{(help 'time)} will show the section documenting the
@code{time} special form. The @code{help} procedure returns the void
object.
The parameter object @code{help-browser} is bound to a string naming
the external program that is used by the @code{help} procedure to view
the documentation. Initially it is bound to the empty string. In
normal circumstances when @code{help-browser} is bound to an empty
string the @code{help} procedure runs the script
@code{~~bin/gambc-doc.bat} which searches for a suitable web browser
to open the documentation in HTML format. Unless the system was built
with the command @samp{configure --enable-help-browser=...}, the
text-only browser @samp{lynx} (see @uref{http://lynx.isc.org/}) will
be used by default if it is available. We highly recommend that you
install this browser if you are interested in viewing the
documentation within the console in which the REPL is running. You
can exit @samp{lynx} conveniently by typing an end of file (usually
@key{^D}).
For example:
@smallexample
> @b{(help-browser "firefox")} @r{@i{; use firefox instead of lynx}}
> @b{(help 'gensym)}
> @b{(help gensym)} @r{@i{; OK because gensym is a procedure}}
> @b{(help 'time)}
> @b{(help time)} @r{@i{; not OK because time is a special form}}
*** ERROR IN (console)@@5.7 -- Macro name can't be used as a variable: time
>
@end smallexample
@end deffn
@deffn procedure repl-result-history-ref @var{i}
@deffnx procedure repl-result-history-max-length-set! @var{n}
@cindex #
@cindex ##
The REPL keeps a history of the last few results printed by the
REPL. The call @code{(repl-result-history-ref @var{i})} returns the
@var{i}th previous result (the last for @var{i}=0, the next to last
for @var{i}=1, etc). By default the REPL result history remembers up
to 3 results. The maximal length of the history can be set to @var{n}
between 0 and 10 by a call to
@code{(repl-result-history-max-length-set! @var{n})}.
For convenience the reader defines an abbreviation for calling
@code{repl-result-history-ref}. Tokens formed by a sequence of one or
more hash signs, such as @samp{@code{#}}, @samp{@code{##}}, etc, are
expanded by the reader into the list @code{(repl-result-history-ref
@var{i})}, where @var{i} is the number of hash signs minus 1. In
other words, @samp{@code{#}} will return the last result printed by
the REPL, @samp{@code{##}} will return the next to last, etc.
For example:
@smallexample
> @b{(map (lambda (x) (* x x)) '(1 2 3))}
(1 4 9)
> @b{(reverse #)}
(9 4 1)
> @b{(append # ##)}
(9 4 1 1 4 9)
> @b{1}
1
> @b{1}
1
> @b{(+ # ##)}
2
> @b{(+ # ##)}
3
> @b{(+ # ##)}
5
> @b{####}
*** ERROR IN (console)@@9.1 -- (Argument 1) Out of range
(repl-result-history-ref 3)
1>
@end smallexample
@end deffn
@deffn procedure trace @var{proc}@dots{}
@deffnx procedure untrace @var{proc}@dots{}
The @code{trace} procedure starts tracing calls to the specified
procedures. When a traced procedure is called, a line containing the
procedure and its arguments is displayed (using the procedure call
expression syntax). The line is indented with a sequence of vertical
bars which indicate the nesting depth of the procedure's continuation.
After the vertical bars is a greater-than sign which indicates that
the evaluation of the call is starting.
When a traced procedure returns a result, it is displayed with the same
indentation as the call but without the greater-than sign. This makes
it easy to match calls and results (the result of a given call is the
value at the same indentation as the greater-than sign). If a traced
procedure P1 performs a tail call to a traced procedure P2, then P2 will
use the same indentation as P1. This makes it easy to spot tail calls.
The special handling for tail calls is needed to preserve the space
complexity of the program (i.e. tail calls are implemented as required
by Scheme even when they involve traced procedures).
The @code{untrace} procedure stops tracing calls to the specified
procedures. When no argument is passed to the @code{trace}
procedure, the list of procedures currently being traced is returned.
The void object is returned by the @code{trace} procedure when it is
passed one or more arguments. When no argument is passed to the
@code{untrace} procedure stops all tracing and returns the void
object. A compiled procedure may be traced but only if it is bound to
a global variable.
For example:
@smallexample
> @b{(define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))}
> @b{(trace fact)}
> @b{(fact 5)}
| > (fact 5)
| | > (fact 4)
| | | > (fact 3)
| | | | > (fact 2)
| | | | | > (fact 1)
| | | | | 1
| | | | 2
| | | 6
| | 24
| 120
120
> @b{(trace -)}
*** WARNING -- Rebinding global variable "-" to an interpreted procedure
> @b{(define (fact-iter n r) (if (< n 2) r (fact-iter (- n 1) (* n r))))}
> @b{(trace fact-iter)}
> @b{(fact-iter 5 1)}
| > (fact-iter 5 1)
| | > (- 5 1)
| | 4
| > (fact-iter 4 5)
| | > (- 4 1)
| | 3
| > (fact-iter 3 20)
| | > (- 3 1)
| | 2
| > (fact-iter 2 60)
| | > (- 2 1)
| | 1
| > (fact-iter 1 120)
| 120
120
> @b{(trace)}
(#<procedure #2 fact-iter> #<procedure #3 -> #<procedure #4 fact>)
> @b{(untrace)}
> @b{(fact 5)}
120
@end smallexample
@end deffn
@deffn procedure step
@deffnx procedure step-level-set! @var{level}
The @code{step} procedure enables single-stepping mode. After the call
to @code{step} the computation will stop just before the interpreter
executes the next evaluation step (as defined by
@code{step-level-set!}). A nested REPL is then started. Note that
because single-stepping is stopped by the REPL whenever the prompt is
displayed it is pointless to enter @code{(step)} by itself. On the
other hand entering @code{(begin (step) @var{expr})} will evaluate
@var{expr} in single-stepping mode.
The procedure @code{step-level-set!} sets the stepping level which
determines the granularity of the evaluation steps when single-stepping
is enabled. The stepping level @var{level} must be an exact integer in
the range 0 to 7. At a level of 0, the interpreter ignores
single-stepping mode. At higher levels the interpreter stops the
computation just before it performs the following operations, depending
on the stepping level:
@enumerate
@item
procedure call
@c @item
@c @code{future} special form and operations at lower levels
@item
@code{delay} special form and operations at lower levels
@item
@code{lambda} special form and operations at lower levels
@item
@code{define} special form and operations at lower levels
@item
@code{set!} special form and operations at lower levels
@item
variable reference and operations at lower levels
@item
constant reference and operations at lower levels
@end enumerate
The default stepping level is 7.
For example:
@smallexample
> @b{(define (fact n) (if (< n 2) 1 (* n (fact (- n 1)))))}
> @b{(step-level-set! 1)}
> @b{(begin (step) (fact 5))}
*** STOPPED IN (console)@@3.15
1> @b{,s}
| > (fact 5)
*** STOPPED IN fact, (console)@@1.22
1> @b{,s}
| | > (< n 2)
| | #f
*** STOPPED IN fact, (console)@@1.43
1> @b{,s}
| | > (- n 1)
| | 4
*** STOPPED IN fact, (console)@@1.37
1> @b{,s}
| | > (fact (- n 1))
*** STOPPED IN fact, (console)@@1.22
1> @b{,s}
| | | > (< n 2)
| | | #f
*** STOPPED IN fact, (console)@@1.43
1> @b{,s}
| | | > (- n 1)
| | | 3
*** STOPPED IN fact, (console)@@1.37
1> @b{,l}
| | | > (fact (- n 1))
*** STOPPED IN fact, (console)@@1.22
1> @b{,l}
| | > (* n (fact (- n 1)))
| | 24
*** STOPPED IN fact, (console)@@1.32
1> @b{,l}
| > (* n (fact (- n 1)))
| 120
120
@end smallexample
@end deffn
@deffn procedure break @var{proc}@dots{}
@deffnx procedure unbreak @var{proc}@dots{}
The @code{break} procedure places a breakpoint on each of the
specified procedures. When a procedure is called that has a
breakpoint, the interpreter will enable single-stepping mode (as if
@code{step} had been called). This typically causes the computation
to stop soon inside the procedure if the stepping level is high
enough.
The @code{unbreak} procedure removes the breakpoints on the specified
procedures. With no argument, @code{break} returns the list of
procedures currently containing breakpoints. The void object is
returned by @code{break} if it is passed one or more arguments. With
no argument @code{unbreak} removes all the breakpoints and returns the
void object. A breakpoint can be placed on a compiled procedure but
only if it is bound to a global variable.
For example:
@smallexample
> @b{(define (double x) (+ x x))}
> @b{(define (triple y) (- (double (double y)) y))}
> @b{(define (f z) (* (triple z) 10))}
> @b{(break double)}
> @b{(break -)}
*** WARNING -- Rebinding global variable "-" to an interpreted procedure
> @b{(f 5)}
*** STOPPED IN double, (console)@@1.21
1> @b{,b}
0 double (console)@@1:21 +
1 triple (console)@@2:31 (double y)
2 f (console)@@3:18 (triple z)
3 (interaction) (console)@@6:1 (f 5)
1> @b{,e}
x = 5
1> @b{,c}
*** STOPPED IN double, (console)@@1.21
1> @b{,c}
*** STOPPED IN f, (console)@@3.29
1> @b{,c}
150
> @b{(break)}
(#<procedure #3 -> #<procedure #4 double>)
> @b{(unbreak)}
> @b{(f 5)}
150
@end smallexample
@end deffn
@deffn procedure generate-proper-tail-calls @r{[}@var{new-value}@r{]}
@cindex proper tail-calls
@cindex tail-calls
[Note: this procedure is DEPRECATED and will be removed
in a future version of Gambit. Use the @samp{proper-tail-calls}
declaration instead.]
The parameter object @code{generate-proper-tail-calls} is bound to a
boolean value controlling how the interpreter handles tail calls.
When it is bound to @code{#f} the interpreter will treat tail calls
like nontail calls, that is a new continuation will be created for the
call. This setting is useful for debugging, because when a primitive
signals an error the location information will point to the call site
of the primitive even if this primitive was called with a tail call.
The initial value of this parameter object is @code{#t}, which means
that a tail call will reuse the continuation of the calling function.
This parameter object only affects code that is subsequently processed
by @code{load} or @code{eval}, or entered at the REPL.
For example:
@smallexample
> @b{(generate-proper-tail-calls)}
#t
> @b{(let loop ((i 1)) (if (< i 10) (loop (* i 2)) oops))}
*** ERROR IN #<procedure #2>, (console)@@2.47 -- Unbound variable: oops
1> @b{,b}
0 #<procedure #2> (console)@@2:47 oops
1 (interaction) (console)@@2:1 ((letrec ((loop (lambda...
1> @b{,t}
> @b{(generate-proper-tail-calls #f)}
> @b{(let loop ((i 1)) (if (< i 10) (loop (* i 2)) oops))}
*** ERROR IN #<procedure #3>, (console)@@6.47 -- Unbound variable: oops
1> @b{,b}
0 #<procedure #3> (console)@@6:47 oops
1 #<procedure #3> (console)@@6:32 (loop (* i 2))
2 #<procedure #3> (console)@@6:32 (loop (* i 2))
3 #<procedure #3> (console)@@6:32 (loop (* i 2))
4 #<procedure #3> (console)@@6:32 (loop (* i 2))
5 (interaction) (console)@@6:1 ((letrec ((loop (lambda...
@end smallexample
@end deffn
@deffn procedure display-environment-set! @var{display?}
[Note: this procedure is DEPRECATED and will be removed
in a future version of Gambit. Use the parameter object
@code{repl-display-environment?} instead.]
This procedure sets a flag that controls the automatic display of the
environment by the REPL. If @var{display?} is true, the environment
is displayed by the REPL before the prompt. The default setting is
not to display the environment.
@end deffn
@deffn procedure repl-display-environment? @var{display?}
The parameter object @code{repl-display-environment?} is bound to a
boolean value that controls the automatic display of the environment
by the REPL. If @var{display?} is true, the environment is displayed
by the REPL before the prompt. This is particularly useful in
single-stepping mode. The default setting is not to display the
environment.
@end deffn
@deffn procedure display-dynamic-environment? @var{display?}
The parameter object @code{display-dynamic-environment?} is bound to a
boolean value that controls wether the dynamic environment is
displayed when the environment is displayed. The default setting is
not to display the dynamic environment.
@end deffn
@deffn procedure pretty-print @var{obj} @r{[}@var{port}@r{]}
This procedure pretty-prints @var{obj} on the port @var{port}. If it
is not specified, @var{port} defaults to the current output-port.
For example:
@smallexample
> @b{(pretty-print
(let* ((x '(1 2 3 4)) (y (list x x x))) (list y y y)))}
(((1 2 3 4) (1 2 3 4) (1 2 3 4))
((1 2 3 4) (1 2 3 4) (1 2 3 4))
((1 2 3 4) (1 2 3 4) (1 2 3 4)))
@end smallexample
@end deffn
@deffn procedure pp @var{obj} @r{[}@var{port}@r{]}
This procedure pretty-prints @var{obj} on the port @var{port}. When
@var{obj} is a procedure created by the interpreter or a procedure
created by code compiled with the declaration
@samp{debug-source}, the procedure's source code is
displayed. If it is not specified, @var{port} defaults to the
interaction channel (i.e. the output will appear at the REPL).
For example:
@smallexample
> @b{(define (f g) (+ (time (g 100)) (time (g 1000))))}
> @b{(pp f)}
(lambda (g)
(+ (##time (lambda () (g 100)) '(g 100))
(##time (lambda () (g 1000)) '(g 1000))))
@end smallexample
@end deffn
@deffn procedure gc-report-set! @var{report?}
@cindex GC
This procedure controls the generation of reports during garbage
collections. If the argument is true, a brief report of memory usage
is generated after every garbage collection. It contains: the time
taken for this garbage collection, the amount of memory allocated in
megabytes since the program was started, the size of the heap in
megabytes, the heap memory in megabytes occupied by live data, the
proportion of the heap occupied by live data, and the number of bytes
occupied by movable and nonmovable objects.
@end deffn
@node Console line-editing, Emacs interface, Procedures related to debugging, Debugging
@section Console line-editing
The console implements a simple Scheme-friendly line-editing
user-interface that is enabled by default. It offers parentheses
balancing, a history of previous commands, symbol completion, and
several emacs-compatible keyboard commands. The user's input is
displayed in a bold font and the output produced by the system is in a
plain font. The history of previous commands is saved in the file
@file{~/.gambc_history}. It is restored when a REPL is started.
Symbol completion is triggered with the tab key. When the cursor is
after a sequence of characters that can form a symbol, typing the tab
key will search the symbol table for the first symbol (in alphabetical
order) that begins with that sequence and insert that symbol. Typing
the tab key in succession will cycle through all symbols with that
prefix. When all possible symbols have been shown or there are no
possible completions, the text reverts to the uncompleted symbol and
the bell is rung.
Here are the keyboard commands available (where the @samp{@code{M-}}
prefix means the escape key is typed and the @samp{@code{C-}} prefix
means the control key is pressed):
@table @code
@item C-d
Generate an end-of-file when the line is empty, otherwise delete
character at cursor.
@item delete @r{or backspace}
Delete character before cursor.
@item M-C-d
Delete word forward and keep a copy of this text on the clipboard.
@item M-delete
Delete word backward and keep a copy of this text on the clipboard.
@item M-backspace
Delete S-expression backward and keep a copy of this text on the clipboard.
@item C-a
Move cursor to beginning of line.
@item C-e
Move cursor to end of line.
@item C-b @r{or @i{left-arrow}}
Move cursor left one character.
@item M-b
Move cursor left one word.
@item M-C-b @r{or @code{M-}@i{left-arrow}}
Move cursor left one S-expression.
@item C-f @r{or @i{right-arrow}}
Move cursor right one character.
@item M-f
Move cursor right one word.
@item M-C-f @r{or @code{M-}@i{right-arrow}}
Move cursor right one S-expression.
@item C-p @r{or @code{M-p} or @i{up-arrow}}
Move to previous line in history.
@item C-n @r{or @code{M-n} or @i{down-arrow}}
Move to next line in history.
@item C-t
Transpose character at cursor with previous character.
@item M-t
Transpose word after cursor with previous word.
@item M-C-t
Transpose S-expression after cursor with previous S-expression.
@item C-l
Clear console and redraw line being edited.
@item C-@i{nul}
Set the mark to the cursor.
@item C-w
Delete the text between the cursor and the mark and keep a copy
of this text on the clipboard.
@item C-k
Delete the text from the cursor to the end of the line and keep a copy
of this text on the clipboard.
@item C-y
Paste the text that is on the clipboard.
@item F8
Same as typing @samp{#||#,c;} (REPL command to continue the computation).
@item F9
Same as typing @samp{#||#,-;} (REPL command to move to newer frame).
@item F10
Same as typing @samp{#||#,+;} (REPL command to move to older frame).
@item F11
Same as typing @samp{#||#,s;} (REPL command to step the computation).
@item F12
Same as typing @samp{#||#,l;} (REPL command to leap the computation).
@end table
On Mac OS X, depending on your configuration, you may have to press
the @code{fn} key to access the function key @code{F12} and the
@code{option} key to access the other function keys.
On Microsoft Windows the clipboard is the system clipboard. This
allows text to be copied and pasted between the program and other
applications. On other operating systems the clipboard is internal to
the program (it is not integrated with the operating system).
@node Emacs interface, GUIDE, Console line-editing, Debugging
@section Emacs interface
@cindex Emacs
@cindex gambit.el
Gambit comes with the Emacs package @samp{gambit.el} which provides a
nice environment for running Gambit from within the Emacs editor.
This package filters the standard output of the Gambit process and
when it intercepts a location information (in the format
@samp{@var{stream}@@@var{line}.@var{column}} where @var{stream} is
either @samp{(stdin)} when the expression was obtained from standard
input, @samp{(console)} when the expression was obtained from the
console, or a string naming a file) it opens a window to highlight the
corresponding expression.
To use this package, make sure the file @samp{gambit.el} is accessible
from your load-path and that the following lines are in your
@samp{.emacs} file:
@smallexample
@b{}(autoload 'gambit-inferior-mode "gambit" "Hook Gambit mode into cmuscheme.")
(autoload 'gambit-mode "gambit" "Hook Gambit mode into scheme.")
(add-hook 'inferior-scheme-mode-hook (function gambit-inferior-mode))
(add-hook 'scheme-mode-hook (function gambit-mode))
(setq scheme-program-name "gsi -:d-")
@end smallexample
Alternatively, if you don't mind always loading this package,
you can simply add this line to your @samp{.emacs} file:
@smallexample
@b{}(require 'gambit)
@end smallexample
You can then start an inferior Gambit process by typing @samp{M-x
run-scheme}. The commands provided in @samp{cmuscheme} mode will be
available in the Gambit interaction buffer (i.e. @samp{*scheme*}) and in
buffers attached to Scheme source files. Here is a list of the most
useful commands (for a complete list type @samp{C-h m} in the Gambit
interaction buffer):
@table @code
@item C-x C-e
Evaluate the expression which is before the cursor (the expression will
be copied to the Gambit interaction buffer).
@item C-c C-z
Switch to Gambit interaction buffer.
@item C-c C-l
Load a file (file attached to current buffer is default) using
@code{(load @var{file})}.
@item C-c C-k
Compile a file (file attached to current buffer is default) using
@code{(compile-file @var{file})}.
@end table
The file @samp{gambit.el} provides these additional commands:
@table @code
@item F8 @r{@i{or}} C-c c
Continue the computation (same as typing @samp{#||#,c;} to the REPL).
@item F9 @r{@i{or}} C-c ]
Move to newer frame (same as typing @samp{#||#,-;} to the REPL).
@item F10 @r{@i{or}} C-c [
Move to older frame (same as typing @samp{#||#,+;} to the REPL).
@item F11 @r{@i{or}} C-c s
Step the computation (same as typing @samp{#||#,s;} to the REPL).
@item F12 @r{@i{or}} C-c l
Leap the computation (same as typing @samp{#||#,l;} to the REPL).
@item C-c _
Removes the last window that was opened to highlight an expression.
@end table
The two keystroke version of these commands can be shortened to
@samp{M-c}, @samp{M-[}, @samp{M-]}, @samp{M-s}, @samp{M-l}, and
@samp{M-_} respectively by adding this line to your @samp{.emacs}
file:
@smallexample
@b{}(setq gambit-repl-command-prefix "\e")
@end smallexample
This is more convenient to type than the two keystroke @samp{C-c} based
sequences but the purist may not like this because it does not follow
normal Emacs conventions.
Here is what a typical @samp{.emacs} file will look like:
@smallexample
@b{}(setq load-path ; add directory containing gambit.el
(cons "/usr/local/Gambit-C/share/emacs/site-lisp"
load-path))
(setq scheme-program-name "/tmp/gsi -:d-") ; if gsi not in executable path
(setq gambit-highlight-color "gray") ; if you don't like the default
(setq gambit-repl-command-prefix "\e") ; if you want M-c, M-s, etc
(require 'gambit)
@end smallexample
@node GUIDE, , Emacs interface, Debugging
@section GUIDE
The implementation and documentation for GUIDE, the Gambit Universal
IDE, are not yet complete.
@node Scheme extensions, Namespaces, Debugging, Top
@chapter Scheme extensions
@menu
* Extensions to standard procedures:: Extensions to standard procedures
* Extensions to standard special forms:: Extensions to standard special forms
* Miscellaneous extensions:: Miscellaneous extensions
* Undocumented extensions:: Undocumented extensions
@end menu
@node Extensions to standard procedures, Extensions to standard special forms, Scheme extensions, Scheme extensions
@section Extensions to standard procedures
@deffn procedure transcript-on @var{file}
@deffnx procedure transcript-off
These procedures do nothing.
@end deffn
@deffn procedure call-with-current-continuation @var{proc}
@deffnx procedure call/cc @var{proc}
The procedure @code{call-with-current-continuation} is bound to the
global variables @code{call-with-current-continuation} and
@code{call/cc}.
@end deffn
@node Extensions to standard special forms, Miscellaneous extensions, Extensions to standard procedures, Scheme extensions
@section Extensions to standard special forms
@deffn {special form} lambda @r{@i{lambda-formals}} @r{@i{body}}
@deffnx {special form} define (@r{@i{variable}} @r{@i{define-formals}}) @r{@i{body}}
@itemize @var{ }
@item
@i{lambda-formals} = @code{(} @i{formal-argument-list} @code{)} | @i{r4rs-lambda-formals}
@item
@i{define-formals} = @i{formal-argument-list} | @i{r4rs-define-formals}
@item
@i{formal-argument-list} = @i{dsssl-formal-argument-list} | @i{rest-at-end-formal-argument-list}
@item
@i{dsssl-formal-argument-list} = @i{reqs} @i{opts} @i{rest} @i{keys}
@item
@i{rest-at-end-formal-argument-list} = @i{reqs} @i{opts} @i{keys} @i{rest} | @i{reqs} @i{opts} @i{keys} @code{.} @i{rest-formal-argument}
@item
@i{reqs} = @i{required-formal-argument}*
@item
@i{required-formal-argument} = @i{variable}
@item
@i{opts} = @code{#!optional} @i{optional-formal-argument}* | @i{empty}
@item
@i{optional-formal-argument} = @i{variable} | @code{(} @i{variable} @i{initializer} @code{)}
@item
@i{rest} = @code{#!rest} @i{rest-formal-argument} | @i{empty}
@item
@i{rest-formal-argument} = @i{variable}
@item
@i{keys} = @code{#!key} @i{keyword-formal-argument}* | @i{empty}
@item
@i{keyword-formal-argument} = @i{variable} | @code{(} @i{variable} @i{initializer} @code{)}
@item
@i{initializer} = @i{expression}
@item
@i{r4rs-lambda-formals} = @code{(} @i{variable}* @code{)} |
@code{(} @i{variable}+ @code{.} @i{variable} @code{)} |
@i{variable}
@item
@i{r4rs-define-formals} = @i{variable}* | @i{variable}* @code{.} @i{variable}
@end itemize
These forms are extended versions of the @code{lambda} and @code{define}
special forms of standard Scheme. They allow the use of optional formal
arguments, either positional or named, and support the syntax and semantics
of the DSSSL standard.
When the procedure introduced by a @code{lambda} (or @code{define}) is
applied to a list of actual arguments, the formal and actual arguments
are processed as specified in the R4RS if the @i{lambda-formals} (or
@i{define-formals}) is a @i{r4rs-lambda-formals} (or
@i{r4rs-define-formals}).
If the @i{formal-argument-list} matches
@i{dsssl-formal-argument-list} or @i{extended-formal-argument-list}
they are processed as follows:
@enumerate a
@item
@i{Variable}s in @i{required-formal-argument}s are bound to
successive actual arguments starting with the first actual argument. It
shall be an error if there are fewer actual arguments than
@i{required-formal-argument}s.
@item
Next @i{variable}s in @i{optional-formal-argument}s are bound to
remaining actual arguments. If there are fewer remaining actual
arguments than @i{optional-formal-argument}s, then the variables are
bound to the result of evaluating @i{initializer}, if one was
specified, and otherwise to @code{#f}. The @i{initializer} is
evaluated in an environment in which all previous formal arguments have
been bound.
@item
If @code{#!key} does not appear in the @i{formal-argument-list}
and there is no @i{rest-formal-argument} then it shall be an error
if there are any remaining actual arguments.
@item
If @code{#!key} does not appear in the @i{formal-argument-list}
and there is a @i{rest-formal-argument} then the
@i{rest-formal-argument} is bound to a list of all remaining actual
arguments.
@item
If @code{#!key} appears in the @i{formal-argument-list} and there is
no @i{rest-formal-argument} then there shall be an even number of
remaining actual arguments. These are interpreted as a series of
pairs, where the first member of each pair is a keyword specifying the
argument name, and the second is the corresponding value. It shall be
an error if the first member of a pair is not a keyword. It shall be
an error if the argument name is not the same as a variable in a
@i{keyword-formal-argument}. If the same argument name occurs more
than once in the list of actual arguments, then the first value is
used. If there is no actual argument for a particular
@i{keyword-formal-argument}, then the variable is bound to the
result of evaluating @i{initializer} if one was specified, and
otherwise to @code{#f}. The @i{initializer} is evaluated in an
environment in which all previous formal arguments have been bound.
@item
If @code{#!key} appears in the @i{formal-argument-list} and there is
a @i{rest-formal-argument} @b{before} the @code{#!key} then there
may be an even or odd number of remaining actual arguments and the
@i{rest-formal-argument} is bound to a list of all remaining actual
arguments. Then, these remaining actual arguments are scanned from
left to right in pairs, stopping at the first pair whose first element
is not a keyword. Each pair whose first element is a keyword matching
the name of a @i{keyword-formal-argument} gives the value (i.e. the
second element of the pair) of the corresponding formal argument. If
the same argument name occurs more than once in the list of actual
arguments, then the first value is used. If there is no actual
argument for a particular @i{keyword-formal-argument}, then the
variable is bound to the result of evaluating @i{initializer} if one
was specified, and otherwise to @code{#f}. The @i{initializer} is
evaluated in an environment in which all previous formal arguments
have been bound.
@item
If @code{#!key} appears in the @i{formal-argument-list} and there is
a @i{rest-formal-argument} @b{after} the @code{#!key} then there may
be an even or odd number of remaining actual arguments. The remaining
actual arguments are scanned from left to right in pairs, stopping at
the first pair whose first element is not a keyword. Each pair shall
have as its first element a keyword matching the name of a
@i{keyword-formal-argument}; the second element gives the value of
the corresponding formal argument. If the same argument name occurs
more than once in the list of actual arguments, then the first value
is used. If there is no actual argument for a particular
@i{keyword-formal-argument}, then the variable is bound to the
result of evaluating @i{initializer} if one was specified, and
otherwise to @code{#f}. The @i{initializer} is evaluated in an
environment in which all previous formal arguments have been bound.
Finally, the @i{rest-formal-argument} is bound to the list of the
actual arguments that were not scanned (i.e. after the last
keyword/value pair).
@end enumerate
In all cases it is an error for a @i{variable} to appear more than
once in a @i{formal-argument-list}.
Note that this specification is compatible with the DSSSL language
standard (i.e. a correct DSSSL program will have the same semantics
when run with Gambit).
It is unspecified whether variables receive their value by binding or by
assignment. Currently the compiler and interpreter use different
methods, which can lead to different semantics if
@code{call-with-current-continuation} is used in an @i{initializer}.
Note that this is irrelevant for DSSSL programs because
@code{call-with-current-continuation} does not exist in DSSSL.
For example:
@smallexample
> @b{((lambda (#!rest x) x) 1 2 3)}
(1 2 3)
> @b{(define (f a #!optional b) (list a b))}
> @b{(define (g a #!optional (b a) #!key (k (* a b))) (list a b k))}
> @b{(define (h1 a #!rest r #!key k) (list a k r))}
> @b{(define (h2 a #!key k #!rest r) (list a k r))}
> @b{(f 1)}
(1 #f)
> @b{(f 1 2)}
(1 2)
> @b{(g 3)}
(3 3 9)
> @b{(g 3 4)}
(3 4 12)
> @b{(g 3 4 k: 5)}
(3 4 5)
> @b{(g 3 4 k: 5 k: 6)}
(3 4 5)
> @b{(h1 7)}
(7 #f ())
> @b{(h1 7 k: 8 9)}
(7 8 (k: 8 9))
> @b{(h1 7 k: 8 z: 9)}
(7 8 (k: 8 z: 9))
> @b{(h2 7)}
(7 #f ())
> @b{(h2 7 k: 8 9)}
(7 8 (9))
> @b{(h2 7 k: 8 z: 9)}
*** ERROR IN (console)@@17.1 -- Unknown keyword argument passed to procedure
(h2 7 k: 8 z: 9)
@end smallexample
@end deffn
@node Miscellaneous extensions, Undocumented extensions, Extensions to standard special forms, Scheme extensions
@section Miscellaneous extensions
@deffn procedure vector-copy @var{vector}
This procedure returns a newly allocated vector with the same content
as the vector @var{vector}. Note that the elements are not
recursively copied.
For example:
@smallexample
> @b{(define v1 '#(1 2 3))}
> @b{(define v2 (vector-copy v1))}
> @b{v2}
#(1 2 3)
> @b{(eq? v1 v2)}
#f
@end smallexample
@end deffn
@deffn procedure subvector @var{vector} @var{start} @var{end}
This procedure is the vector analog of the @code{substring}
procedure. It returns a newly allocated vector formed from the
elements of the vector @var{vector} beginning with index @var{start}
(inclusive) and ending with index @var{end} (exclusive).
For example:
@smallexample
> @b{(subvector '#(a b c d e f) 3 5)}
#(d e)
@end smallexample
@end deffn
@deffn procedure vector-append @var{vector}@dots{}
This procedure is the vector analog of the @code{string-append}
procedure. It returns a newly allocated vector whose elements
form the concatenation of the given vectors.
For example:
@smallexample
> @b{(define v '#(1 2 3))}
> @b{(vector-append v v v)}
#(1 2 3 1 2 3 1 2 3)
@end smallexample
@end deffn
@deffn procedure append-vectors @var{lst}
This procedure returns a newly allocated vector whose elements form
the concatenation of all the vectors in the list @var{lst}. It is
equivalent to @code{(apply vector-append @r{@var{lst}})}.
For example:
@smallexample
> @b{(define v '#(1 2 3))}
> @b{(append-vectors (list v v v))}
#(1 2 3 1 2 3 1 2 3)
@end smallexample
@end deffn
@deffn procedure subvector-fill! @var{vector} @var{start} @var{end} @var{fill}
This procedure is like @code{vector-fill!}, but fills a selected part
of the given vector. It sets the elements of the vector @var{vector},
beginning with index @var{start} (inclusive) and ending with index
@var{end} (exclusive) to @var{fill}. The value returned is
unspecified.
For example:
@smallexample
> @b{(define v (vector 'a 'b 'c 'd 'e 'f))}
> @b{(subvector-fill! v 3 5 'x)}
> @b{v}
#(a b c x x f)
@end smallexample
@end deffn
@deffn procedure subvector-move! @var{src-vector} @var{src-start} @var{src-end} @var{dst-vector} @var{dst-start}
This procedure replaces part of the contents of vector
@var{dst-vector} with part of the contents of vector
@var{src-vector}. It copies elements from @var{src-vector}, beginning
with index @var{src-start} (inclusive) and ending with index
@var{src-end} (exclusive) to @var{dst-vector} beginning with index
@var{dst-start} (inclusive). The value returned is unspecified.
For example:
@smallexample
> @b{(define v1 '#(1 2 3 4 5 6))}
> @b{(define v2 (vector 'a 'b 'c 'd 'e 'f))}
> @b{(subvector-move! v1 3 5 v2 1)}
> @b{v2}
#(a 4 5 d e f)
@end smallexample
@end deffn
@deffn procedure vector-shrink! @var{vector} @var{k}
This procedure shortens the vector @var{vector} so that its new size
is @var{k}. The value returned is unspecified.
For example:
@smallexample
> @b{(define v (vector 'a 'b 'c 'd 'e 'f))}
> @b{v}
#(a b c d e f)
> @b{(vector-shrink! v 3)}
> @b{v}
#(a b c)
@end smallexample
@end deffn
@deffn procedure append-strings @var{lst}
This procedure returns a newly allocated string whose elements form
the concatenation of all the strings in the list @var{lst}. It is
equivalent to @code{(apply string-append @r{@var{lst}})}.
For example:
@smallexample
> @b{(define s "abc")}
> @b{(append-strings (list s s s))}
"abcabcabc"
@end smallexample
@end deffn
@deffn procedure substring-fill! @var{string} @var{start} @var{end} @var{fill}
This procedure is like @code{string-fill!}, but fills a selected part
of the given string. It sets the elements of the string @var{string},
beginning with index @var{start} (inclusive) and ending with index
@var{end} (exclusive) to @var{fill}. The value returned is
unspecified.
For example:
@smallexample
> @b{(define s (string #\a #\b #\c #\d #\e #\f))}
> @b{(substring-fill! s 3 5 #\x)}
> @b{s}
"abcxxf"
@end smallexample
@end deffn
@deffn procedure substring-move! @var{src-string} @var{src-start} @var{src-end} @var{dst-string} @var{dst-start}
This procedure replaces part of the contents of string
@var{dst-string} with part of the contents of string
@var{src-string}. It copies elements from @var{src-string}, beginning
with index @var{src-start} (inclusive) and ending with index
@var{src-end} (exclusive) to @var{dst-string} beginning with index
@var{dst-start} (inclusive). The value returned is unspecified.
For example:
@smallexample
> @b{(define s1 "123456")}
> @b{(define s2 (string #\a #\b #\c #\d #\e #\f))}
> @b{(substring-move! s1 3 5 s2 1)}
> @b{s2}
"a45def"
@end smallexample
@end deffn
@deffn procedure string-shrink! @var{string} @var{k}
This procedure shortens the string @var{string} so that its new size
is @var{k}. The value returned is unspecified.
For example:
@smallexample
> @b{(define s (string #\a #\b #\c #\d #\e #\f))}
> @b{s}
"abcdef"
> @b{(string-shrink! s 3)}
> @b{s}
"abc"
@end smallexample
@end deffn
@deffn procedure box @var{obj}
@deffnx procedure box? @var{obj}
@deffnx procedure unbox @var{box}
@deffnx procedure set-box! @var{box} @var{obj}
@cindex boxes
These procedures implement the @dfn{box} data type. A box is a
cell containing a single mutable field. The lexical syntax
of a box containing the object @var{obj} is @code{#&@var{obj}}
(@pxref{Box syntax}).
The procedure @code{box} returns a new box object whose content is
initialized to @var{obj}. The procedure @code{box?} returns @code{#t}
if @var{obj} is a box, and otherwise returns @code{#f}. The procedure
@code{unbox} returns the content of the box @var{box}. The procedure
@code{set-box!} changes the content of the box @var{box} to @var{obj}.
The procedure @code{set-box!} returns an unspecified value.
For example:
@smallexample
> @b{(define b (box 0))}
> @b{b}
#&0
> @b{(define (inc!) (set-box! b (+ (unbox b) 1)))}
> @b{(inc!)}
> @b{b}
#&1
> @b{(unbox b)}
1
@end smallexample
@end deffn
@deffn procedure keyword? @var{obj}
@deffnx procedure keyword->string @var{keyword}
@deffnx procedure string->keyword @var{string}
@cindex keywords
These procedures implement the @dfn{keyword} data type. Keywords are
similar to symbols but are self evaluating and distinct from the
symbol data type. The lexical syntax of keywords is specified in
@ref{Keyword syntax}.
The procedure @code{keyword?} returns @code{#t} if @var{obj} is a
keyword, and otherwise returns @code{#f}. The procedure
@code{keyword->string} returns the name of @var{keyword} as a string.
The procedure @code{string->keyword} returns the keyword whose name is
@var{string}.
For example:
@smallexample
> @b{(keyword? 'color)}
#f
> @b{(keyword? color:)}
#t
> @b{(keyword->string color:)}
"color"
> @b{(string->keyword "color")}
color:
@end smallexample
@end deffn
@deffn procedure gensym @r{[}@var{prefix}@r{]}
This procedure returns a new @dfn{uninterned symbol}. Uninterned symbols
are guaranteed to be distinct from the symbols generated by the
procedures @code{read} and @code{string->symbol}. The symbol
@var{prefix} is the prefix used to generate the new symbol's name. If
it is not specified, the prefix defaults to @samp{g}.
For example:
@smallexample
> @b{(gensym)}
#:g0
> @b{(gensym)}
#:g1
> @b{(gensym 'star-trek-)}
#:star-trek-2
@end smallexample
@end deffn
@deffn procedure 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{]} debug)
@opindex debug
@opindex -debug
Enable (or disable) the generation of debugging information. The kind
of debugging information that is generated depends on the declarations
@samp{debug-location}, @samp{debug-source}, and
@samp{debug-environments}. If any of the command line options
@samp{-debug}, @samp{-debug-location}, @samp{-debug-source} and
@samp{-debug-environments} are present, the @samp{debug} declaration
is initially enabled, otherwise it is initially disabled. When all
kinds of debugging information are generated there is a substantial
increase in the C compilation time and the size of the generated code.
When compiling a 3000 line Scheme file it was observed that the total
compilation time is 500% longer and the executable code is 150%
bigger.
@item (@r{[}not@r{]} debug-location)
@opindex debug-location
@opindex -debug-location
Select (or deselect) source code location debugging information. When
this declaration and the @samp{debug} declaration are in effect, run
time error messages indicate the location of the error in the source
code file. If any of the command line options @samp{-debug-source}
and @samp{-debug-environments} are present and @samp{-debug-location}
is absent, the @samp{debug-location} declaration is initially
disabled, otherwise it is initially enabled. When compiling a 3000
line Scheme file it was observed that the total compilation time is
200% longer and the executable code is 60% bigger.
@item (@r{[}not@r{]} debug-source)
@opindex debug-source
@opindex -debug-source
Select (or deselect) source code debugging information. When this
declaration and the @samp{debug} declaration are in effect, run time
error messages indicate the source code, the backtraces are more
precise, and the @code{pp} procedure will display the source code of
compiled procedures. If any of the command line options
@samp{-debug-location} and @samp{-debug-environments} are present and
@samp{-debug-source} is absent, the @samp{debug-source} declaration is
initially disabled, otherwise it is initially enabled. When compiling
a 3000 line Scheme file it was observed that the total compilation
time is 90% longer and the executable code is 90% bigger.
@item (@r{[}not@r{]} debug-environments)
@opindex debug-environments
@opindex -debug-environments
Select (or deselect) environment debugging information. When this
declaration and the @samp{debug} declaration are in effect, the
debugger will have access to the environments of the continuations.
In other words the local variables defined in compiled procedures (and
not optimized away by the compiler) will be shown by the @samp{,e}
REPL command. If any of the command line options
@samp{-debug-location} and @samp{-debug-source} are present and
@samp{-debug-environments} is absent, the @samp{debug-environments}
declaration is initially disabled, otherwise it is initially enabled.
When compiling a 3000 line Scheme file it was observed that the total
compilation time is 70% longer and the executable code is 40% bigger.
@item (@r{[}not@r{]} proper-tail-calls)
@opindex proper-tail-calls
@cindex proper tail-calls
@cindex tail-calls
Generate (or don't generate) proper tail calls. When proper tail
calls are turned off, tail calls are handled like non-tail calls, that
is a continuation frame will be created for all calls regardless of
their kind. This is useful for debugging because the caller of a
procedure will be visible in the backtrace produced by the REPL's
@samp{,b} command even when the call is a tail call. Be advised that
this does cause stack space to be consumed for tail calls which may
cause the stack to overflow when performing long iterations with tail
calls (whether they are expressed with a @code{letrec}, named
@code{let}, @code{do}, or other form).
@item (@r{[}not@r{]} optimize-dead-local-variables)
@opindex optimize-dead-local-variables
Remove (or preserve) the dead local variables in the environment.
Preserving the dead local variables is useful for debugging because
continuations will contain the dead variables. Thus, if the code is
also compiled with the declaration @samp{debug-environments}
the @samp{,e}, @samp{,ed}, @samp{,be}, and @samp{,bed} REPL
commands will display the dead variables. On the other hand,
preserving the dead local variables may change the space complexity of
the program (i.e. some of the data that would normally be reclaimed by
the garbage collector will not be). Note that due to other compiler
optimizations some dead local variables may be removed regardless of
this declaration.
@item (@var{number-type} @var{primitive}@dots{})
@opindex generic
@opindex fixnum
@opindex flonum
Numeric arguments and result of the specified primitives are
known to be of the given type (all primitives if none specified).
@var{number-type} can be: @samp{generic}, @samp{fixnum}, or
@samp{flonum}.
@item (@var{mostly-number-type} @var{primitive}@dots{})
@opindex mostly-generic
@opindex mostly-fixnum
@opindex mostly-fixnum-flonum
@opindex mostly-flonum
@opindex mostly-flonum-fixnum
Numeric arguments and result of the specified primitives are expected
to be most often of the given type (all primitives if none specified).
@var{mostly-number-type} can be: @samp{mostly-generic},
@samp{mostly-fixnum}, @samp{mostly-fixnum-flonum},
@samp{mostly-flonum}, or @samp{mostly-flonum-fixnum}.
@end table
The default declarations used by the compiler are equivalent to:
@smallexample
@b{}(declare
(gambit-scheme)
(separate)
(inline)
(inline-primitives)
(inlining-limit 350)
(constant-fold)
(lambda-lift)
(not standard-bindings)
(not extended-bindings)
(run-time-bindings)
(safe)
(interrupts-enabled)
(not debug) ;; depends on debugging command line options
(debug-location) ;; depends on debugging command line options
(debug-source) ;; depends on debugging command line options
(debug-environments) ;; depends on debugging command line options
(proper-tail-calls)
(optimize-dead-local-variables)
(generic)
(mostly-fixnum-flonum)
)
@end smallexample
These declarations are compatible with the semantics of R5RS Scheme
and includes a few procedures from R6RS (mainly fixnum specific and
flonum specific procedures). Typically used declarations that enhance
performance, at the cost of violating the R5RS Scheme semantics, are:
@code{(standard-bindings)}, @code{(block)}, @code{(not safe)} and
@code{(fixnum)}.
@end deffn
@node Undocumented extensions, , Miscellaneous extensions, Scheme extensions
@section Undocumented extensions
The procedures in this section are not yet documented.
@deffn procedure continuation? @var{obj}
@deffnx procedure continuation-capture @var{proc}
@deffnx procedure continuation-graft @var{cont} @var{proc} @var{obj}@dots{}
@deffnx procedure continuation-return @var{cont} @var{obj}@dots{}
These procedures provide access to internal first-class continuations
which are represented using continuation objects distinct from procedures.
The procedure @code{continuation?} returns @code{#t} when @var{obj} is
a continuation object and @code{#f} otherwise.
The procedure @code{continuation-capture} is similar to the
@code{call/cc} procedure but it represents the continuation with a
continuation object. The @var{proc} parameter must be a procedure
accepting a single argument. The procedure
@code{continuation-capture} reifies its continuation and calls
@var{proc} with the corresponding continuation object as its sole
argument. Like for @code{call/cc}, the implicit continuation of the
call to @var{proc} is the implicit continuation of the call to
@code{continuation-capture}.
The procedure @code{continuation-graft} performs a procedure call to
the procedure @var{proc} with arguments @var{obj}@dots{} and the
implicit continuation corresponding to the continuation object
@var{cont}. The current continuation of the call to procedure
@code{continuation-graft} is ignored.
The procedure @code{continuation-return} invokes the implicit
continuation corresponding to the continuation object @var{cont} with
the result(s) @var{obj}@dots{}. This procedure can be easily
defined in terms of @code{continuation-graft}:
@smallexample
(define (continuation-return cont . objs)
(continuation-graft (lambda () (apply values objs))))
@end smallexample
For example:
@smallexample
> @b{(define x #f)}
> @b{(define p (make-parameter 11))}
> @b{(pp (parameterize ((p 22))
(cons 33 (continuation-capture
(lambda (c) (set! x c) 44)))))}
(33 . 44)
> @b{x}
#<continuation #2>
> @b{(continuation-return x 55)}
(33 . 55)
> @b{(continuation-graft x (lambda () (expt 2 10)))}
(33 . 1024)
> @b{(continuation-graft x expt 2 10)}
(33 . 1024)
> @b{(continuation-graft x (lambda () (p)))}
(33 . 22)
> @b{(define (map-sqrt1 lst)
(call/cc
(lambda (k)
(map (lambda (x)
(if (< x 0)
(k 'error)
(sqrt x)))
lst))))}
> @b{(map-sqrt1 '(1 4 9))}
(1 2 3)
> @b{(map-sqrt1 '(1 -1 9))}
error
> @b{(define (map-sqrt2 lst)
(continuation-capture
(lambda (c)
(map (lambda (x)
(if (< x 0)
(continuation-return c 'error)
(sqrt x)))
lst))))}
> @b{(map-sqrt2 '(1 4 9))}
(1 2 3)
> @b{(map-sqrt2 '(1 -1 9))}
error
@end smallexample
@end deffn
@deffn procedure display-exception @var{exc} @r{[}@var{port}@r{]}
@deffnx procedure display-exception-in-context @var{exc} @var{cont} @r{[}@var{port}@r{]}
@deffnx procedure display-procedure-environment @var{proc} @r{[}@var{port}@r{]}
@deffnx procedure display-continuation-environment @var{cont} @r{[}@var{port}@r{]}
@deffnx procedure display-continuation-dynamic-environment @var{cont} @r{[}@var{port}@r{]}
@end deffn
@deffn procedure display-continuation-backtrace @var{cont} @r{[}@var{port} @r{[}@var{all-frames?} @r{[}@var{display-env?} @r{[}@var{max-head} @r{[}@var{max-tail} @r{[}@var{depth}@r{]}@r{]}@r{]}@r{]}@r{]}@r{]}
The procedure @code{display-continuation-backtrace} displays the
frames of the continuation corresponding to the continuation object
@var{cont} on the port @var{port}. If it is not specified, @var{port}
defaults to the current output-port. The frames are displayed in the
same format as the REPL's @samp{,b} command.
The parameter @var{all-frames?}, which defaults to @code{#f}, controls
which frames are displayed. Some frames of ancillary importance, such
as internal frames created by the interpreter, are not displayed when
@var{all-frames?} is @code{#f}. Otherwise all frames are displayed.
The parameter @var{display-env?}, which defaults to @code{#f}, controls
if the frames are displayed with its environment (the variables
accessible and their bindings).
The parameters @var{max-head} and @var{max-tail}, which default to 10
and 4 respectively, control how many frames are displayed at the head
and tail of the continuation.
The parameter @var{depth}, which defaults to 0, causes the frame numbers
to be offset by that value.
For example:
@smallexample
> @b{(define x #f)}
> @b{(define (fib n)
(if (< n 2)
(continuation-capture
(lambda (c) (set! x c) 1))
(+ (fib (- n 1))
(fib (- n 2)))))}
> @b{(fib 10)}
89
> @b{(display-continuation-backtrace x)}
0 fib (console)@@7:12 (fib (- n 2))
1 fib (console)@@7:12 (fib (- n 2))
2 fib (console)@@7:12 (fib (- n 2))
3 fib (console)@@7:12 (fib (- n 2))
4 fib (console)@@7:12 (fib (- n 2))
5 (interaction) (console)@@8:1 (fib 10)
#f
> @b{(display-continuation-backtrace x (current-output-port) #t)}
0 fib (console)@@7:12 (fib (- n 2))
1 fib (console)@@6:9 (+ (fib (- n 1)) (fib (- ...
2 fib (console)@@7:12 (fib (- n 2))
3 fib (console)@@6:9 (+ (fib (- n 1)) (fib (- ...
4 fib (console)@@7:12 (fib (- n 2))
5 fib (console)@@6:9 (+ (fib (- n 1)) (fib (- ...
6 fib (console)@@7:12 (fib (- n 2))
7 fib (console)@@6:9 (+ (fib (- n 1)) (fib (- ...
8 fib (console)@@7:12 (fib (- n 2))
9 fib (console)@@6:9 (+ (fib (- n 1)) (fib (- ...
...
13 ##with-no-result-expected-toplevel
14 ##repl-debug
15 ##repl-debug-main
16 ##kernel-handlers
#f
> @b{(display-continuation-backtrace x (current-output-port) #f #t)}
0 fib (console)@@7:12 (fib (- n 2))
n = 2
1 fib (console)@@7:12 (fib (- n 2))
n = 4
2 fib (console)@@7:12 (fib (- n 2))
n = 6
3 fib (console)@@7:12 (fib (- n 2))
n = 8
4 fib (console)@@7:12 (fib (- n 2))
n = 10
5 (interaction) (console)@@8:1 (fib 10)
#f
> @b{(display-continuation-backtrace x (current-output-port) #f #f 2 1 100)}
100 fib (console)@@7:12 (fib (- n 2))
101 fib (console)@@7:12 (fib (- n 2))
...
105 (interaction) (console)@@8:1 (fib 10)
#f
@end smallexample
@end deffn
@deffn procedure make-thread-group @r{[}@var{name} @r{[}@var{thread-group}@r{]}@r{]}
@deffnx procedure thread-group? @var{obj}
@deffnx procedure thread-group-name @var{thread-group}
@deffnx procedure thread-group-parent @var{thread-group}
@deffnx procedure thread-group-resume! @var{thread-group}
@deffnx procedure thread-group-suspend! @var{thread-group}
@deffnx procedure thread-group-terminate! @var{thread-group}
@deffnx procedure thread-group->thread-group-list @var{thread-group}
@deffnx procedure thread-group->thread-group-vector @var{thread-group}
@deffnx procedure thread-group->thread-list @var{thread-group}
@deffnx procedure thread-group->thread-vector @var{thread-group}
@end deffn
@deffn procedure thread-state @var{thread}
@deffnx procedure thread-state-uninitialized? @var{thread-state}
@deffnx procedure thread-state-initialized? @var{thread-state}
@deffnx procedure thread-state-active? @var{thread-state}
@deffnx procedure thread-state-active-waiting-for @var{thread-state}
@deffnx procedure thread-state-active-timeout @var{thread-state}
@deffnx procedure thread-state-normally-terminated? @var{thread-state}
@deffnx procedure thread-state-normally-terminated-result @var{thread-state}
@deffnx procedure thread-state-abnormally-terminated? @var{thread-state}
@deffnx procedure thread-state-abnormally-terminated-reason @var{thread-state}
@deffnx procedure top @r{[}@var{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 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{]}
@deffnx procedure defer-user-interrupts
@end deffn
@deffn procedure primordial-exception-handler @var{exc}
@end deffn
@deffn procedure err-code->string @var{code}
@end deffn
@deffn procedure foreign? @var{obj}
@deffnx procedure foreign-tags @var{foreign}
@deffnx procedure foreign-address @var{foreign}
@deffnx procedure foreign-release! @var{foreign}
@deffnx procedure foreign-released? @var{foreign}
@end deffn
@deffn procedure invalid-hash-number-exception? @var{obj}
@deffnx procedure invalid-hash-number-exception-procedure @var{exc}
@deffnx procedure invalid-hash-number-exception-arguments @var{exc}
@end deffn
@deffn procedure tcp-client-peer-socket-info @var{tcp-client-port}
@deffnx procedure tcp-client-self-socket-info @var{tcp-client-port}
@end deffn
@deffn procedure tcp-server-socket-info @var{tcp-server-port}
@end deffn
@deffn procedure socket-info? @var{obj}
@deffnx procedure socket-info-address @var{socket-info}
@deffnx procedure socket-info-family @var{socket-info}
@deffnx procedure socket-info-port-number @var{socket-info}
@end deffn
@deffn procedure system-version
@deffnx procedure system-version-string
@end deffn
@deffn procedure system-type
@deffnx procedure system-type-string
@deffnx procedure configure-command-string
@end deffn
@deffn procedure system-stamp
@end deffn
@deffn {special form} future @var{expr}
@deffnx procedure touch @var{obj}
@end deffn
@deffn procedure tty? @var{obj}
@deffnx procedure tty-history @var{tty}
@deffnx procedure tty-history-set! @var{tty} @var{history}
@deffnx procedure tty-history-max-length-set! @var{tty} @var{n}
@deffnx procedure tty-paren-balance-duration-set! @var{tty} @var{duration}
@deffnx procedure tty-text-attributes-set! @var{tty} @var{attributes}
@deffnx procedure tty-mode-set! @var{tty} @var{mode}
@deffnx procedure tty-type-set! @var{tty} @var{type}
@end deffn
@deffn procedure with-input-from-port @var{port} @var{thunk}
@deffnx procedure with-output-to-port @var{port} @var{thunk}
@end deffn
@deffn procedure input-port-char-position @var{port}
@deffnx procedure output-port-char-position @var{port}
@end deffn
@deffn procedure open-event-queue @var{n}
@end deffn
@deffn procedure main @dots{}
@end deffn
@deffn {special form} define-record-type @dots{}
@deffnx {special form} define-type @dots{}
@end deffn
@deffn {special form} namespace @dots{}
@end deffn
@deffn {special form} this-source-file
@end deffn
@deffn {special form} receive @dots{}
@end deffn
@deffn {special form} cond-expand @dots{}
@end deffn
@deffn {special form} define-cond-expand-feature @var{ident}
@end deffn
@deffn procedure finite? @var{x}
@deffnx procedure infinite? @var{x}
@deffnx procedure nan? @var{x}
@end deffn
@deffn undefined six.!
@deffnx {special form} six.!x @var{x}
@deffnx {special form} six.&x @var{x}
@deffnx {special form} six.*x @var{x}
@deffnx {special form} six.++x @var{x}
@deffnx {special form} six.+x @var{x}
@deffnx {special form} six.--x @var{x}
@deffnx {special form} six.-x @var{x}
@deffnx {special form} six.arrow @var{expr} @var{ident}
@deffnx undefined six.break
@deffnx {special form} six.call @var{func} @var{arg}@dots{}
@deffnx undefined six.case
@deffnx undefined six.clause
@deffnx {special form} six.compound @var{statement}@dots{}
@deffnx {special form} six.cons @var{x} @var{y}
@deffnx undefined six.continue
@deffnx {special form} six.define-procedure @var{ident} @var{proc}
@deffnx {special form} six.define-variable @var{ident} @var{type} @var{dims} @var{init}
@deffnx {special form} six.do-while @var{stat} @var{expr}
@deffnx {special form} six.dot @var{expr} @var{ident}
@deffnx {special form} six.for @var{stat1} @var{expr2} @var{expr3} @var{stat2}
@deffnx undefined six.goto
@deffnx {special form} six.identifier @var{ident}
@deffnx {special form} six.if @var{expr} @var{stat1} @r{[}@var{stat2}@r{]}
@deffnx {special form} six.index @var{expr1} @var{expr2}
@deffnx undefined six.label
@deffnx {special form} six.list @var{x} @var{y}
@deffnx {special form} six.literal @var{value}
@deffnx procedure six.make-array @var{init} @var{dim}@dots{}
@deffnx {special form} six.new @var{ident} @var{arg}@dots{}
@deffnx {special form} six.null
@deffnx {special form} six.prefix @var{datum}
@deffnx {special form} six.procedure @var{type} @var{params} @var{stat}
@deffnx {special form} six.procedure-body @var{stat}@dots{}
@deffnx undefined six.return
@deffnx undefined six.switch
@deffnx {special form} six.while @var{expr} @var{stat}@dots{}
@deffnx {special form} six.x!=y @var{x} @var{y}
@deffnx {special form} six.x%=y @var{x} @var{y}
@deffnx {special form} six.x%y @var{x} @var{y}
@deffnx {special form} six.x&&y @var{x} @var{y}
@deffnx {special form} six.x&=y @var{x} @var{y}
@deffnx {special form} six.x&y @var{x} @var{y}
@deffnx {special form} six.x*=y @var{x} @var{y}
@deffnx {special form} six.x*y @var{x} @var{y}
@deffnx {special form} six.x++ @var{x}
@deffnx {special form} six.x+=y @var{x} @var{y}
@deffnx {special form} six.x+y @var{x} @var{y}
@deffnx {special form} |six.x,y| @var{x} @var{y}
@deffnx {special form} six.x-- @var{x}
@deffnx {special form} six.x-=y @var{x} @var{y}
@deffnx {special form} six.x-y @var{x} @var{y}
@deffnx {special form} six.x/=y @var{x} @var{y}
@deffnx {special form} six.x/y @var{x} @var{y}
@deffnx undefined six.x:-y @var{x} @var{y}
@deffnx {special form} six.x:=y @var{x} @var{y}
@deffnx {special form} six.x:y @var{x} @var{y}
@deffnx {special form} six.x<<=y @var{x} @var{y}
@deffnx {special form} six.x<<y @var{x} @var{y}
@deffnx {special form} six.x<=y @var{x} @var{y}
@deffnx {special form} six.x<y @var{x} @var{y}
@deffnx {special form} six.x==y @var{x} @var{y}
@deffnx {special form} six.x=y @var{x} @var{y}
@deffnx {special form} six.x>=y @var{x} @var{y}
@deffnx {special form} six.x>>=y @var{x} @var{y}
@deffnx {special form} six.x>>y @var{x} @var{y}
@deffnx {special form} six.x>y @var{x} @var{y}
@deffnx {special form} six.x?y:z @var{x} @var{y} @var{z}
@deffnx {special form} six.x^=y @var{x} @var{y}
@deffnx {special form} six.x^y @var{x} @var{y}
@deffnx {special form} |six.x\|=y| @var{x} @var{y}
@deffnx {special form} |six.x\|y| @var{x} @var{y}
@deffnx {special form} |six.x\|\|y| @var{x} @var{y}
@deffnx {special form} six.~x @var{x}
@end deffn
@node Namespaces, Characters and strings, Scheme extensions, Top
@chapter Namespaces
TO DO!
@node Characters and strings, Numbers, Namespaces, Top
@chapter Characters and strings
Gambit supports the Unicode character encoding standard. Scheme
characters can be any of the characters whose Unicode encoding is in
the range 0 to #x10ffff (inclusive) but not in the range #xd800 to
#xdfff. Source code can also contain any Unicode character, however
to read such source code properly @code{gsi} and @code{gsc} must be
told which character encoding to use for reading the source code
(i.e. ASCII, ISO-8859-1, UTF-8, etc). This can be done by specifying
the runtime option @samp{-:f} when @code{gsi} and @code{gsc} are
started.
@menu
* Extensions to character procedures:: Extensions to character procedures
* Extensions to string procedures:: Extensions to string procedures
@end menu
@node Extensions to character procedures, Extensions to string procedures, Characters and strings, Characters and strings
@section Extensions to character procedures
@deffn procedure char->integer @var{char}
@deffnx procedure integer->char @var{n}
The procedure @code{char->integer} returns the Unicode encoding of
the character @var{char}.
The procedure @code{integer->char} returns the character whose
Unicode encoding is the exact integer @var{n}.
For example:
@smallexample
> @b{(char->integer #\!)}
33
> @b{(integer->char 65)}
#\A
> @b{(integer->char (char->integer #\u1234))}
#\u1234
> @b{(integer->char #xd800)}
*** ERROR IN (console)@@4.1 -- (Argument 1) Out of range
(integer->char 55296)
@end smallexample
@end deffn
@deffn procedure char=? @var{char1}@dots{}
@deffnx procedure char<? @var{char1}@dots{}
@deffnx procedure char>? @var{char1}@dots{}
@deffnx procedure char<=? @var{char1}@dots{}
@deffnx procedure char>=? @var{char1}@dots{}
@deffnx procedure char-ci=? @var{char1}@dots{}
@deffnx procedure char-ci<? @var{char1}@dots{}
@deffnx procedure char-ci>? @var{char1}@dots{}
@deffnx procedure char-ci<=? @var{char1}@dots{}
@deffnx procedure char-ci>=? @var{char1}@dots{}
These procedures take any number of arguments including no argument.
This is useful to test if the elements of a list are sorted in a
particular order. For example, testing that the list of characters
@code{lst} is sorted in nondecreasing order can be done with the call
@code{(apply char<? lst)}.
@end deffn
@node Extensions to string procedures, , Extensions to character procedures, Characters and strings
@section Extensions to string procedures
@deffn procedure string=? @var{string1}@dots{}
@deffnx procedure string<? @var{string1}@dots{}
@deffnx procedure string>? @var{string1}@dots{}
@deffnx procedure string<=? @var{string1}@dots{}
@deffnx procedure string>=? @var{string1}@dots{}
@deffnx procedure string-ci=? @var{string1}@dots{}
@deffnx procedure string-ci<? @var{string1}@dots{}
@deffnx procedure string-ci>? @var{string1}@dots{}
@deffnx procedure string-ci<=? @var{string1}@dots{}
@deffnx procedure string-ci>=? @var{string1}@dots{}
These procedures take any number of arguments including no argument.
This is useful to test if the elements of a list are sorted in a
particular order. For example, testing that the list of strings
@code{lst} is sorted in nondecreasing order can be done with the call
@code{(apply string<? lst)}.
@end deffn
@node Numbers, Homogeneous vectors, Characters and strings, Top
@chapter Numbers
@menu
* Extensions to numeric procedures:: Extensions to numeric procedures
* IEEE floating point arithmetic:: IEEE floating point arithmetic
* Integer square root and nth root:: Integer square root and nth root
* Bitwise-operations on exact integers:: Bitwise-operations on exact integers
* Fixnum specific operations:: Operations on fixnums
* Flonum specific operations:: Operations on flonums
* Pseudo random numbers:: Pseudo random numbers
@end menu
@node Extensions to numeric procedures, IEEE floating point arithmetic, Numbers, Numbers
@section Extensions to numeric procedures
@deffn procedure = @var{z1}@dots{}
@deffnx procedure < @var{x1}@dots{}
@deffnx procedure > @var{x1}@dots{}
@deffnx procedure <= @var{x1}@dots{}
@deffnx procedure >= @var{x1}@dots{}
These procedures take any number of arguments including no argument.
This is useful to test if the elements of a list are sorted in a
particular order. For example, testing that the list of numbers
@code{lst} is sorted in nondecreasing order can be done with the call
@code{(apply < lst)}.
@end deffn
@node IEEE floating point arithmetic, Integer square root and nth root, Extensions to numeric procedures, Numbers
@section IEEE floating point arithmetic
To better conform to IEEE floating point arithmetic the standard
numeric tower is extended with these special inexact reals:
@table @code
@item +inf.0
positive infinity
@item -inf.0
negative infinity
@item +nan.0
``not a number''
@item -0.
negative zero (@samp{0.} is the positive zero)
@end table
The infinities and ``not a number'' are reals (i.e. @code{(real?
+inf.0)} is @code{#t}) but are not rational (i.e. @code{(rational?
+inf.0)} is @code{#f}).
Both zeros are numerically equal (i.e. @code{(= -0. 0.)} is @code{#t})
but are not equivalent (i.e. @code{(eqv? -0. 0.)} and @code{(equal?
-0. 0.)} are @code{#f}). All numerical comparisons with ``not a
number'', including @code{(= +nan.0 +nan.0)}, are @code{#f}.
@node Integer square root and nth root, Bitwise-operations on exact integers, IEEE floating point arithmetic, Numbers
@section Integer square root and nth root
@deffn procedure integer-sqrt @var{n}
This procedure returns the integer part of the square root of the
nonnegative exact integer @var{n}.
For example:
@smallexample
> @b{(integer-sqrt 123)}
11
@end smallexample
@end deffn
@deffn procedure integer-nth-root @var{n1} @var{n2}
This procedure returns the integer part of @var{n1} raised to the
power 1/@var{n2}, where @var{n1} is a nonnegative exact integer and
@var{n2} is a positive exact integer.
For example:
@smallexample
> @b{(integer-nth-root 100 3)}
4
@end smallexample
@end deffn
@node Bitwise-operations on exact integers, Fixnum specific operations, Integer square root and nth root, Numbers
@section Bitwise-operations on exact integers
The procedures defined in this section are compatible with the
withdrawn ``Integer Bitwise-operation Library SRFI'' (SRFI 33). Note
that some of the procedures specified in SRFI 33 are not provided.
Most procedures in this section are specified in terms of the binary
representation of exact integers. The two's complement representation
is assumed where an integer is composed of an infinite number of bits.
The upper section of an integer (the most significant bits) are either
an infinite sequence of ones when the integer is negative, or they are
an infinite sequence of zeros when the integer is nonnegative.
@deffn procedure arithmetic-shift @var{n1} @var{n2}
This procedure returns @var{n1} shifted to the left by @var{n2} bits,
that is @code{(floor (* @var{n1} (expt 2 @var{n2})))}. Both @var{n1}
and @var{n2} must be exact integers.
For example:
@smallexample
> @b{(arithmetic-shift 1000 7) @r{@i{; n1=...0000001111101000}}}
128000
> @b{(arithmetic-shift 1000 -6) @r{@i{; n1=...0000001111101000}}}
15
> @b{(arithmetic-shift -23 -3) @r{@i{; n1=...1111111111101001}}}
-3
@end smallexample
@end deffn
@deffn procedure bitwise-merge @var{n1} @var{n2} @var{n3}
This procedure returns an exact integer whose bits combine the bits
from @var{n2} and @var{n3} depending on @var{n1}. The bit at index
@var{i} of the result depends only on the bits at index @var{i} in
@var{n1}, @var{n2} and @var{n3}: it is equal to the bit in @var{n2}
when the bit in @var{n1} is 0 and it is equal to the bit in @var{n3}
when the bit in @var{n1} is 1. All arguments must be exact integers.
For example:
@smallexample
> @b{(bitwise-merge -4 -11 10) @r{@i{; ...11111100 ...11110101 ...00001010}}}
9
> @b{(bitwise-merge 12 -11 10) @r{@i{; ...00001100 ...11110101 ...00001010}}}
-7
@end smallexample
@end deffn
@deffn procedure bitwise-and @var{n}@dots{}
This procedure returns the bitwise ``and'' of the exact integers
@var{n}@dots{}. The value -1 is returned when there are no arguments.
For example:
@smallexample
> @b{(bitwise-and 6 12) @r{@i{; ...00000110 ...00001100}}}
4
> @b{(bitwise-and 6 -4) @r{@i{; ...00000110 ...11111100}}}
4
> @b{(bitwise-and -6 -4) @r{@i{; ...11111010 ...11111100}}}
-8
> @b{(bitwise-and)}
-1
@end smallexample
@end deffn
@deffn procedure bitwise-ior @var{n}@dots{}
This procedure returns the bitwise ``inclusive-or'' of the exact
integers @var{n}@dots{}. The value 0 is returned when there are no
arguments.
For example:
@smallexample
> @b{(bitwise-ior 6 12) @r{@i{; ...00000110 ...00001100}}}
14
> @b{(bitwise-ior 6 -4) @r{@i{; ...00000110 ...11111100}}}
-2
> @b{(bitwise-ior -6 -4) @r{@i{; ...11111010 ...11111100}}}
-2
> @b{(bitwise-ior)}
0
@end smallexample
@end deffn
@deffn procedure bitwise-xor @var{n}@dots{}
This procedure returns the bitwise ``exclusive-or'' of the exact
integers @var{n}@dots{}. The value 0 is returned when there are no
arguments.
For example:
@smallexample
> @b{(bitwise-xor 6 12) @r{@i{; ...00000110 ...00001100}}}
10
> @b{(bitwise-xor 6 -4) @r{@i{; ...00000110 ...11111100}}}
-6
> @b{(bitwise-xor -6 -4) @r{@i{; ...11111010 ...11111100}}}
6
> @b{(bitwise-xor)}
0
@end smallexample
@end deffn
@deffn procedure bitwise-not @var{n}
This procedure returns the bitwise complement of the exact integer
@var{n}.
For example:
@smallexample
> @b{(bitwise-not 3) @r{@i{; ...00000011}}}
-4
> @b{(bitwise-not -1) @r{@i{; ...11111111}}}
0
@end smallexample
@end deffn
@deffn procedure bit-count @var{n}
This procedure returns the bit count of the exact integer @var{n}. If
@var{n} is nonnegative, the bit count is the number of 1 bits in the
two's complement representation of @var{n}. If @var{n} is negative,
the bit count is the number of 0 bits in the two's complement
representation of @var{n}.
For example:
@smallexample
> @b{(bit-count 0) @r{@i{; ...00000000}}}
0
> @b{(bit-count 1) @r{@i{; ...00000001}}}
1
> @b{(bit-count 2) @r{@i{; ...00000010}}}
1
> @b{(bit-count 3) @r{@i{; ...00000011}}}
2
> @b{(bit-count 4) @r{@i{; ...00000100}}}
1
> @b{(bit-count -23) @r{@i{; ...11101001}}}
3
@end smallexample
@end deffn
@deffn procedure integer-length @var{n}
This procedure returns the bit length of the exact integer @var{n}.
If @var{n} is a positive integer the bit length is one more than the
index of the highest 1 bit (the least significant bit is at index 0).
If @var{n} is a negative integer the bit length is one more than the
index of the highest 0 bit. If @var{n} is zero, the bit length is 0.
For example:
@smallexample
> @b{(integer-length 0) @r{@i{; ...00000000}}}
0
> @b{(integer-length 1) @r{@i{; ...00000001}}}
1
> @b{(integer-length 2) @r{@i{; ...00000010}}}
2
> @b{(integer-length 3) @r{@i{; ...00000011}}}
2
> @b{(integer-length 4) @r{@i{; ...00000100}}}
3
> @b{(integer-length -23) @r{@i{; ...11101001}}}
5
@end smallexample
@end deffn
@deffn procedure bit-set? @var{n1} @var{n2}
This procedure returns a boolean indicating if the bit at index
@var{n1} of @var{n2} is set (i.e. equal to 1) or not. Both @var{n1}
and @var{n2} must be exact integers, and @var{n1} must be
nonnegative.
For example:
@smallexample
> @b{(map (lambda (i) (bit-set? i -23)) @r{@i{; ...11101001}}