Chapter 12. System Operations

This chapter describes operations for
handling exceptions, interrupts, environments,
compilation and evaluation, profiling,
controlling the operation of the system,
timing and statistics,
defining and setting parameters,
and
querying the operating system environment.

Section 12.1. Exceptions

Chez Scheme provides some extensions to the
Revised6 Report exception-handling mechanism, including mechanisms
for producing formatted error messages, displaying conditions,
and redefining the base exception handler.
These extensions are described in this section.

warning raises a continuable exception with condition type
&warning and should be used to describe situations for which the
&warning condition type is appropriate, typically a situation
that should not prevent the program from continuing but might result
in a more serious problem at some later point.

The continuation object with which the exception is raised also includes
a &who condition whose who field is who if who is
not #f, a &message condition whose message field is
msg, and an &irritants condition whose irritants field
is (irritant ...).

who must be a string, a symbol, or #f identifying the procedure
or syntactic form reporting the warning upon whose behalf the warning is being
reported.
It is usually best to identify a procedure the programmer has called rather
than some other procedure the programmer may not be aware is involved in
carrying out the operation.
msg must be a string and should describe the exceptional situation.
The irritants may be any Scheme objects and should include values that may
have caused or been materially involved in the exceptional situation.

These procedures are like assertion-violation, error,
and warning except
that msg is assumed to be a format string, as if in a call to
format (Section 9.13), with
irritant ... treated as the additional arguments to
format.
This allows programs to control the appearance of the error message, at
least when the default exception handler is in place.

For each of these procedures, the continuation object with which the exception
is raised includes a &format condition to signify that the string
contained in the condition object's &message condition is a
format string and the objects contained in the condition object's
&irritants condition should be treated as the additional
format arguments.

Presence of this condition type within a compound condition indicates
that the string provided by the &message condition, if
present, is a format string and the list of objects provided by
the &irritants condition, if present, should be treated as
additional format arguments.
This condition type might be defined as follows.

syntax: &sourceprocedure: (make-source-condition form)returns: a condition of type &sourceprocedure: (source-condition? obj)returns: #t if obj is a condition of type &source, #f otherwise
procedure: (source-condition-form condition)returns: the contents of condition's form field
libraries: (chezscheme)

This condition type can be included within a compound condition when a
source expression can be identified in situations in which a
&syntax condition would be inappropriate, such as when a
run-time assertion violation is detected.
The form argument should be an s-expression or syntax object
representing the source expression.
This condition type might be defined as follows.

This condition type can be included within a compound condition to indicate
the current continuation at the point where the exception described by the
condition occurred.
The continuation of a failed assert or a call to
assertion-violation, assertion-violationf,
error, errorf, or syntax-error is now included
via this condition type in the conditions passed to raise.
The continuation argument should be a continuation.
This condition type might be defined as follows.

If textual-output-port is not supplied, it defaults to the current output port.
This procedure displays a message to the effect that an exception
has occurred with value obj.
If obj is a condition (Chapter 11 of
The Scheme Programming Language, 4th Edition), it displays information encapsulated within the condition,
handling messages, who conditions, irritants, source information,
etc., as appropriate.

This procedure is the default value of the base-exception-handler
parameter called on a condition when no other exception handler has been
defined or when all dynamically established exception handlers have chosen
not to handle the condition.
It first displays obj, as if with display-condition, to the
console error port.
For non-serious warning conditions, it returns immediately after displaying
the condition.

For serious or other non-warning conditions, it
saves the condition in the parameter debug-condition, where
debug (Section 3.2) can retrieve it and
allow it to be inspected.
If the debug-on-exception parameter is set to #f (the
default unless the --debug-on-exception command-line option is provided), the
handler prints a message instructing the user to type (debug) to
enter the debugger, then resets to the current café.
Otherwise, the handler invokes debug directly and resets if
debug returns.

global parameter: debug-on-exceptionlibraries: (chezscheme)

The value of this parameter determines whether the default exception handler
immediately enters the debugger immediately when it receives a serious or
non-warning condition.
If the --debug-on-exception
command-line option (Section 2.1) has been provided, the
initial value of this parameter is #t.
Otherwise, the initial value is #f.

thread parameter: base-exception-handlerlibraries: (chezscheme)

The value of this parameter must be a procedure, and the procedure
should accept one argument.
The default value of base-exception-handler is
the procedure default-exception-handler.

The value of this parameter is invoked whenever no exception handler
established by a program has chosen to handle an exception.

thread parameter: debug-conditionlibraries: (chezscheme)

This parameter is used by the default exception handler to hold the
last serious or non-warning condition received by the handler, where
it can be inspected via the debug procedure
(Section 3.2).
It can also be invoked by user code to store or retrieve a
condition.

thread parameter: current-exception-statelibraries: (chezscheme)

current-exception-state may be used to get or set
the current exception state.
When called without arguments, current-exception-state returns
an exception state comprising the current stack of handlers established
by with-exception-handler and guard.
When called with a single argument, which must be an exception state,
current-exception-state sets the exception state.

create-exception-state creates an exception
state whose stack of exception handlers is empty except for, in effect,
an infinite number of occurrences of handler at its
base.
handler must be a procedure, and should accept one argument.
If not provided, handler defaults to a procedure equivalent
to the value of the following expression.

(lambda (x) ((base-exception-handler) x))

Section 12.2. Interrupts

Chez Scheme allows programs to control
the action of the Scheme system when various events
occur, including an interrupt from the
keyboard, the expiration of an internal timer set by set-timer,
a breakpoint caused by a call to break, or a request from the
storage manager to initiate a garbage collection.
These mechanisms are described in this section, except for the
collect request mechanism, which is described in Section 13.1.

Timer, keyboard, and collect-request interrupts are supported via a counter
that is decremented approximately once for each call to a nonleaf procedure.
(A leaf procedure is one that does not itself make any calls.)
When no timer is running, this counter is set to a default value (1000
in Version 8) when a program starts or after an interrupt occurs.
If a timer is set (via set-timer), the counter is set to the
minimum of the default value and the number of ticks to which the timer is
set.
When the counter reaches zero, the system looks to see if the timer
is set and has expired or if a keyboard or collect request interrupt
has occurred.
If so, the current procedure call is pended ("put on hold") while the
appropriate interrupt handler is invoked to handle the interrupt.
When (if) the interrupt handler returns, the pended call takes place.
Thus, timer, keyboard, and collect-request interrupts effectively occur
synchronously with respect to the procedure call mechanism, and
keyboard and collect request interrupts may be delayed by a number
of calls equal to the default timer value.

The arguments to break follow the protocol described above for
errorf.
The default break handler (see break-handler) displays a message and
invokes the debugger.
The format string and objects may be omitted, in which case the
message issued by the default break handler identifies the break
using the who argument but provides no more information
about the break.
If the who argument is omitted as well, no message is generated.
The default break handler returns normally if the debugger
exits normally.

thread parameter: break-handlerlibraries: (chezscheme)

The value of this parameter must be a procedure.
The current break handler is called by break, which passes
along its arguments.
See break for a description of the default break
handler.
The example below shows how to disable breaks.

(break-handler (lambda args (void)))

thread parameter: keyboard-interrupt-handlerlibraries: (chezscheme)

The value of this parameter must be a procedure.
The keyboard-interrupt handler is called (with no arguments) when
a keyboard interrupt occurs.
The default keyboard-interrupt handler invokes the interactive
debugger.
If the debugger exits normally the interrupted computation is
resumed.
The example below shows how to install a keyboard-interrupt handler
that resets without invoking the debugger.

n must be a nonnegative integer.
When n is nonzero, set-timer starts an internal timer with
an initial value of n.
When n ticks elapse, a timer interrupt occurs, resulting in
invocation of the timer interrupt handler.
Each tick corresponds roughly to one nonleaf procedure call (see the
introduction to this section); thus, ticks are not
uniform time units but instead depend heavily on how much work is done
by each procedure call.

When n is zero, set-timer turns the timer off.

The value returned in either case is the value of the timer before the
call to set-timer.
A return value of 0 should not be taken to imply that the timer was not on;
the return value may also be 0 if the timer was just about to fire when
the call to set-timer occurred.

The engine mechanism (Section 6.4) is built on top of the
timer interrupt so timer interrupts should not be used with engines.

thread parameter: timer-interrupt-handlerlibraries: (chezscheme)

The value of this parameter must be a procedure.
The timer interrupt handler is called by the system when the internal timer
(set by set-timer) expires.
The default handler raises an exception with condition type &assertion
to say that the handler has not
been defined; any program that uses the timer should redefine the
handler before setting the timer.

