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.

procedure: (warning who msg irritant ...)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (assertion-violationf who msg irritant ...)
returns: does not return
procedure: (errorf who msg irritant ...)
returns: does not return
procedure: (warningf who msg irritant ...)
returns: unspecified
libraries: (chezscheme)

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.

syntax: &format
procedure: (make-format-condition)
returns: a condition of type &format
procedure: (format-condition? obj)
returns: #t if obj is a condition of type &format, #f otherwise
libraries: (chezscheme)

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.

(define-condition-type &format &condition
  make-format-condition format-condition?)

syntax: &source
procedure: (make-source-condition form)
returns: a condition of type &source
procedure: (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.

(define-condition-type &source &condition
  make-source-condition source-condition?
  (form source-condition-form))

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

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.

(define-condition-type &continuation &condition
  make-continuation-condition continuation-condition?
  (continuation condition-continuation))

procedure: (display-condition obj)
procedure: (display-condition obj textual-output-port)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (default-exception-handler obj)
returns: unspecified
libraries: (chezscheme)

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-exception
libraries: (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-handler
libraries: (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-condition
libraries: (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-state
libraries: (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.

procedure: (create-exception-state)
procedure: (create-exception-state procedure)
libraries: (chezscheme)

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.

Calls to the break handler occur immediately whenever break is called.

procedure: (break who msg irritant ...)
procedure: (break who)
procedure: (break)
returns: unspecified
libraries: (chezscheme)

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-handler
libraries: (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-handler
libraries: (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.

(keyboard-interrupt-handler 
  (lambda ()
    (newline (console-output-port))
    (reset)))

procedure: (set-timer n)
returns: previous current timer value
libraries: (chezscheme)

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-handler
libraries: (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.

procedure: (disable-interrupts)
procedure: (enable-interrupts)
returns: disable count
libraries: (chezscheme)

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.

syntax: (with-interrupts-disabled body1 body2 ...)
syntax: (critical-section body1 body2 ...)
returns: the values of the body body1 body2 ...
libraries: (chezscheme)

with-interrupts-disabled evaluates the body body1 body2 ... 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.

with-interrupts-disabled can be defined as follows.

(define-syntax with-interrupts-disabled
  (syntax-rules ()
    [(_ b1 b2 ...)
     (dynamic-wind
       disable-interrupts
       (lambda () b1 b2 ...)
       enable-interrupts)]))

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.

procedure: (register-signal-handler sig procedure)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (environment? obj)
returns: #t if obj is an environment, otherwise #f
libraries: (chezscheme)

(environment? (interaction-environment)) <graphic> #t
(environment? 'interaction-environment) <graphic> #f
(environment? (copy-environment (scheme-environment))) <graphic> #t
(environment? (environment '(prefix (rnrs) $rnrs-))) <graphic> #t

procedure: (environment-mutable? env)
returns: #t if env is mutable, otherwise #f
libraries: (chezscheme)

(environment-mutable? (interaction-environment)) <graphic> #t
(environment-mutable? (scheme-environment)) <graphic> #f
(environment-mutable? (copy-environment (scheme-environment))) <graphic> #t
(environment-mutable? (environment '(prefix (rnrs) $rnrs-))) <graphic> #f

procedure: (scheme-environment)
returns: an environment
libraries: (chezscheme)

scheme-environment returns an environment containing the initial top-level bindings. This environment corresponds to the scheme module.

The environment returned by this procedure is immutable.

(define cons 3)
(top-level-value 'cons (scheme-environment)) <graphic> #<procedure cons>
(set-top-level-value! 'cons 3 (scheme-environment)) <graphic> exception

procedure: (ieee-environment)
returns: an IEEE/ANSI standard compatibility environment
libraries: (chezscheme)

ieee-environment returns an environment containing bindings for the keywords and variables whose meanings are defined by the IEEE/ANSI Standard for Scheme [25].

The bindings for each of the identifiers in the IEEE environment are those of the corresponding Revised6 Report library, so this does not provide full backward compatibility.

The environment returned by this procedure is immutable.

(define cons 3)
(top-level-value 'cons (ieee-environment)) <graphic> #<procedure cons>
(set-top-level-value! 'cons 3 (ieee-environment)) <graphic> exception

thread parameter: interaction-environment
libraries: (chezscheme)

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.

(define cons 3)
cons <graphic> 3
(top-level-value 'cons (interaction-environment)) <graphic> 3

(interaction-environment (scheme-environment))
cons <graphic> #<procedure cons>
(set! cons 3) <graphic> exception: attempt to assign immutable variable
(define cons 3) <graphic> exception: invalid definition in immutable environment

procedure: (copy-environment env)
procedure: (copy-environment env mutable?)
procedure: (copy-environment env mutable? syms)
returns: a new environment
libraries: (chezscheme)

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.

(define e (copy-environment (scheme-environment)))
(eval '(define cons +) e)
(eval '(cons 3 4) e)                    <graphic> 7
(eval '(cons 3 4) (scheme-environment)) <graphic> (3 . 4)

procedure: (revert-interaction-semantics)
procedure: (revert-interaction-semantics env)
returns: unspecified
libraries: (chezscheme)

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:

(cons 3 4) <graphic> (3 . 4)
(set! cons 3) <graphic> exception: attempt to assign immutable variable
(define cons (lambda (x) (lambda (y) (lambda (p) ((p x) y)))))
(((cons 3) 4) (lambda (a) (lambda (d) d))) <graphic> 4
(set! cons 3)
cons <graphic> 3

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.

(define f (lambda (x) (+ x 5)))
(f 3) <graphic> 8
(define + -)
(f 3) <graphic> 8
(define f (lambda (x) (+ x 5)))
(f 3) <graphic> -2

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.

(revert-interaction-semantics)
(cons 3 4) <graphic> (3 . 4)
(set! cons 3)
cons <graphic> 3
(define f (lambda (x) (+ x 5)))
(f 3) <graphic> 8
(define + -)
(f 3) <graphic> -2

The command-line option --revert-interaction-semantics implicitly invokes this procedure on the initial interaction environment at system start-up time.

procedure: (environment-symbols env)
returns: a list of symbols
libraries: (chezscheme)

This procedure returns a list of symbols representing the identifiers bound in environment env. It is primarily useful in building the list of symbols to be copied from one environment to another.

(define listless-environment
  (copy-environment
    (scheme-environment)
    #t
    (remq 'list (environment-symbols (scheme-environment)))))
(eval '(let ([x (cons 3 4)]) x) listless-environment) <graphic> (3 . 4)
(eval '(list 3 4) listless-environment) <graphic> exception

procedure: (apropos-list s)
procedure: (apropos-list s env)
returns: see below
libraries: (chezscheme)

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.

(library (a) (export a-vector-sortof) (import (rnrs))
  (define a-vector-sortof '(vector 1 2 3)))
(apropos-list 'vector-sort) <graphic>
  (vector-sort vector-sort!
   ((a) a-vector-sortof)
   ((chezscheme) vector-sort vector-sort!)
   ((rnrs) vector-sort vector-sort!)
   ((rnrs sorting) vector-sort vector-sort!)
   ((scheme) vector-sort vector-sort!))

procedure: (apropos s)
procedure: (apropos s env)
returns: unspecified
libraries: (chezscheme)

apropos is like apropos-list except the information is displayed to the current output port, as shown in the following transcript.

> (library (a) (export a-vector-sortof) (import (rnrs))
    (define a-vector-sortof '(vector 1 2 3)))
> (apropos 'vector-sort)
interaction environment:
  vector-sort, vector-sort!
(a):
  a-vector-sortof
(chezscheme):
  vector-sort, vector-sort!
(rnrs):
  vector-sort, vector-sort!
(rnrs sorting):
  vector-sort, vector-sort!
(scheme):
  vector-sort, vector-sort!

Section 12.4. Compilation, Evaluation, and Loading

procedure: (eval obj)
procedure: (eval obj env)
returns: value of the Scheme form represented by obj
libraries: (chezscheme)

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-eval
libraries: (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).

(current-eval interpret)
(+ 1 1) <graphic> 2

(current-eval (lambda (x . ignore) x))
(+ 1 1) <graphic> (+ 1 1)

procedure: (compile obj)
procedure: (compile obj env)
returns: value of the Scheme form represented by obj
libraries: (chezscheme)

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.

procedure: (interpret obj)
procedure: (interpret obj env)
returns: value of the Scheme form represented by obj
libraries: (chezscheme)

interpret is like compile, except that the expression is interpreted rather than compiled. interpret may be used as a replacement for compile, with the following caveats:

interpret is sometimes faster than compile when the form to be evaluated is short running, since it avoids some of the work done by compile prior to evaluation.

procedure: (load path)
procedure: (load path eval-proc)
returns: unspecified
libraries: (chezscheme)

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 "myfile.ss"
  (lambda (x)
    (pretty-print
      (if (annotation? x)
          (annotation-stripped x)
          x))
    (newline)
    (eval x)))

pretty-prints each expression before evaluating it.

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

procedure: (load-library path)
procedure: (load-library path eval-proc)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (load-program path)
procedure: (load-program path eval-proc)
returns: unspecified
libraries: (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.

For example, assume the file t1.ss contains the following forms:

(define-syntax a (identifier-syntax 3))
(module m (x) (define x 4))
(define y 5)

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.

procedure: (compile-file input-filename)
procedure: (compile-file input-filename output-filename)
returns: unspecified
libraries: (chezscheme)

input-filename and output-filename must be strings.

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:

optimize-level
run-cp0
cp0-effort-limit
cp0-score-limit
cp0-outer-unroll-limit
generate-inspector-information
compile-profile
generate-interrupt-trap

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.

procedure: (compile-script input-filename)
procedure: (compile-script input-filename output-filename)
returns: unspecified
libraries: (chezscheme)

input-filename and output-filename must be strings.

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.

procedure: (compile-library input-filename)
procedure: (compile-library input-filename output-filename)
returns: unspecified
libraries: (chezscheme)

input-filename and output-filename must be strings.

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-filename output-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.

procedure: (compile-port textual-input-port binary-output-port)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (make-boot-file output-filename base-boot-list input-filename ...)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (make-boot-header output-filename base-boot1 base-boot2...)
returns: unspecified
libraries: (chezscheme)

This procedure has been subsumed by make-boot-file and is provided for backward compatibility. The call

(make-boot-header output-filename base-boot1 base-boot2 ...)

is equivalent to

(make-boot-file output-filename '(base-boot1 base-boot2 ...))

procedure: (machine-type)
returns: the current machine type
libraries: (chezscheme)

Consult the release notes for the current version of Chez Scheme for a list of supported machine types.

procedure: (expand obj)
procedure: (expand obj env)
returns: expansion of the Scheme form represented by obj
libraries: (chezscheme)

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-expand
libraries: (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.

procedure: (sc-expand obj)
procedure: (sc-expand obj env)
returns: the expanded form of obj
libraries: (chezscheme)

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 obj env)
returns: result of expanding and optimizing form represented by obj
libraries: (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.

(expand/optimize
  '(let ([y '(3 . 4)])
     (+ (car y) (cdr y)))) <graphic> 7

(print-gensym #f)
(expand/optimize
  '(let ([y '(3 . 4)])
     (lambda (x)
       (* (+ (car y) (cdr y)) x)))) <graphic> (lambda (x) (#2%* 7 x))

(expand/optimize
  '(let ([n (expt 2 10)])
     (define even?
       (lambda (x) (or (zero? x) (not (odd? x)))))
     (define odd?
       (lambda (x) (not (even? (- x 1)))))
     (define f
       (lambda (x)
         (lambda (y)
           (lambda (z)
             (if (= z 0) (omega) (+ x y z))))))
     (define omega
       (lambda ()
         ((lambda (x) (x x)) (lambda (x) (x x)))))
     (let ([g (f 1)] [m (f n)])
       (let ([h (if (> ((g 2) 3) 5)
                    (lambda (x) (+ x 1))
                    odd?)])
         (h n))))) <graphic> 1025

syntax: (eval-when situations form1 form2 ...)
returns: see below
libraries: (chezscheme)

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.

For example, assume that a file contains the following two forms:

(define-syntax reverse-define
  (syntax-rules ()
    [(_ e x) (define x e)]))

(reverse-define 3 three)

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.

(define nodups?
  (lambda (ids)
    (define bound-id-member?
      (lambda (id ids)
        (and (not (null? ids))
             (or (bound-identifier=? id (car ids))
                 (bound-id-member? id (cdr ids))))))
    (or (null? ids)
        (and (not (bound-id-member? (car ids) (cdr ids)))
             (nodups? (cdr ids))))))

(define-syntax mvlet
  (lambda (x)
    (syntax-case x ()
      [(_ ((x ...) expr) b1 b2 ...)
       (and (andmap identifier? #'(x ...))
            (nodups? #'(x ...)))
       #'(call-with-values
           (lambda () expr)
           (lambda (x ...) b1 b2 ...))])))

(mvlet ((a b c) (values 1 2 3))
  (list (* a a) (* b b) (* c c)))

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 form1 form2 ... 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 form1 form2 ... 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 form1 form2 ... 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 form1 form2 ... 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 form1 form2 ... 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 form1 form2 ... 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.

(eval-when (compile load eval)
  (define nodups?
    (lambda (ids)
      (define bound-id-member?
        (lambda (id ids)
          (and (not (null? ids))
               (or (bound-identifier=? id (car ids))
                   (bound-id-member? id (cdr ids))))))
      (or (null? ids)
          (and (not (bound-id-member? (car ids) (cdr ids)))
               (nodups? (cdr ids)))))))

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-when
libraries: (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-directories
libraries: (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 who name procedure)
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.

(define find-file
  (lambda (fn)
    (with-source-path 'find-file fn values)))

(find-file "pie") <graphic> "pie"

(source-directories '("." "../ham"))
(find-file "pie") <graphic> exception in find-file: pie not found

(source-directories '("." "../spam"))
(find-file "pie") <graphic> "../spam/pie"

(source-directories '("." "../ham"))
(find-file "/pie") <graphic> "/pie"

(source-directories '("." "../ham"))
(find-file "./pie") <graphic> "./pie"

(source-directories '("." "../spam"))
(find-file "../pie") <graphic> "../ham/pie"

Section 12.6. Compiler Controls

thread parameter: optimize-level
libraries: (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.

syntax: ($primitive variable)
syntax: #%variable
syntax: ($primitive 2 variable)
syntax: #2%variable
syntax: ($primitive 3 variable)
syntax: #3%variable
returns: the primitive value for variable
libraries: (chezscheme)

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.

(#%car '(a b c)) <graphic> a
(let ([car cdr]) (car '(a b c))) <graphic> (b c)
(let ([car cdr]) (#%car '(a b c))) <graphic> a
(begin (set! car cdr) (#%car '(a b c))) <graphic> a

thread parameter: generate-interrupt-trap
libraries: (chezscheme)

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-simple
libraries: (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.

thread parameter: generate-inspector-information
libraries: (chezscheme)

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-compressed
libraries: (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-message
libraries: (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:

compiling input-path with output to output-path

When the parameter is set to #f, the message is not printed.

thread parameter: run-cp0
thread parameter: cp0-effort-limit
thread parameter: cp0-score-limit
thread parameter: cp0-outer-unroll-limit
libraries: (chezscheme)

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:

(define-syntax case
  (syntax-rules ()
    [(_ e [(k ...) a1 a2 ...] ... [else b1 b2 ...])
     (let ([t e])
       (cond
         [(memv t '(k ...)) a1 a2 ...]
         ...
         [else b1 b2 ...]))]
    [(_ e [(k ...) a1 a2 ...] ...)
     (let ([t e])
       (cond
         [(memv t '(k ...)) a1 a2 ...]
         ...))]))

and count on the introduce let expression to be eliminated if e turns out to be an unassigned variable, and count on the entire case expression to be folded if e turns out to be a constant.

It is possible to see what cp0 does with an expression via the procedure expand/optimize, which expands its argument and passes the result through cp0, as illustrated by the following transcript.

> (print-gensym #f)
> (expand/optimize
    '(lambda (x)
       (case x [(a) 1] [(b c) 2] [(d) 3] [else 4])))
(lambda (x)
  (if (#2%memv x '(a))
      1
      (if (#2%memv x '(b c)) 2 (if (#2%memv x '(d)) 3 4))))
> (expand/optimize
    '(+ (let ([f (lambda (x)
                (case x [(a) 1] [(b c) 2] [(d) 3] [else 4]))])
          (f 'b))
         15))
17

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

(letrec ([fact (lambda (x) (if (zero? x) 1 (* x (fact (- x 1)))))])
  (fact 10))

would be left unchanged with the outer unroll limit set to zero, but would be converted into

(letrec ([fact (lambda (x) (if (zero? x) 1 (* x (fact (- x 1)))))])
  (* 10 (fact 9)))

with the outer unroll limit set to one.

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,

(letrec ([fact (lambda (x) (if (zero? x) 1 (* x (fact (- x 1)))))])
  (fact 10))

would be reduced to 3628800, but

(letrec ([fact (lambda (x) (if (zero? x) 1 (* x (fact (- x 1)))))])
  (fact z))

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:

  1. compiling code with profile instrumentation enabled,
  2. running the code to generate profiling information,
  3. dumping the profile data in raw or HTML format, and
  4. 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.

(define fat+
  (lambda (x y)
    (if (zero? y)
        x
        (fat+ (1+ x) (1- y)))))

(define fatfib
  (lambda (x)
    (if (< x 2)
        1
        (fat+ (fatfib (1- x)) (fatfib (1- (1- x)))))))

We can load fatfib.ss with profiling enabled as follows.

(parameterize ([compile-profile #t])
  (load "/tmp/fatfib/fatfib.ss"))

We then run the application as usual.

(fatfib 20) <graphic> 10946

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.

profile.html listing

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:

fatfib.html listing

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.

(fatfib 20)
(with-output-to-file "/tmp/fatfib/pdump"
  (lambda () (fasl-write (profile-dump)))
  'replace)

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.

profile of fatfib

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-profile
libraries: (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:

(parameterize ([compile-profile #t]
               [run-cp0 (lambda (cp0 x) x)])
  (compile-file "program.ss"))

can be used to compile program.ss with profiling enabled and cp0 disabled.

procedure: (profile-clear)
returns: unspecified
libraries: (chezscheme)

Calling this procedure causes profile information to be cleared, i.e., the counts associated with each section of code are set to zero.

procedure: (profile-dump-html)
procedure: (profile-dump-html prefix)
returns: unspecified
libraries: (chezscheme)

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.

(profile-palette) <graphic>
  #(("black" . "white") ("#666666" . "white")
    ("#A000C8" . "black") ("#8200DC" . "white")
    ("#1E3CFF" . "white") ("#00A0FF" . "black")
    ("#00D28C" . "black") ("#00DC00" . "black")
    ("#A0E632" . "black") ("#E6DC32" . "black")
    ("#E6AF2D" . "black") ("#F08228" . "black")
    ("#FA3C3C" . "white"))
(profile-palette
 ; set palette with rainbow colors and black text
 ; for all but unprofiled or unexecuted code
  '#(("black" . "white")      ; black
     ("#666666" . "white")    ; gray
     ("#8B00FF" . "black")    ; violet
     ("#6600FF" . "black")    ; indigo
     ("#0000FF" . "black")    ; blue
     ("#00FF00" . "black")    ; green
     ("#FFFF00" . "black")    ; yellow
     ("#FF7F00" . "black")    ; orange
     ("#FF0000" . "black")))  ; red

thread parameter: (profile-line-number-color)
libraries: (chezscheme)

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.

procedure: (profile-dump-list)
procedure: (profile-dump-list warn?)
returns: a list of profile entries (see below)
libraries: (chezscheme)

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.

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.

procedure: (profile-dump)
returns: raw profile information
libraries: (chezscheme)

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

procedure: (new-cafe)
procedure: (new-cafe eval-proc)
returns: see below
libraries: (chezscheme)

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.

> (new-cafe (lambda (x) x))
>> 3
3
>> (a . (b . (c . ())))
(a b c)

(define sum
  (lambda (ls)
    (if (null? ls)
        0
        (+ (car ls) (sum (cdr ls))))))
> (new-cafe sum)
>> (1 2 3)
6

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-string
libraries: (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-string)
">"
> (waiter-prompt-string "%")
% (waiter-prompt-string)
"%"
% (new-cafe)
%% (waiter-prompt-string)
"%"

thread parameter: waiter-prompt-and-read
libraries: (chezscheme)

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.

(define default-prompt-and-read
  (lambda (n)
    (unless (and (integer? n) (>= n 0))
       (assertion-violationf 'default-prompt-and-read
         "~s is not a nonnegative integer"
         n))
    (let ([prompt (waiter-prompt-string)])
      (unless (string=? prompt "")
        (do ([n n (- n 1)])
            ((= n 0)
             (write-char #\space (console-output-port))
             (flush-output-port (console-output-port)))
            (display prompt (console-output-port))))
      (let ([x (read (console-input-port))])
         (when (and (eof-object? x) (not (string=? prompt "")))
            (newline (console-output-port))
            (flush-output-port (console-output-port)))
         x))))

thread parameter: waiter-write
libraries: (chezscheme)

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:

(waiter-write
  (lambda (x)
    (unless (eq? x (void))
      (pretty-print x (console-output-port)))
    (flush-output-port (console-output-port))))

procedure: (reset)
returns: does not return
libraries: (chezscheme)

reset invokes the current reset handler (see reset-handler) without arguments.

thread parameter: reset-handler
libraries: (chezscheme)

The value of this parameter must be a procedure and should accept zero arguments. The current reset handler is called by reset. The default reset handler resets to the current café.

procedure: (exit obj ...)
returns: does not return
libraries: (chezscheme)

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

thread parameter: exit-handler
libraries: (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.

procedure: (abort)
procedure: (abort obj)
returns: does not return
libraries: (chezscheme)

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

thread parameter: abort-handler
libraries: (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-start
libraries: (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-script
libraries: (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.

(lambda (fn . fns)
  (command-line (cons fn fns))
  (command-line-arguments fns)
  (load fn))

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-program
libraries: (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.

(lambda (fn . fns)
  (command-line (cons fn fns))
  (command-line-arguments fns)
  (load-program fn))

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-line
libraries: (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-arguments
libraries: (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-greeting
libraries: (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.

procedure: (transcript-on path)
returns: unspecified
libraries: (chezscheme)

path must be a string.

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.

procedure: (transcript-off)
returns: unspecified
libraries: (chezscheme)

transcript-off ends transcription and closes the transcript file.

procedure: (transcript-cafe path)
libraries: (chezscheme)

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.

(current-time) <graphic> #<time-utc 1198815722.473668000>
(current-time 'time-process) <graphic> #<time-process 0.120534264>

procedure: (make-time type nsec sec)
returns: a time object
libraries: (chezscheme)

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.

(make-time 'time-utc 787511000 1198783214)
(make-time 'time-duration 10 5)
(make-time 'time-duration 10 -5)

procedure: (time? obj)
returns: #t if obj is a time object, #f otherwise
libraries: (chezscheme)

(time? (current-time)) <graphic> #t
(time? (make-time 'time-utc 0 0)) <graphic> #t
(time? "1400 hours") <graphic> #f

procedure: (time-type time)
returns: the time type of time
procedure: (time-nanosecond time)
returns: the nanosecond of time
procedure: (time-second time)
returns: the second of time
libraries: (chezscheme)

time must be a time object.

(time-type (current-time)) <graphic> time-utc
(time-type (current-time 'time-process)) <graphic> time-process
(time-type (make-time 'time-duration 0 50) <graphic> time-duration
(time-second (current-time)) <graphic> 1198816497
(time-nanosecond (current-time)) <graphic> 2399000
(time-second (make-time 'time-duration 10 -5)) <graphic> -5
(time-nanosecond (make-time 'time-duration 10 -5)) <graphic> 10

procedure: (set-time-type! time type)
returns: unspecified
procedure: (set-time-nanosecond! time nsec)
returns: unspecified
procedure: (set-time-second! time sec)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (time=? time1 time2)
procedure: (time<? time1 time2)
procedure: (time<=? time1 time2)
procedure: (time>=? time1 time2)
procedure: (time>? time1 time2)
returns: #t if the relation holds, #f otherwise
libraries: (chezscheme)

time1 and time2 must be time objects and must have the same type.

(let ([t (current-time)])
  (time=? t t)) <graphic> #t
(let ([t (current-time)])
  (let loop ()
    (when (time=? (current-time) t))
      (loop))
  (time>? (current-time) t)) <graphic> #t

procedure: (current-date)
procedure: (current-date offset)
returns: a date object representing the current date
libraries: (chezscheme)

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.

The following examples assume the local time zone is EST.

(current-date) <graphic> #<date Thu Dec 27 23:23:20 2007>
(current-date 0) <graphic> #<date Fri Dec 28 04:23:20 2007>

procedure: (make-date nsec sec min hour day mon year offset)
returns: a date object
libraries: (chezscheme)

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.

(make-date 0 0 0 0 1 1 1970 0) <graphic> #<date Thu Jan  1 00:00:00 1970>
(make-date 0 30 7 9 23 9 2007 -14400) <graphic> #<date Sun Sep 23 09:07:30 2007>

procedure: (date? obj)
returns: #t if obj is a date object, #f otherwise
libraries: (chezscheme)

(date? (current-date))
(date? (make-date 0 30 7 9 23 9 2007 -14400))
(date? "Sun Sep 23 09:07:30 2007") <graphic> #f

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

date must be a date object.

(define d (make-date 0 30 7 9 23 9 2007 -14400))
(date-nanosecond d) <graphic> 0
(date-second d) <graphic> 30
(date-minute d) <graphic> 7
(date-hour d) <graphic> 9
(date-day d) <graphic> 23
(date-month d) <graphic> 9
(date-year d) <graphic> 2007
(date-zone-offset d) <graphic> -14400

procedure: (date-week-day date)
returns: the week-day of date
procedure: (date-year-day date)
returns: the year-day of date
libraries: (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.

(define d1 (make-date 0 0 0 0 1 1 1970 -18000))
d1 <graphic> #<date Thu Jan  1 00:00:00 1970>
(date-week-day d1) <graphic> 4
(date-year-day d1) <graphic> 0

(define d2 (make-date 0 30 7 9 23 9 2007 -14400))
d2 <graphic> #<date Sun Sep 23 09:07:30 2007>
(date-week-day d2) <graphic> 0
(date-year-day d2) <graphic> 265

procedure: (time-utc->date time)
procedure: (time-utc->date time offset)
returns: a date object corresponding to time
procedure: (date->time-utc date)
returns: a time object corresponding to date
libraries: (chezscheme)

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.

(define d (make-date 0 30 7 9 23 9 2007 -14400))
(date->time-utc d) <graphic> #<time-utc 1190552850.000000000>
(define t (make-time 'time-utc 0 1190552850))
(time-utc->date t) <graphic> #<date Sun Sep 23 09:07:30 2007>
(time-utc->date t 0) <graphic> #<date Sun Sep 23 13:07:30 2007> 

procedure: (date-and-time)
procedure: (date-and-time date)
returns: a string giving the current date and time
libraries: (chezscheme)

The string is always in the format illustrated by the examples below and always has length 24.

(date-and-time) <graphic> "Fri Jul 13 13:13:13 2001"
(define d (make-date 0 0 0 0 1 1 2007 0))
(date-and-time d) <graphic> "Mon Jan 01 00:00:00 2007"

procedure: (sleep time)
returns: unspecified
libraries: (chezscheme)

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 expr
libraries: (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.

> (time (collect))
(time (collect))
    1 collection
    1 ms elapsed cpu time, including 1 ms collecting
    1 ms elapsed real time, including 1 ms collecting
    160 bytes allocated, including 8184 bytes reclaimed

procedure: (display-statistics)
procedure: (display-statistics textual-output-port)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (statistics)
returns: a sstats structure containing current statistics
libraries: (chezscheme)

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.

(define-structure
  (sstats cpu real bytes
    gc-count gc-cpu gc-real gc-bytes))

procedure: (make-sstats cpu real bytes gc-count gc-cpu gc-real gc-bytes)
returns: a sstats structure
libraries: (chezscheme)

Each of the arguments must be a real number.

procedure: (sstats? obj)
returns: #t if obj is a sstats structure, otherwise #f
libraries: (chezscheme)

procedure: (sstats-cpu s)
procedure: (sstats-real s)
procedure: (sstats-bytes s)
procedure: (sstats-gc-count s)
procedure: (sstats-gc-cpu s)
procedure: (sstats-gc-real s)
procedure: (sstats-gc-bytes s)
returns: the value of the corresponding field of s
libraries: (chezscheme)

s must be a sstats structure.

procedure: (set-sstats-cpu! s obj)
procedure: (set-sstats-real! s obj)
procedure: (set-sstats-bytes! s obj)
procedure: (set-sstats-gc-count! s obj)
procedure: (set-sstats-gc-cpu! s obj)
procedure: (set-sstats-gc-real! s obj)
procedure: (set-sstats-gc-bytes! s obj)
returns: unspecified
libraries: (chezscheme)

s must be a sstats structure. Each procedure sets the value of the corresponding field to obj.

procedure: (sstats-difference s1 s2)
returns: a sstats structure representing the difference between s1 and s2
libraries: (chezscheme)

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.

procedure: (sstats-print s)
procedure: (sstats-print s textual-output-port)
returns: unspecified
libraries: (chezscheme)

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.

procedure: (make-parameter object)
procedure: (make-parameter object procedure)
returns: a parameter (procedure)
libraries: (chezscheme)

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.

For example, the default value of print-length is defined as follows:

(define print-length
  (make-parameter
    #f
    (lambda (x)
      (unless (or (not x) (and (fixnum? x) (fx>= x 0)))
        (assertion-violationf 'print-length
          "~s is not a positive fixnum or #f"
          x))
      x)))

(print-length)  <graphic> #f
(print-length 3)
(print-length)  <graphic> 3
(format "~s" '(1 2 3 4 5 6))  <graphic> "(1 2 3 ...)"
(print-length #f)
(format "~s" '(1 2 3 4 5 6))  <graphic> "(1 2 3 4 5 6)"

The definition of make-parameter is straightforward using case-lambda:

(define make-parameter
  (case-lambda
    [(init guard)
     (let ([v (guard init)])
       (case-lambda
         [() v]
         [(u) (set! v (guard u))]))]
    [(init)
     (make-parameter init (lambda (x) x))]))

In threaded versions of Chez Scheme, make-parameter creates global parameters. The procedure make-thread-parameter, described in Section 15.5, may be used to make thread parameters.

syntax: (parameterize ((param expr) ...) body1 body2 ...)
returns: the values of the body body1 body2 ...
libraries: (chezscheme)

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.

(define test
  (make-parameter 0))
(test)  <graphic> 0
(test 1)
(test)  <graphic> 1
(parameterize ([test 2])
  (test))  <graphic> 2
(test)  <graphic> 1
(parameterize ([test 2])
  (test 3)
  (test))  <graphic> 3
(test)  <graphic> 1
(define k (lambda (x) x))
(begin (set! k (call/cc k))
       'k)  <graphic> k
(parameterize ([test 2])
  (test (call/cc k))
  (test))  <graphic> k
(test)  <graphic> 1
(k 3)  <graphic> 3
(test)  <graphic> 1

The definition of parameterize is similar to the definition of fluid-let (page 109):

(define-syntax parameterize
  (lambda (x)
    (syntax-case x ()
      [(_ () b1 b2 ...) #'(begin b1 b2 ...)]
      [(_ ((x e) ...) b1 b2 ...)
       (with-syntax ([(p ...) (generate-temporaries #'(x ...))]
                     [(y ...) (generate-temporaries #'(x ...))])
         #'(let ([p x] ... [y e] ...)
             (let ([swap (lambda ()
                           (let ([t (p)]) (p y) (set! y t))
                           ...)])
               (dynamic-wind swap (lambda () b1 b2 ...) swap))))])))

Section 12.13. Environmental Queries and Settings

procedure: (scheme-version)
returns: a version string
libraries: (chezscheme)

The version string is in the form

"Chez Scheme Version version"

for Chez Scheme, and

"Petite Chez Scheme Version version"

for Petite Chez Scheme.

procedure: (scheme-version-number)
returns: three values: the major, minor, and sub-minor version numbers
libraries: (chezscheme)

Each of the three return values is a nonnegative fixnum.

In Chez Scheme Version 7.9.4:

(scheme-version-number) <graphic> 7
                         9
                         4

procedure: (petite?)
returns: #t if called in Petite Chez Scheme, #f otherwise
libraries: (chezscheme)

The only difference between Petite Chez Scheme and Chez Scheme is that the compiler is not available in the former, so this predicate can serve as a way to determine if the compiler is available.

procedure: (threaded?)
returns: #t if called in a threaded version of the system, #f otherwise
libraries: (chezscheme)

procedure: (interactive?)
returns: #t if system is run interactively, #f otherwise
libraries: (chezscheme)

This predicate returns #t if the Scheme process's stdin and stdout are connected to a tty (Unix-based systems) or console (Windows). Otherwise, it returns #f.

procedure: (get-process-id)
returns: the operating system process id if the current process
libraries: (chezscheme)

procedure: (getenv key)
returns: environment value of key or #f
libraries: (chezscheme)

key must be a string. getenv returns the operating system shell's environment value associated with key, or #f if no environment value is associated with key.

(getenv "HOME") <graphic> "/u/freddy"

procedure: (putenv key value)
returns: unspecified
libraries: (chezscheme)

key and value must be strings.

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.

(putenv "SCHEME" "rocks!")
(getenv "SCHEME") <graphic> "rocks!"

procedure: (get-registry key)
returns: registry value of key or #f
procedure: (put-registry! key val)
procedure: (remove-registry! key)
returns: unspecified
libraries: (chezscheme)

key and val must be strings.

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.

These routines are defined for Windows only.

(get-registry "hkey_local_machine\\Software\\North\\South") <graphic> #f
(put-registry! "hkey_local_machine\\Software\\North\\South" "east")
(get-registry "hkey_local_machine\\Software\\North\\South") <graphic> "east"
(remove-registry! "hkey_local_machine\\Software\\North")
(get-registry "hkey_local_machine\\Software\\North\\South") <graphic> #f

Section 12.14. Subset Modes

thread parameter: subset-mode
libraries: (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.

R. Kent Dybvig / Chez Scheme Version 8 User's Guide
Copyright © 2009 R. Kent Dybvig
Revised October 2011 for Chez Scheme Version 8.4
Cadence Research Systems / www.scheme.com
Cover illustration © 2010 Jean-Pierre Hébert
ISBN: 978-0-966-71392-3
about this book / purchase this book in print form