disable-interrupts disables the handling of interrupts,
including timer, keyboard, and collect request interrupts.
enable-interrupts re-enables these interrupts.
The system maintains a disable count that starts at zero; when zero,
interrupts are enabled.
Each call to disable-interrupts increments the count,
effectively disabling interrupts.
Each call to enable-interrupts decrements the count, if
not already zero, effectively enabling interrupts.
For example, two calls to disable-interrupts followed by one call to
enable-interrupts leaves interrupts disabled.
Calls to enable-interrupts when the count is already zero
(and interrupts are enabled) have no effect.
The value returned by either procedure is the number of calls to
enable-interrupts required to enable interrupts.

Great care should be exercised when using these procedures, since disabling
interrupts inhibits the normal processing of keyboard interrupts,
timer interrupts, and, perhaps most importantly, collect request interrupts.
Since garbage collection does not happen automatically when interrupts are
disabled, it is possible for the storage allocator to run out of space
unnecessarily should interrupts be disabled for a long period of time.

The with-interrupts-disabled syntactic form should be used instead of
these more primitive procedures whenever possible,
since with-interrupts-disabled ensures that interrupts are re-enabled
whenever a nonlocal exit occurs, such as when an exception is handled by
the default exception handler.

with-interrupts-disabled evaluates the body
body1body2 ... with interrupts disabled.
That is, upon entry, interrupts are disabled, and
upon exit, interrupts are re-enabled.
Thus, with-interrupts-disabled allows the implementation of indivisible
operations in nonthreaded versions of Chez Scheme or within a single thread
in threaded versions of Chez Scheme.
critical-section is the same as with-interrupts-disabled and
is provided for backward compatibility.

The use of dynamic-wind ensures that interrupts are
disabled whenever the body of the with-interrupts-disabled expression
is active and re-enabled whenever it is not.
Since calls to disable-interrupts are counted (see the
discussion under disable-interrupts and
enable-interrupts above), with-interrupts-disabled
expressions may be nested with the desired effect.

register-signal-handler is used to
establish a signal handler for a given low-level signal.
sig must be an exact integer identifying a valid signal, and
procedure should accept one argument.
See your host system's <signal.h> or documentation for a list
of valid signals and their numbers.
After a signal handler for a given signal has been registered, receipt
of the specified signal results in a call to the handler.
The handler is passed the signal number, allowing the same handler to
be used for different signals while differentiating among them.

Signals handled in this fashion are treated like keyboard interrupts in
that the handler is not called immediately when the signal is delivered
to the process, but rather at some procedure call boundary after the
signal is delivered.
It is generally not a good idea, therefore, to establish handlers for
memory faults, illegal instructions, and the like, since the code that
causes the fault or illegal instruction will continue to execute
(presumably erroneously) for some time before the handler is invoked.

register-signal-handler is supported only on Unix-based
systems.

Section 12.3. Environments

Environments are first-class objects containing identifier bindings.
They are similar to modules but, unlike modules, may be manipulated
at run time.
Environments may be provided as optional arguments to eval,
expand, and the procedures that define, assign, or
reference top-level values.

There are several built-in environments, and new environments can
be created by copying existing environments or selected bindings
from existing environments.

Environments can be mutable or immutable.
A mutable environment can be extended with new bindings, its
existing bindings can be modified, and its variables can be assigned.
An immutable environment cannot be modified in any of these ways.

The original value of interaction-environment is the default
top-level environment.
It is initially set to a mutable copy of
(scheme-environment) and which may be extended or otherwise
altered by top-level definitions and assignments.
It may be set to any environment, mutable or not, to change the
default top-level evaluation environment.

An expression's top-level bindings resolve to the environment that is
in effect when the expression is expanded, and changing the value
of this parameter has no effect on running code.
Changes affect only code that is subsequently expanded, e.g., as the
result of a call to eval, load, or
compile-file.

copy-environment returns a copy of env, i.e., a new
environment that contains the same bindings as env.

The environment is mutable if mutable? is omitted or true;
if mutable? is false, the environment is immutable.

The set of bindings copied from env to the new environment
is determined by syms, which defaults to the value of
(environment-symbols env).
The binding, if any, for each element of syms is copied to the
new environment, and no other bindings are present in the new
environment.

In the current implementation, the storage space used by an environment
is never collected, so repeated use of copy-environment will
eventually cause the system to run out of memory.

If env is not specified, it defaults to the value of the
interaction-environment parameter.
env must be a mutable environment.

In the initial interaction environment and any copy of a built-in
environment, such as the scheme environment, built-in
bindings are read-only.
In particular, built-in variable bindings cannot be assigned via
set!, but they can be redefined with define,
define-syntax, etc.
For example, cons can be referenced, but it cannot
be not assigned until it has been redefined:

Redefinition of a built-in keyword, procedure, etc., does not affect
code that has already been expanded, so any code that has already been
loaded, entered via the waiter, or explicitly evaluated must be reloaded,
reentered, or reevaluated.

This differs from the Version 7 semantics, in which variable bindings
(but not keyword or other identifier bindings, such as module-name
bindings) can be assigned even if they are not redefined.
The current semantics allows the compiler to do two useful things: (1)
produce better warnings when primitives are misused, and (2) generate
better code, because it knows at compile time exactly what procedure will
be invoked when it sees a reference to a variable bound to a primitive
that has not been redefined.

If the Version 7 semantics is preferred, the procedure
revert-interaction-semantics may be used to convert all
read-only variable bindings in a mutable environment into assignable
bindings, effectively reverting the environment to the Version 7
semantics.

This procedure returns a selected list of symbols and pairs.
Each symbol in the list represents an identifier bound in env.
Each pair represents a set of identifiers exported by a
predefined library or a library previously defined or loaded
into the system.
The car of the pair is the library name, and the cdr is a list
of symbols.
If s is a string, only entries whose names have s as a
substring are included, and if s is a symbol, only those whose names
have the name of s as a substring are selected.
If no environment is provided, it defaults to the value of
interaction-environment.

Section 12.4. Compilation, Evaluation, and Loading

eval treats obj as the representation of an expression.
It evaluates the expression in environment env and returns
its value.
If no environment is provided, it defaults to the environment
returned by interaction-environment.

Single-argument eval is a Chez Scheme extension.
Chez Scheme also permits obj to be the representation of a
nonexpression form, i.e., a definition, whenever the environment
is mutable.
Chez Scheme further allows obj to be an annotation
(Section 11.11), and the default evaluators
make use of annotations to incorporate source-file
information in error messages and associate source-file
information with compiled code.

In Chez Scheme, eval is actually a wrapper that simply
passes its arguments to the current evaluator.
(See current-eval.)
The default evaluator is compile, which expands the
expression via the current expander (see
current-expand), compiles it,
executes the resulting code, and returns its value.
If the environment argument, env, is present,
compile passes it along to the current expander,
which is sc-expand by default.

thread parameter: current-evallibraries: (chezscheme)

current-eval determines the evaluation procedure used by the
procedures eval, load, and
new-cafe.
current-eval is initially bound to the value of
compile.
(In Petite Chez Scheme, it is initially bound to the value of
interpret.)
The evaluation procedureshould expect one or two arguments: an object
to evaluate and an optional environment.
The second argument might be an annotation
(Section 11.11).

obj, which can be an annotation (Section 11.11)
or unannotated value, is treated as a Scheme expression, expanded with the
current expander (the value of current-expand) in the specified
environment (or the interaction environment, if no environment
is provided), compiled to machine code, and executed.
compile is the default value of the current-eval
parameter.

path must be a string.
load reads and evaluates the contents of the file specified by
path.
The file may contain source or object code.
By default, load employs eval to evaluate each source
expression found in a source file.
If eval-proc is specified, load uses this procedure instead.
eval-proc must accept one argument, the expression to evaluate.
The expression passed to eval-proc might be an annotation
(Section 11.11) or an unannotated value.

The eval-proc argument
facilitates the implementation of embedded Scheme-like languages
and the use of alternate
evaluation mechanisms to be used for Scheme programs.
eval-proc can be put to other uses as well.
For example,

load-library is identical to load except
that it treats the input file as if it were prefixed by an implicit
#!r6rs.
This effectively disables any non-R6RS lexical
syntax except where subsequently overridden by #!chezscheme.

path must be a string.
load-program reads and evaluates the contents of the file specified by
path.
The file may contain source or object code.
If it contains source code, load-program wraps
the code in a top-level-program form so that the file's
content is treated as an RNRS top-level program
(Section 10.3 of The Scheme Programming Language, 4th Edition).
By default, load-program employs eval to evaluate each source
expression found in the file.
If eval-proc is specified, load-program uses this procedure instead.
eval-proc must accept one argument, the expression to evaluate.
The expression passed to eval-proc might be an annotation
(Section 11.11) or an unannotated value.

The parameter source-directories (Section 12.5)
determines the set of directories searched for source files not identified
by absolute path names.

procedure: (visit path)returns: unspecified
libraries: (chezscheme)

path must be a string.
visit reads the named file, which must contain compiled object
code compatible with the current machine type and version, and it
runs those portions of the compiled object code that
establish compile-time information or correspond to expressions
identified as "visit" time by eval-when forms contained in
the original source file.

If t1.ss is compiled to t1.so, applying load
to t1.so has the effect of defining all three identifiers.
Applying visit to t1.so, however, has the effect of
installing the transformer for a, installing the interface for
m (for use by import), and recording y as
a variable.
visit is useful when separately compiling one file that depends
on bindings defined in another without actually loading and evaluating
the code in the supporting file.

The parameter source-directories (Section 12.5)
determines the set of directories searched for source files not identified
by absolute path names.

procedure: (revisit path)returns: unspecified
libraries: (chezscheme)

path must be a string.
revisit reads the named file, which must contain compiled object
code compatible with the current machine type and version, and it
runs those portions of the compiled object code that compute
run-time values or correspond to expressions identified as "revisit" time by
eval-when forms contained in the original source file.

Continuing the example given for visit above,
applying revisit to the object file, t1.so, has
the effect of establishing the values of the variable x
exported from m and the top-level variable y,
without installing either the interface for m or
the transformer for a.

revisit is useful for loading compiled application code without
loading unnecessary compile-time information.
Care must be taken when using this feature if the application calls
eval or uses top-level-value,
set-top-level-value!, or top-level-syntax to access
top-level bindings at run-time, since these procedures use compile-time
information to resolve top-level bindings.

The parameter source-directories (Section 12.5)
determines the set of directories searched for source files not identified
by absolute path names.

The normal evaluation process proceeds in two steps: compilation and
execution.
compile-file performs the compilation process for an entire source
file, producing an object file.
When the object file is subsequently loaded (see load), the
compilation process is not necessary, and the file typically loads
several times faster.

If the optional output-filename argument is omitted, the
actual input and output filenames are determined as follows.
If input-filename has no extension, the input filename
is input-filename followed by .ss and the
output filename is input-filename followed by .so.
If input-filename has the extension .so, the
input filename is input-filename and the output filename
is input-filename followed by .so.
Otherwise, the input filename is input-filename and the
output filename is input-filename without its extension,
followed by .so.
For example, (compile-file "myfile") produces an object file
with the name "myfile.so" from the source file named
"myfile.ss", (compile-file "myfile.sls") produces an
object file with the name "myfile.so" from the source file named
"myfile.sls", and
(compile-file "myfile1" "myfile2") produces an object file with
the name "myfile2" from the source file name "myfile1".

Before compiling a file, compile-file saves the values of the
following parameters:

It restores the values after the file has been compiled.
This allows the programmer to control the values of these parameters on
a per-file basis, e.g., via an eval-when with situation
compile embedded in the source file.
For example, if

(eval-when (compile) (optimize-level 3))

appears at the top of a source file, the optimization level is set
to 3 just while the remainder of file is compiled.

compile-script is like compile-file but differs in
that it copies the leading #! line from the
source-file script into the object file.
When the #! line is present, it also disables compression, as if
the parameter
compile-compressed were set to
false.

compile-script permits compiled script files to be created from
source script to reduce script load time.
As with source-code scripts, compiled scripts may be run with the
--script
command-line option.

compile-library is identical to compile-file except
that it treats the input file as if it were prefixed by an implicit
#!r6rs.
This effectively disables any non-R6RS lexical
syntax except where subsequently overridden by #!chezscheme.

procedure: (compile-program input-filename)procedure: (compile-program input-filenameoutput-filename)returns: a list of libraries invoked by the program
libraries: (chezscheme)

input-filename and output-filename must be strings.

compile-program is like compile-script but differs in
that it implements the semantics of RNRS top-level programs, while
compile-script implements the semantics of the interactive
top-level.
The resulting compiled program will also run faster than if compiled
via compile-file or compile-script.

compile-program returns a list of libraries directly
invoked by the compiled top-level program, excluding built-in
libraries like (rnrs) and (chezscheme).
The procedure library-requirements may be used to determine
the indirect requirements, i.e., additional libraries required by
the directly invoked libraries.
When combined with library-object-filename, this information can
be used to determine the set of files that must be distributed with the
compiled program file.

A program invokes a library only if it references one or more variables
exported from the library.
The set of libraries invoked by a top-level program, and hence
loaded when the program is loaded, might be smaller than the set
imported by the program, and it might be larger than the set
directly imported by the program.

As with source-code top-level programs, compiled top-level programs may be
run with the
--program
command-line option.

compile-port is like compile-file except that it takes
input from an arbitrary textual input port and sends output to an arbitrary
binary output port.
Neither port is closed automatically after compilation; it is assumed
that the program that opens the ports and invokes compile-port
will take care of closing the ports.

output-filename, input-filename, and the elements of
base-boot-list must be strings.

make-boot-file writes a boot header to the file named by
output-filename, followed by the object code for each
input-filename in turn.
If an input file is not already compiled, make-boot-file compiles
the file as it proceeds.

The boot header identifies the elements of base-boot-list as
alternative boot files upon which the new boot file depends.
If the list of strings naming base boot files is empty, the first named
input file should be a base boot file, i.e., petite.boot or some boot file
derived from petite.boot.

Boot files are loaded explicitly via the --boot or -b
command-line options or implicitly based on the name of the executable
(Section 2.9).

See Section 2.8 for more information on boot files
and the use of make-boot-file.

expand treats obj as the representation of an expression.
It expands the expression in environment env and returns
an object representing the expanded form.
If no environment is provided, it defaults to the environment
returned by interaction-environment.

obj can be an annotation
(Section 11.11), and the default expander
makes use of annotations to incorporate source-file
information in error messages.

expand actually passes its arguments to the current expander
(see current-expand), initially sc-expand.

thread parameter: current-expandlibraries: (chezscheme)

current-expand determines the expansion procedure used by
the compiler, interpreter, and direct calls to
expand
to expand syntactic extensions.
current-expand is initially bound to the value of
sc-expand.

It may be set another procedure, but since the format of
expanded code expected by the compiler and interpreter is not publicly
documented, only sc-expand produces correct output, so the
other procedure must ultimately be defined in terms of
sc-expand.

The first argument to the expansion procedure represents the input
expression.
It can be an annotation (Section 11.11) or an
unannotated value.
the second argument is an environment.
Additional arguments might be passed to the expansion procedure
by the compiler, interpreter, and expand; their number
and roles are unspecified.

The procedure
sc-expand is used to expand programs written using
syntax-case macros.
sc-expand is the default expander, i.e., the initial
value of current-expand.
obj represents the program to be expanded, and
env must be an environment.
obj can be an annotation (Section 11.11)
or unannotated value.
If not provided, env defaults to the environment returned by
interaction-environment.

procedure: (expand/optimize obj)procedure: (expand/optimize objenv)returns: result of expanding and optimizing form represented by objlibraries: (chezscheme)

expand/optimize treats obj as the representation of
an expression.
obj can be an annotation (Section 11.11)
or unannotated value.
expand/optimize expands the expression in environment env
and passes the expression through the source optimizer cp0
(unless cp0 is disabled via run-cp0).
It also simplifies letrec and letrec* expressions within
the expression and makes their undefined checks explicit.
It returns an object representing the expanded, simplified, and optimized form.
If no environment is provided, it defaults to the environment
returned by interaction-environment.

expand/optimize is primarily useful for understanding what
cp0 does and does not optimize.
Many optimizations are performed later in the compiler,
so expand/optimize does not give a complete picture of
optimizations performed.

situations must be a list containing some combination of the symbols
eval, compile, load, visit, and
revisit.

When source files are loaded (see load), the forms in the file
are read, compiled, and executed sequentially, so that each form in
the file is fully evaluated before the next one is read.
When a source file is compiled (see compile-file), however, the
forms are read and compiled, but not executed, in sequence.
This distinction matters only when the execution of one
form in the file affects the compilation of later forms, e.g.,
when the form results in the definition of a module or syntactic form or
sets a compilation parameter such as optimize-level or
case-sensitive.

Loading this from source has the effect of defining
reverse-define as a syntactic form and binding the identifier
three to 3.
The situation may be different if the file is compiled with
compile-file, however.
Unless the system or programmer takes steps to assure that the first
form is fully executed before the second expression is compiled,
the syntax expander will not recognize reverse-define as a syntactic
form and will generate code for a procedure call to reverse-define
instead of generating code to define three to be 3.
When the object file is subsequently loaded, the attempt to reference
either reverse-define or three will fail.

As it happens, when a define-syntax, module,
import, or import-only form appears at top level, as in the
example above, the compiler does indeed arrange to evaluate it before
going on to compile the remainder of the file.
If the compiler encounters a variable definition for an identifier that
was previously something else, it records that fact as well.
The compiler also generates the
appropriate code so that the bindings will be present as well when
the object file is subsequently loaded.
This solves most, but not all, problems of this nature, since most are
related to the use of define-syntax and modules.
Some problems are not so straightforwardly handled, however.
For example, assume that the file contains the following definitions
for nodups? and mvlet.

When loaded directly, this results in the definition of
nodups? as a procedure and mvlet as a syntactic
abstraction before evaluation of the mvlet expression.
Because nodups? is defined before the mvlet
expression is expanded, the call to nodups? during the
expansion of mvlet causes no difficulty.
If instead this file were compiled, using compile-file, the
compiler would arrange to define mvlet before continuing
with the expansion and evaluation of the mvlet expression,
but it would not arrange to define nodups?.
Thus the expansion of the mvlet expression would fails.

In this case it does not help to evaluate the syntactic extension alone.
A solution in this case would be to move the definition of
nodups? inside the definition for mvlet, just as
the definition for bound-id-member? is placed within
nodups?, but this does not work for help routines shared
among several syntactic definitions.
Another solution is to label the nodups? definition a
"meta" definition (see Section 11.8) but this
does not work for helpers that are used both by syntactic
abstractions and by run-time code.

A somewhat simpler problem occurs when setting parameters that affect
compilation, such as optimize-level and
case-sensitive?.
If not set prior to compilation, their settings usually will not have
the desired effect.

eval-when offers a solution to these problems by allowing the
programmer to explicitly control what forms should or should not
be evaluated during compilation.
eval-when is a syntactic form and is handled directly by the
expander.
The action of eval-when depends upon the situations argument
and whether or not the forms form1form2 ...
are being compiled via compile-file or are being evaluated
directly.
Let's consider each of the possible situation specifiers
eval, compile, load, visit, and
revisit in turn.

eval:

The eval specifier is relevant only when the eval-when
form is being
evaluated directly, i.e., if it is typed at the keyboard or loaded from a
source file.
Its presence causes form1form2 ... to be
expanded and this expansion to be included in the expansion of the
eval-when form.
Thus, the forms will be evaluated directly as if not contained within an
eval-when form.

compile:

The compile specifier is relevant only when the eval-when
form appears in a file currently being compiled.
(Its presence is simply ignored otherwise.)
Its presence forces form1form2 ... to be
expanded and evaluated immediately.

load:

The load specifier is also relevant only when the eval-when
form appears
in a file currently being compiled.
Its presence causes form1form2 ... to be
expanded and this expansion to be included in the expansion of the
eval-when form.
Any code necessary to record binding information and evaluate syntax
transformers for definitions contained in the forms is marked for
execution when the file is "visited," and any code necessary to
compute the values of variable definitions and the expressions contained
within the forms is marked for execution when the file is "revisited."

visit:

The visit specifier is also relevant only when the eval-when
form appears
in a file currently being compiled.
Its presence causes form1form2 ... to be
expanded and this expansion to be included in the expansion of the
eval-when form, with an annotation that the forms are to be
executed when the file is "visited."

revisit:

The revisit specifier is also relevant only when the eval-when
form appears
in a file currently being compiled.
Its presence causes form1form2 ... to be
expanded and this expansion to be included in the expansion of the
eval-when form, with an annotation that the forms are to be
executed when the file is "revisited."

A file is considered "visited" when it is brought in by either
load or visit and "revisited" when it is brought in
by either load or revisit.

Top-level expressions are treated as if they are wrapped in an
eval-when with situations load and eval.
This means that, by default, forms typed at the keyboard or
loaded from a source file are evaluated, and forms appearing in a
file to be compiled are not evaluated directly but are compiled for
execution when the resulting object file is subsequently loaded.

The treatment of top-level definitions is slightly more involved.
All definitions result in changes to the compile-time environment.
For example, an identifier defined by define is recorded
as a variable, and an identifier defined by define-syntax
is recorded as a keyword and associated with the value of its
right-hand-side (transformer) expression.
These changes are made at eval, compile, and load
time as if the definitions were wrapped in an eval-when with
situations eval, load, and compile.
(This behavior can be altered by changing the value of the
parameter eval-syntax-expanders-when.)
Some definitions also result in changes to the run-time environment.
For example, a variable is associated with the value of its
right-hand-side expression.
These changes are made just at evaluation and load time as if the
definitions were wrapped in an eval-when with situations
eval and load.

The treatment of local expressions or definitions (those not at top level)
that are wrapped in an eval-when depends only upon whether the
situation eval is present in the list of situations.
If the situation eval is present, the definitions and expressions
are evaluated as if they were not wrapped in an eval-when form,
i.e., the eval-when form is treated as a begin form.
If the situation eval is not present, the forms are ignored;
in a definition context, the eval-when form is treated as an
empty begin, and in an expression context, the eval-when
form is treated as a constant with an unspecified value.

Since top-level syntax bindings are established, by default, at compile
time as well as eval and load time, top-level variable bindings needed
by syntax transformers should be wrapped in an eval-when form
with situations compile, load, and eval.
We can thus nodups? problem above by enclosing the definition
of nodups? in an eval-when as follows.

This forces it to be evaluated before it is needed during the expansion
of the mvlet expression.

Just as it is useful to add compile to the default
load and eval situations, omitting options is also
useful.
Omitting one or more of compile, load, and
eval has the effect of preventing the evaluation at the given
time.
Omitting all of the options has the effect of inhibiting evaluation
altogether.

One common combination of situations is (compile eval), which by the
inclusion of compile causes the expression to be evaluated at
compile time, and by the omission of load inhibits the generation
of code by the compiler for execution when the file is subsequently loaded.
This is typically used for the definition of syntactic extensions used only
within the file in which they appear; in this case their presence in the
object file is not necessary.
It is also used to set compilation parameters that are intended to be in
effect whether the file is loaded from source or compiled via
compile-file

(eval-when (compile eval) (case-sensitive #t))

Another common situations list is (compile), which might be
used to set compilation options to be used only when the file is
compiled via compile-file.

(eval-when (compile) (optimize-level 3))

Finally, one other common combination is (load eval), which might
be useful for inhibiting the double evaluation (during the compilation of
a file and again when the resulting object file is loaded) of syntax
definitions when the syntactic extensions are not needed within
the file in which their definitions appear.

The behavior of eval-when is usually intuitive but can be
understood precisely as follows.
The syntax-case expander, which handles eval-when
forms, maintains two state sets, one for compile-time forms and
one for run-time forms.
The set of possible states in each set are "L" for load,
"C" for compile, "V" for visit, "R" for
revisit, and "E" for eval.

When compiling a file, the compile-time set initially contains "L"
and "C" and the run-time set initially contains only "L."
When not compiling a file (as when a form is evaluated by the
read-eval-print loop or loaded from a source file), both sets
initially contain only "E."
The subforms of an eval-when form at top level are expanded with
new compile- and run-time sets determined by the current sets and
the situations listed in the eval-when form.
Each element of the current set contributes zero or more elements to the
new set depending upon the given situations according to the following
table.

load

compile

visit

revisit

eval

L

L

C

V

R

---

C

---

---

---

---

C

V

V

C

V

---

---

R

R

C

---

R

---

E

---

---

---

---

E

For example, if the current compile-time state set is {L}
and the situations are load and compile, the new compile-time
state set is {L, C}, since L/load
contributes "L" and L/compile contributes "C."

The state sets determine how forms are treated by the expander.
Compile-time forms such as syntax definitions are evaluated at a time
or times determined by the compile-time state set, and run-time forms
are evaluated at a time or times determined by the run-time state set.
A form is evaluated immediately if "C" is in the state set.
Code is generated to evaluate the form at visit or revisit
time if "V" or "R" is present.
If "L" is present in the compile-time set, it is treated as "V;"
likewise, if "L" is present in the run-time set, it is treated as
"R."
If more than one of states is present in the state set, the
form is evaluated at each specified time.

"E" can appear in the state set only when not compiling a file, i.e.,
when the expander is invoked from an evaluator such as compile
or interpret.
When it does appear, the expanded form is returned from the expander to be
processed by the evaluator, e.g., compile or interpret,
that invoked the expander.

The value of the parameter eval-syntax-expanders-when actually determines
the initial compile-time state set.
The parameter is bound to a list of situations, which defaults to
(compile load eval).
When compiling a file, compile contributes "C" to the
state set, load contributes "L," visit contributes
"V," revisit contributes "R," and eval
contributes nothing.
When not compiling a file, eval contributes "E" to the
state set, and the other situations contribute nothing.
There is no corresponding parameter for controlling the initial value
of the run-time state set.

For RNRS top-level programs, eval-when is essentially ineffective.
The entire program is treated as a single expression, so eval-when
becomes a local eval-when for which only the eval
situation has any relevance.
As for any local eval-when form, the subforms are ignored if
the eval situation is not present; otherwise, they are treated as
if the eval-when wrapper were absent.

syntax: eval-syntax-expanders-whenlibraries: (chezscheme)

This parameter must be set to a list representing a set of
eval-when situations, e.g., a list containing at most one
occurrence of each of the symbols eval, compile,
load, visit, and revisit.
It is used to determine the evaluation time of syntax
definitions, module forms, and import forms are expanded.
(See the discussion of eval-when above.)
The default value is (compile load eval), which causes
compile-time information in a file to be established when the file is
loaded from source, when it is compiled via compile-file,
and when a compiled version of the file is loaded via load
or visit.

Section 12.5. Source Directories and Files

global parameter: source-directorieslibraries: (chezscheme)

The value of source-directories must be a list of strings, each
of which names a directory path.
source-directories determines the set of directories searched
for source or object files when a file is loaded via load, load-library,
load-program, include,
visit, or revisit,
when a syntax error occurs, or when a source
file is opened in the interactive inspector.

The default value is the list ("."), which means source files
will be found only in or relative to the current directory, unless named
with an absolute path.

This parameter is never altered by the system, with one exception.
The expander temporarily adds (via parameterize) the directory
in which a library file resides to the front of the source-directories
list when it compiles or loads the library from source, which it does
only if the library is not already defined.

procedure: (with-source-path whonameprocedure)libraries: (chezscheme)

The procedure with-source-path searches through the current
source-directories path, in order, for a file with the specified
name and invokes procedure on the result.
If no such file is found, an exception is raised with condition types
&assertion and &who with who as
who value.

If name is an absolute pathname or one beginning with ./
(or .\ under Windows) or ../ (or ..\ under
Windows), or if the list of source directories
contains only ".", the default, or "", which is
equivalent to ".", no searching is performed and name is
returned.

who must be a symbol, name must be a string, and
procedure should accept one argument.

The following examples assumes that the file "pie" exists
in the directory "../spam" but not in "../ham" or the current
directory.

Section 12.6. Compiler Controls

thread parameter: optimize-levellibraries: (chezscheme)

This parameter can take on one of the four values 0, 1, 2, and 3.

The optimize level determines whether code generated by the compiler
is guaranteed to be safe or not.
Safe code performs full type and bounds checking so that, for example,
an attempt to apply a non-procedure, an attempt to take the car of a
non-pair, or an attempt to reference beyond the end of a vector each
result in an exception being raised.
With unsafe code, the same situations may result in invalid memory
references, corruption of the Scheme heap (which may cause
seemingly unrelated problems later), system crashes, or other undesirable
behaviors.
The compiler generates safe code at optimize levels 0, 1, and 2, but
not at optimize level 3.
Unsafe code is typically faster, but optimize-level 3 should be used with
caution and only on sections of well-tested code that must run as quickly
as possible.

The optimize level also determines whether the compiler assumes the names
of primitives in a reverted interaction environment (see
revert-interaction-semantics) to have their original value even
if assigned.
This aspect of the optimize level has no impact on code appearing within
a library or RNRS top-level program, and it has no impact on bindings
imported from a module or library, such as the scheme module,
(chezscheme) library, or any of the rnrs libraries.
This includes the initial bindings of the default interaction environment
unless the procedure revert-interaction-semantics has been
applied to the environment or the --revert-interaction-semantics
command-line option has been used.
The compiler assumes the names of primitives in a reverted
interaction environment have their original value at optimize levels
2 and 3 but not at optimize levels 0 or 1.

The optimize level does not otherwise affect optimization, so level 1 is
effectively the same as level 0, level 2 is effectively the same as levels
0 and 1, except for its effect on code evaluated in a reverted interaction
environment, and level 3 differs from level 2 only in that code generated
with the former is unsafe rather than safe.

One way to use optimize levels is on a per-file
basis, using eval-when to force the use of a particular
optimize level at compile time.
For example, placing:

(eval-when (compile) (optimize-level 3))

at the front of a file will cause all of the forms in the file to be
compiled at optimize level 3 when the file is compiled (using
compile-file) but does not affect the optimize level used
when the file is loaded from source.
Since compile-file parameterizes optimize-level (see parameterize),
the above
expression does not permanently alter the optimize level in the
system in which the compile-file is performed.

The optimize level can also be set via the
--optimize-level
command-line option (Section 2.9).
This option is particularly useful for running RNRS top-level programs
at optimize-level 3 via the
--program command-line option,
since eval-when is ineffective for RNRS top-level programs as described
on page 322.

variable must name a primitive procedure.
The $primitive syntactic form allows control over the
optimize level at the granularity of individual primitive references,
and it can be used to access the original value
of a primitive, regardless of the lexical context or the current
top-level binding for the variable originally bound to the primitive.

The expression ($primitive variable) may
be abbreviated as #%variable.
The reader expands #% followed by an object
into a $primitive expression, much as it expands 'object
into a quote expression.

If a 2 or 3 appears in the form or between the
# and % in the abbreviated form, the compiler treats
an application of the primitive as if it were compiled
at the corresponding optimize level (see the optimize-level
parameter).
If no number appears in the form, an the application of the primitive is
treated as an optimize-level 3 application if the current optimize
level is 3;
otherwise, it is treated as an optimize-level 2 application.

To support interrupts, including keyboard, timer, and collect request
interrupts, the compiler inserts a short sequence of instructions at the
entry to each nonleaf procedure (Section 12.2).
This small overhead may be eliminated by setting
generate-interrupt-trap to #f.
The default value of this parameter is #t.

It is rarely a good idea to compile code without interrupt trap
generation, since a tight loop in the generated code may completely
prevent interrupts from being serviced, including the collect request
interrupt that causes garbage collections to occur automatically.
Disabling trap generation may be useful, however, for routines that act
simply as "wrappers" for other routines for which code is presumably
generated with interrupt trap generation enabled.
It may also be useful for short performance-critical routines with
embedded loops or recursions that are known to be short running and
that make no other calls.

thread parameter: compile-interpret-simplelibraries: (chezscheme)

At all optimize levels, when the value of
compile-interpret-simple is set to a true value (the default),
compile interprets simple
expressions.
A simple expression is one that creates no procedures.
This can save a significant amount of time over the course of many
calls to compile or eval (with current-eval
set to compile, its default value).
When set to false, compile compiles all expressions.

When this parameter is set to a true value (the default), information
about the source and contents of procedures and continuations is
generated during compilation and retained in tables associated with
each code segment.
This information allows the inspector to provide more complete
information, at the expense of using more memory and producing
larger object files (via compile-file).
Although compilation and loading may be slower when inspector
information is generated, the speed of the compiled code is not
affected.
If this parameter is changed during the compilation of a file, the
original value will be restored.
For example, if:

(eval-when (compile) (generate-inspector-information #f))

is included in a file, generation of inspector information will be
disabled only for the remainder of that particular file.

thread parameter: compile-compressedlibraries: (chezscheme)

When this parameter is set to true, the default, object files
produced by compile-file and compile-port
are compressed.

thread parameter: compile-file-messagelibraries: (chezscheme)

When this parameter is set to true, the default, compile-file,
compile-library, compile-program, and
compile-script print a message of the form:

These parameters control the operation of cp0, a source
optimization pass that runs after macro expansion and prior
to most other compiler passes.
cp0 performs procedure inlining, in which the code of one
procedure is inlined at points where it is called by other procedures,
as well as copy propagation, constant folding, useless code
elimination, and several related optimizations.
The algorithm used by the optimizer is described in detail in the paper
"Fast and effective procedure inlining" [30].

When cp0 is enabled, the programmer can count on the compiler
to fold constants, eliminate unnecessary let bindings, and
eliminate unnecessary and inaccessible code.
This is particularly useful when writing macros, since the programmer
can usually handle only the general case and let the compiler simplify
the code when possible.
For example, the programmer can define case as follows:

In the first example, the let expression produced by case
is eliminated, and in the second, the entire expression is optimized down
to the constant 17.
Although not shown by expand/optimize, the memv calls
in the output code for the first example will be replaced by calls to the
less expensive eq? by a later pass of the compiler.
Additional examples are given in the description
of expand/optimize.

The value of run-cp0 must be a procedure.
Whenever the compiler is invoked on a Scheme form, the value p
of this parameter is called to determine whether and how
cp0 is run.
p receives two arguments: cp0, the entry point into
cp0, and x, the form being compiled.
The default value of run-cp0 simply invokes cp0 on
x, then cp0 again on the result.
The second run is useful in some cases because the first run
may not eliminate bindings for certain variables that appear to be
referenced but are not actually referenced after inlining.
The marginal benefit of the second run is usually minimal, but so is the
cost.

Interesting variants include

(run-cp0 (lambda (cp0 x) x))

which bypasses (disables) cp0, and

(run-cp0 (lambda (cp0 x) (cp0 x)))

which runs cp0 just once.

The value of cp0-effort-limit determines the maximum amount
of effort spent on each inlining attempt.
The time spent optimizing a program is a linear function of this limit and the
number of calls in the program's source, so small values for this parameter
enforce a tighter bound on compile time.
When set to zero, inlining is disabled except when the name of a procedure
is referenced only once.
The value of cp0-score-limit determines the maximum amount of
code produced per inlining attempt.
Small values for this parameter limit the amount of overall code expansion.
These parameters must be set to nonnegative fixnum values.

The parameter cp0-outer-unroll-limit
controls the amount of inlining performed by the optimizer for
recursive procedures.
With the parameter's value set to the default value of 0, recursive
procedures are not inlined.
A nonzero value for the outer unroll limit allows calls external to
a recursive procedure to be inlined.
For example, the expression

Interesting effects can be had by varying several of these parameters at
once.
For example, setting the
effort and outer unroll limits to large values and the score limit
to 1 has the effect of inlining even complex recursive procedures
whose values turn out to be constant at compile time without risking
any code expansion.
For example,

would be left unchanged, although the optimizer may take a while to
reach this decision if the effort and outer unroll limits are large.

Section 12.7. Profiling

With profiling enabled,
the compiler instruments the code it produces to count the number of
times each section of code is executed.
This information can be
displayed in HTML format or via the
profile viewer included with the
Scheme Widget Library (SWL).

Profiling involves four steps:

compiling code with profile instrumentation enabled,

running the code to generate profiling information,

dumping the profile data in raw or HTML format, and

viewing the profile data.

To compile the code with profiling enabled, set the parameter
compile-profile to #t while compiling your application
or loading it from source.
Let's assume that the file /tmp/fatfib/fatfib.ss contains the following source code.

After the run (or multiple runs), we
dump the profile information as a set of html files using
profile-dump-html.

(profile-dump-html)

This creates a file named profile.html containing a summary of the profile
information gathered during the run.
If we view this file in a browser, we should see something like the
following.

The most frequently executed code is highlighted in colors closer to
red in the visible spectrum, while
the least frequently executed code is highlighted in colors closer to
violet.
Each of the entries in the lists of files and hot spots are links into
additional generated files, one per source file (provided
profile-dump-html was able to locate an unmodified copy of
the source file).
In this case, there is only one, fatfib.ss.html.
If we move to that file, we should see something like this:

As in the summary, the code is color-coded according to frequency
of execution.

Profiling information may also be viewed via the SWL profview
application.
To use profview, we must first dump the information to a
file using fasl-write and profile-dump.

Once we have the profile data, we can start SWL to run the
profview application.
After starting up SWL, we load profview.ss as shown below.
(SWL Version 1.0d is assumed.)

(load "/usr/lib/swl1.0d/apps/profview/profview.ss")

(The actual location of profview.ss may vary from one installation to
another. If you cannot locate profview.ss on your system, it can be
found in the source distribution of SWL.)

The profilew viewer can then be started via p-view.

(p-view (with-input-from-file "/tmp/fatfib/pdump" read))

The profile information should look something like the
following.

If the application spans multiple files, multiple files will be displayed.

If neither method for displaying profile information is suitable,
profile-dump-list may be used to generate a list of profile
entries, which may then be analyzed manually or via a custom
profile-viewing application.

thread parameter: compile-profilelibraries: (chezscheme)

When this parameter is set to a true value, the compiler instruments
the code it generates with instructions that count the number of times
each section of code is executed.
This information may be viewed in html form via profile-dump-html
or dumped in raw form via profile-dump and viewed
with the profview profile viewer
distributed with SWL as described above.
Setting this parameter also forces source information to be retained,
regardless of the setting of generate-inspector-information,
since this information is required by the profile viewer.

The default value of compile-profile is #f.
The code generated when compile-profile is set to
#t is larger and less efficient, so this parameter
should be set only when profile information is needed.

The source optimizer, "cp0," eliminates some calls via inlining and
other optimizations.
This can lead to apparently incomplete or misleading profile output.
Because of this, it is often useful to disable cp0 via
the run-cp0 parameter (page 327) when
compiling with profiling enabled.
For example:

This procedure produces one or more HTML files, including
profile.html, which contains color-coded summary information,
and one file source.html for each source
file source containing a color-coded copy of the
source code, as described in the lead-in to this section.
If prefix is specified, it must be a string and is prepended
to the names of the generated HTML files.
For example, if prefix is "/tmp/", the generated
files are placed in the directory /tmp.

thread parameter: (profile-palette)libraries: (chezscheme)

This value of this parameter must be a nonempty vector of at least
three pairs.
The car of each pair is a background color and the cdr is a foreground
(text) color.
Each color must be a string, and each string should contain an HTML
cascading style sheet (css) color specifier.
The first pair is used for unprofiled code, and the the second is used
for unexecuted profiled code.
The third is used for code that is executed least frequently, the fourth
for code executed next-least frequently, and so on, with the last
being used for code that is executed most frequently.
Programmers may wish to supply their own palette to enhance visibility
or to change the number of colors used.

By default, a black background is used for unprofiled code, and a gray
background is used for unexecuted profiled code.
Background colors ranging from purple to red are used for executed
profiled code, depending on frequency of execution, with red for the most
frequently executed code.

This value of this parameter must be a string or #f.
If it is a string, the string should contain an HTML cascading style sheet (css)
color specifier.
If the parameter is set to string, profile-dump-html includes line numbers
in its html rendering of each source file, using the specified color.
If the parameter is set to #f, no line numbers are included.

Each profile entry in the returned list is itself a list containing the
following elements, which identify one block of code and how many times it
was executed.

execution count

pathname

beginning file position (inclusive)

ending file position (exclusive)

line number of beginning file position

character position of beginning file position

profile-dump-list may be unable to locate an unmodified copy
of the file in the current source directories
or at the absolute address, if an absolute address was used when
the file was compiled or loaded.
If this happens, the line number and character position of the beginning
file position are #f and the pathname is the pathname originally
used.
A warning is also issued (an exception with condition type
&warning is raised) unless the warn? argument is provided
and is false.

Otherwise, the pathname is the path to an unmodified copy of the source
and the line and character positions are set to nonnegative integers.

In either case, the execution count, beginning file position, and ending
file position are all nonnegative integers and the pathname is a string.

The information returned by profile-dump-list can be used to
implement a custom viewer or used as input for offline analysis of
profiling information.

This procedure produces a Scheme object containing a dump of all
profiling information gathered since startup or the last call to
profile-clear.
The format of the output is unspecified but is suitable input to the
SWL profview profile viewer, which is described in the
lead-in to this section.

Section 12.8. Waiter Customization

Chez Scheme interacts with the user
through a waiter, or read-eval-print loop (REPL).
The waiter operates within a context called a café.
When the system starts up, the user is placed in a café and
given a waiter.
new-cafe opens a new Scheme café, stacked on top of the old one.
In addition to starting the waiter, new-cafe sets up the café's
reset and exit handlers (see reset-handler and exit-handler).
Exiting a café resumes the continuation of the call
to new-cafe that created the café.
Exiting from the initial café leaves Scheme altogether.
A café may be exited from either by an explicit call to exit or
by receipt of end-of-file ("control-D" on Unix systems) in response
to the waiter's prompt.
In the former case, any values passed to exit are returned from
new-cafe.

If the optional eval-proc argument is specified, eval-proc
is used to evaluate forms entered from the console.
Otherwise, the value of the parameter current-eval is used.
eval-proc must accept one argument, the expression to evaluate.

Interesting values for eval-proc include expand,
which causes the macro expanded value of each expression entered to
be printed and (lambda (x) x), which simply causes each expression
entered to be printed.
An arbitrary procedure of one argument may be used to facilitate
testing of a program on a series of input values.

The default waiter reader (see waiter-prompt-and-read) displays
the current waiter prompt (see waiter-prompt-string)
to the current value of console-output-port and
reads
from the current value of console-input-port.
The default waiter printer (see waiter-write) sends output
to the current value of console-output-port.
These parameters, along with current-eval,
can be modified to change the behavior of the waiter.

thread parameter: waiter-prompt-stringlibraries: (chezscheme)

The value of waiter-prompt-string must be a string.
It is used by the default waiter prompter (see the parameter
waiter-prompt-and-read) to print a prompt.
Nested cafés
are marked by repeating the prompt string once for each nesting level.

waiter-prompt-and-read must be set to a procedure.
It is used by the waiter to
print a prompt and read an expression.
The value of waiter-prompt-and-read is called by the waiter with a
positive integer that indicates the café nesting level.
It should return an expression to be evaluated by the current
evaluator (see new-cafe and current-eval).

procedure: (default-prompt-and-read level)libraries: (chezscheme)

level must be a positive integer indicating the cafeé nesting
level as described above.

This procedure is the default value of the waiter-prompt-and-read
parameter whenever the expression editor
(Section 2.2, Chapter 14) is
not enabled.
It might be defined as follows.

The value of waiter-write must be a procedure.
The waiter uses the value of waiter-write to print the results
of each expression read and evaluated by the waiter.
The following example installs a procedure equivalent to the default
waiter-write:

exit invokes the current exit handler (see
exit-handler), passing along its arguments, if any.

thread parameter: exit-handlerlibraries: (chezscheme)

The value of this parameter must be a procedure and should accept any
number of arguments.
The current exit handler is called by exit.

The default exit handler exits from the current café,
returning its arguments as the values of the call to
new-cafe that created the current café.
If the current café is the original café, or if exit
is called from a script, exit exits from Scheme.
In this case, the exit code for the Scheme process is 0 if
no arguments were supplied or if the first argument is void,
the value of the first argument
if it is a 32-bit exact integer, and -1 otherwise.

abort invokes the current abort handler (see abort-handler),
passing along its argument, if any.

thread parameter: abort-handlerlibraries: (chezscheme)

The value of this parameter must be a procedure and should accept either
zero arguments or one argument.
The current abort handler is called by abort.

The default abort handler exits the Scheme process.
The exit code for the Scheme process is -1 if no arguments were supplied,
0 if the first argument is void, the value of the first argument if it is
a 32-bit exact integer, and -1 otherwise.

global parameter: scheme-startlibraries: (chezscheme)

The value of scheme-start is a procedure that determines the
system's action upon start-up.
The procedure receives zero or more arguments, which are strings
representing the file names (or command-line arguments not recognized
by the Scheme executable) after given on the command line.
The default value first loads the files named by the arguments, then
starts up the initial café:

(lambda fns
(for-each load fns)
(new-cafe))

scheme-start may be altered to start up an application or to
perform customization prior to normal system start-up.

To have any affect, this parameter must be set within a boot file or prior to the
saving of a heap that is subsequently loaded.
(See Chapter 2.)

global parameter: scheme-scriptlibraries: (chezscheme)

The value of scheme-script is a procedure that determines the
system's action upon start-up,
when the --script option is used.
The procedure receives one or more arguments.
The first is a string identifying the script filename and the remainder
are strings representing the remaining file names (or command-line
arguments not recognized by the Scheme executable) given on the command
line.
The default value of this parameter is a procedure that sets the
command-line and command-line-arguments parameters,
loads the script using load, and returns void, which is
translated into a 0 exit status for the script process.

scheme-script may be altered to start up an application or to
perform customization prior to normal system start-up.

To have any affect, this parameter must be set within a boot file or prior to the
saving of a heap that is subsequently loaded.
(See Chapter 2.)

global parameter: scheme-programlibraries: (chezscheme)

The value of scheme-program is a procedure that determines the
system's action upon start-up
when the --program (RNRS top-level program) option is used.
The procedure receives one or more arguments.
The first is a string identifying the program filename and the remainder
are strings representing the remaining file names (or command-line
arguments not recognized by the Scheme executable) given on the command
line.
The default value of this parameter is a procedure that sets the
command-line and command-line-arguments parameters,
loads the program using load-program, and returns void, which is
translated into a 0 exit status for the script process.

scheme-program may be altered to start up an application or to
perform customization prior to normal system start-up.

To have any affect, this parameter must be set within a boot file or prior to the
saving of a heap that is subsequently loaded.
(See Chapter 2.)

global parameter: command-linelibraries: (chezscheme)

This parameter is set by the default values of scheme-script
and scheme-program
to a list representing the command line, with the script name followed
by the command-line arguments, when the --script or
--program option is used on system startup.

global parameter: command-line-argumentslibraries: (chezscheme)

This parameter is set by the default values of scheme-script
and scheme-program
to a list of the command-line arguments when the --script
or --program option is used on system startup.

global parameter: suppress-greetinglibraries: (chezscheme)

The value of suppress-greeting is a boolean value that determines
whether Chez Scheme prints an identifying banner and copyright notice.
The parameter defaults to #f but may be set to #t for
use in batch processing applications where the banner would be disruptive.

To have any affect, this parameter must be set within a boot file or prior to the
saving of a heap that is subsequently loaded.
(See Chapter 2.)

Section 12.9. Transcript Files

A transcript file is a record of an interactive session.
It is also useful as a "quick-and-dirty" alternative to opening an
output file and using explicit output operations.

transcript-on opens the file named by path for output,
and it copies to this file all input from the current input port and
all output to the current output port.
An exception is raised with condition-type i/o-filename if the
file cannot be opened for output.

path must be a string.
transcript-cafe opens a transcript file as with
transcript-on and
enters a new café; exiting
from this café (see exit) also ends transcription and closes the
transcript file.
Invoking transcript-off while in a transcript café ends transcription
and closes the transcript file but does not cause an exit from the
café.

Section 12.10. Times and Dates

This section documents procedures for handling times and dates. Most of
the procedures described here are proposed in
SRFI 19:
Time Data Types and Procedures, by Will Fitzgerald.

Times are represented by time objects.
Time objects record the nanosecond and second of a particular time
or duration, along with a time type that identifies the nature
of the time object.
The time type is one of the following symbols:

time-utc:

The time elapsed since the "epoch:" 00:00:00 UTC, January 1, 1970,
subject to adjustment, e.g., to correct for leap seconds.

time-monotonic:

The time elapsed since some arbitrary point in the past, ideally
not subject to adjustment.

time-duration:

The time elapsed between two times.
When used as an argument to current-time, it behaves like
time-monotonic, but may also used to represent the result
of subtracting two time objects.

time-process:

The amount of CPU time used by the current process.

time-thread:

The amount of CPU time used by the current thread.
It is the same as time-process if
not running threaded or if the system does not allow individual
thread times to be determined.

A time-object second is an exact integer (possibly negative),
and a nanosecond is an exact nonnegative integer less than 109.
The second and nanosecond of a time object may be converted to
an aggregate nanosecond value by scaling the
seconds by 109 and adding the nanoseconds.
Thus, if the second and nanosecond of a time object are 5 and 10,
the time object represents 5000000010 nanoseconds (5.000000010 seconds).
If the second and nanosecond are -5 and 10, the time object
represents -4999999990 nanoseconds (-4.999999990 seconds).

Dates are represented by date objects.
A date object records the nanosecond, second, minute, hour, day, month,
and year of a particular date, along with an offset that identifies the
time zone.

As for time objects, a nanosecond is an exact integer less than 109.
A date-object second is, however, an exact nonnegative integer
less than 62.
(The values 61 and 62 allow for leap seconds.)
A minute is an exact nonnegative integer less than 60, and
an hour is an exact nonnegative integer less than 24.
A day is an exact nonnegative integer in ranging from 1 representing
the first day of the month to n, where n is the number of
days in the date's month and year.
A month is an exact nonnegative integer ranging from 1 through 12,
where 1 represents January, 2 represents February, and so on.
A year must be an exact integer.
Years less than 1970 or greater than 2038 may not be supported
depending on limitations of the underlying implementation.
A time-zone offset represents the time-zone offset, in seconds, from UTC.
It is an exact integer in the range -86400 to +86400, inclusive.
For example, Eastern Standard Time (EST), which is 5 hours east, has
offset 5 × 3600 = -18000.
The offset for Eastern Daylight Time (EDT) is -14400.
UTC is represented by offset zero.

procedure: (current-time)procedure: (current-time time-type)returns: a time object representing the current time
libraries: (chezscheme)

time-type must be one of the time-type symbols listed above
and defaults to time-utc.

time must be a time object.
type must be one of the time-type symbols listed above.
nsec represents nanoseconds and must be an exact nonnegative
integer less than 109.
sec represents seconds and must be an exact integer.

Each of these procedures modifies the time object, changing one aspect
while leaving the others unaffected.
For example, set-time-nanosecond! changes the nanosecond of
time without changing the second or type.
In particular, no conversion of values is performed when the type of a time
object is changed.

offset represents the time-zone offset in seconds east of UTC,
as described above.
It must be an exact integer in the range -86400 to
+86400, inclusive and defaults to the local time-zone offset.
UTC may be obtained by passing an offset of zero.

nsec represents nanoseconds and must be an exact nonnegative integer
less than 109.
sec represents seconds and must be an exact nonnegative integer
less than 62.
min represents minutes and must be an exact nonnegative integer
less than 60.
hour must be an exact nonnegative integer less than 24.
day must be an exact integer, 1 ≤ day ≤ 31.
(The actual upper limit may be less depending on the month and year.)
mon represents the month must be an exact integer, 1 ≤ mon ≤ 12.
year must be an exact integer.
It should be at least 1970.
offset represents the time-zone offset in seconds east of UTC,
as described above.
It must be an exact integer in the range -86400 to +86400, inclusive.
UTC may be specified by passing an offset of zero.

procedure: (date-nanosecond date)returns: the nanosecond of dateprocedure: (date-second date)returns: the second of dateprocedure: (date-minute date)returns: the minute of dateprocedure: (date-hour date)returns: the hour of dateprocedure: (date-day date)returns: the day of dateprocedure: (date-month date)returns: the month of dateprocedure: (date-year date)returns: the year of dateprocedure: (date-zone-offset date)returns: the time-zone offset of datelibraries: (chezscheme)

These procedures allow the day-of-week or day-of-year to be determined for
the date represented by date.
A week-day is an exact nonnegative integer less than 7, where
0 represents Sunday, 1 represents Monday, and so on.
A year-day is an exact nonnegative integer less than 367, where
0 represents the first day of the year (January 1), 1 the
second day, 2 the third, and so on.

These procedures are used to convert between time and date objects.
The time argument to time-utc->date must have time-type
utc, and date->time-utc always returns a time
object with time-type utc.

For time-utc->date,
offset represents the time-zone offset in seconds east of UTC,
as described at the beginning of this section.
It must be an exact integer in the range -86400 to
+86400, inclusive and defaults to the local time-zone offset.
UTC may be obtained by passing an offset of zero.

time must be a time object with type time-duration.
sleep causes the invoking thread to suspend operation for
approximately the amount of time indicated by the time object, unless
the process receives a signal that interrupts the sleep operation.
The actual time slept depends on the granularity of the system clock
and how busy the system is running other threads and processes.

Section 12.11. Timing and Statistics

This section documents procedures for timing computations.
The current-time procedure described in
Section 12.10 may also be used to
time computations.

syntax: (time expr)returns: the values of exprlibraries: (chezscheme)

time evaluates expr and, as a side-effect, prints (to the
console-output port) the amount of cpu time, the amount of real time,
the number of bytes allocated, and the amount of collection overhead
associated with evaluating expr.

This procedure displays a running total of the amount of
cpu time, real time, bytes allocated, and collection overhead.
If textual-output-port is not supplied, it defaults to the current output port.

procedure: (cpu-time)returns: the amount of cpu time consumed since system start-up
libraries: (chezscheme)

The amount is in milliseconds.
The amount includes "system" as well as "user" time, i.e., time
spent in the kernel on behalf of the process as well as time spent in
the process itself.

procedure: (real-time)returns: the amount of real time that has elapsed since system start-up
libraries: (chezscheme)

The amount is in milliseconds.

procedure: (bytes-allocated)procedure: (bytes-allocated g)returns: the number of bytes currently allocated
libraries: (chezscheme)

If g is supplied, bytes-allocated returns the number of
bytes currently allocated in the specified generation.
g must be a nonnegative exact integer no greater than the
maximum nonstatic generation, i.e., the
value returned by collect-maximum-generation, or the symbol
static.
If g is not supplied, bytes-allocated returns the total
number of bytes allocated in all generations.

statistics packages together various timing and allocation
statistics into a single sstats structure.
A sstats structure has the following fields:

cpu,

the cpu time consumed,

real,

the elapsed real time,

bytes,

the number of bytes allocated.

gc-count,

the number of collections.

gc-cpu,

the cpu time consumed during collections,

gc-real,

the elapsed real time during collections, and

gc-bytes,

the number of bytes reclaimed by the collector.

All values are computed since system start-up.
All times are calculated in milliseconds.

The sstats structure and the corresponding allocation procedure,
predicate, accessors, and setters described below are defined as vector-based
structures as if via define-structure
(Section 16.3) as follows.

s1 and s2 must be sstats structures.
sstats-difference subtracts each field of s2 from the
corresponding field of s1 to produce the result sstats
structure.
It coerces negative results to zero.
sstats-difference is commonly used to measure the time elapsed
between two points in the execution of a program.
In doing such comparisons, it is often useful to adjust for overhead
in the statistics gathering functions by calling statistics
twice before timing a computation and once after; the difference in the
results of the first two calls is then subtracted from the difference in
the results of the last two calls.
After adjusting for overhead, small negative results could occur for very
fast running computations without the coercion of negative results to
zero by sstats-difference.

s must be a sstats structure.
If textual-output-port is not supplied, it defaults to the current output port.
sstats-print displays the fields of s in a manner similar
to display-statistics and time.

Section 12.12. Parameters

This section describes mechanisms for creating and manipulating parameters.
New parameters may be created conveniently with make-parameter.
Nothing distinguishes parameters from other
procedures, however, except for their behavior.
If more complicated actions must be taken when a parameter is invoked
than can be accommodated easily through the make-parameter mechanism,
the parameter may be defined directly with case-lambda.

make-parameter accepts one or two arguments.
The first argument is the initial value of the internal variable, and
the second, if present, is a filter applied to the initial value
and all subsequent values.
The filter should accept one argument.
If the value is not appropriate, the filter should raise an exception or
convert the value into a more appropriate form.

Using the syntactic form parameterize, the values of parameters can
be changed in a manner analogous to fluid-let for ordinary variables.
Each param is set to the value of the corresponding
expr while the body is evaluated.
When control leaves the body by normal return or by the invocation of a
continuation created outside of the body, the parameters are restored to
their original values.
If control returns to the body via a continuation created during the
execution of the body, the parameters are again set to their temporary
values.

putenv stores the key, value pair in the
environment of the process,
where it is available to the current process (e.g., via getenv)
and any spawned processes.
The key and value are copied into storage allocated outside of
the Scheme heap; this space is never reclaimed.

get-registry returns a string containing the registry
value of key if the value exists.
If no registry value for key exists, get-registry returns
#f.

put-registry! sets the registry
value of key to val.
It raises an exception with condition type &assertion if the
value cannot be set, which may happen if
the user has insufficient access.

remove-registry! removes the registry
key or value named by key.
It raises an exception with condition type &assertion if the
value cannot be removed.
Reasons for failure include the key not being present, the user having
insufficient access, or key being a key with subkeys.

Section 12.14. Subset Modes

thread parameter: subset-modelibraries: (chezscheme)

The value of this parameter
must be #f (the default) or the symbol system.
Setting subset-mode to system allows the manipulation
of various undocumented system variables, data structures, and
settings.
It is typically used only for system debugging.