This is gambit-c.info, produced by makeinfo version 4.11 from gambit-c.txi.

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

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

   Copyright (C) 1994-2008 Marc Feeley.

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

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

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


File: gambit-c.info,  Node: Handling of file names,  Next: Filesystem operations,  Prev: Host environment,  Up: Host environment

16.1 Handling of file names
===========================

Gambit uses a naming convention for files that is compatible with the
one used by the host environment but extended to allow referring to the
"home directory" of the current user or some specific user and the
"Gambit installation directory".

   A "path" is a string that denotes a file, for example
`"src/readme.txt"'.  Each component of a path is separated by a `/'
under UNIX and Mac OS X and by a `/' or `\' under MSDOS and Microsoft
Windows.  A leading separator indicates an absolute path under UNIX,
Mac OS X, MSDOS and Microsoft Windows.  A path which does not contain a
path separator is relative to the "current working directory" on all
operating systems.  A volume specifier such as `C:' may prefix a file
name under MSDOS and Microsoft Windows.

   The rest of this section uses `/' to represent the path separator.

   A path which starts with the characters `~~/' denotes a file in the
Gambit installation directory.  This directory is normally
`/usr/local/Gambit-C/version' under UNIX and Mac OS X and
`C:/Gambit-C/version' under MSDOS and Microsoft Windows.  To override
this binding under UNIX, Mac OS X, MSDOS and Microsoft Windows, use the
`-:=<DIR>' runtime option or define the `GAMBCOPT' environment variable.

   A path which starts with the characters `~/' denotes a file in the
user's home directory.  The user's home directory is contained in the
`HOME' environment variable under UNIX, Mac OS X, MSDOS and Microsoft
Windows.  Under MSDOS and Microsoft Windows, if the `HOME' environment
variable is not defined, the environment variables `HOMEDRIVE' and
`HOMEPATH' are concatenated if they are defined.  If this fails to
yield a home directory, the Gambit installation directory is used
instead.

   A path which starts with the characters `~USERNAME/' denotes a file
in the home directory of the given user.  Under UNIX and Mac OS X this
is found using the password file.  There is no equivalent under MSDOS
and Microsoft Windows.

 -- procedure: current-directory [NEW-CURRENT-DIRECTORY]
     The parameter object `current-directory' is bound to the current
     working directory.  Calling this procedure with no argument returns
     the absolute "normalized path" of the directory and calling this
     procedure with one argument sets the directory to
     NEW-CURRENT-DIRECTORY.  The initial binding of this parameter
     object is the current working directory of the current process.
     The path returned by `current-directory' always contains a trailing
     directory separator.  Modifications of the parameter object do not
     change the current working directory of the current process (i.e.
     that is accessible with the UNIX `getcwd()' function and the
     Microsoft Windows `GetCurrentDirectory' function).  It is an error
     to mutate the string returned by `current-directory'.

     For example under UNIX:

          > (current-directory)
          "/Users/feeley/gambit/doc/"
          > (current-directory "..")
          > (current-directory)
          "/Users/feeley/gambit/"
          > (path-expand "foo" "~~")
          "/usr/local/Gambit-C/4.0b22/foo"
          > (parameterize ((current-directory "~~")) (path-expand "foo"))
          "/usr/local/Gambit-C/4.0b22/foo"


 -- procedure: path-expand PATH [ORIGIN-DIRECTORY]
     The procedure `path-expand' takes the path of a file or directory
     and returns an expanded path, which is an absolute path when PATH
     or ORIGIN-DIRECTORY are absolute paths.  The optional
     ORIGIN-DIRECTORY parameter, which defaults to the current working
     directory, is the directory used to resolve relative paths.
     Components of the paths PATH and ORIGIN-DIRECTORY need not exist.

     For example under UNIX:

          > (path-expand "foo")
          "/Users/feeley/gambit/doc/foo"
          > (path-expand "~/foo")
          "/Users/feeley/foo"
          > (path-expand "~~/foo")
          "/usr/local/Gambit-C/4.0b22/foo"
          > (path-expand "../foo")
          "/Users/feeley/gambit/doc/../foo"
          > (path-expand "foo" "")
          "foo"
          > (path-expand "foo" "/tmp")
          "/tmp/foo"
          > (path-expand "this/file/does/not/exist")
          "/Users/feeley/gambit/doc/this/file/does/not/exist"
          > (path-expand "")
          "/Users/feeley/gambit/doc/"


 -- procedure: path-normalize PATH [ALLOW-RELATIVE? [ORIGIN-DIRECTORY]]
     The procedure `path-normalize' takes a path of a file or directory
     and returns its normalized path.  The optional ORIGIN-DIRECTORY
     parameter, which defaults to the current working directory, is the
     directory used to resolve relative paths.  All components of the
     paths PATH and ORIGIN-DIRECTORY must exist, except possibly the
     last component of PATH.  A normalized path is a path containing no
     redundant parts and which is consistent with the current structure
     of the filesystem.  A normalized path of a directory will always
     end with a path separator (i.e. `/', `\', or `:' depending on the
     operating system).  The optional ALLOW-RELATIVE? parameter, which
     defaults to `#f', indicates if the path returned can be expressed
     relatively to ORIGIN-DIRECTORY: a `#f' requests an absolute path,
     the symbol `shortest' requests the shortest of the absolute and
     relative paths, and any other value requests the relative path.
     The shortest path is useful for interaction with the user because
     short relative paths are typically easier to read than long
     absolute paths.

     For example under UNIX:

          > (path-expand "../foo")
          "/Users/feeley/gambit/doc/../foo"
          > (path-normalize "../foo")
          "/Users/feeley/gambit/foo"
          > (path-normalize "this/file/does/not/exist")
          *** ERROR IN (console)@3.1 -- No such file or directory
          (path-normalize "this/file/does/not/exist")


 -- procedure: path-extension PATH
 -- procedure: path-strip-extension PATH
 -- procedure: path-directory PATH
 -- procedure: path-strip-directory PATH
 -- procedure: path-strip-trailing-directory-separator PATH
 -- procedure: path-volume PATH
 -- procedure: path-strip-volume PATH
     These procedures extract various parts of a path, which need not
     be a normalized path.  The procedure `path-extension' returns the
     file extension (including the period) or the empty string if there
     is no extension.  The procedure `path-strip-extension' returns the
     path with the extension stripped off.  The procedure
     `path-directory' returns the file's directory (including the last
     path separator) or the empty string if no directory is specified
     in the path.  The procedure `path-strip-directory' returns the
     path with the directory stripped off.  The procedure
     `path-strip-trailing-directory-separator' returns the path with
     the directory separator stripped off if one is at the end of the
     path.  The procedure `path-volume' returns the file's volume
     (including the last path separator) or the empty string if no
     volume is specified in the path.  The procedure
     `path-strip-volume' returns the path with the volume stripped off.

     For example under UNIX:

          > (path-extension "/tmp/foo")
          ""
          > (path-extension "/tmp/foo.txt")
          ".txt"
          > (path-strip-extension "/tmp/foo.txt")
          "/tmp/foo"
          > (path-directory "/tmp/foo.txt")
          "/tmp/"
          > (path-strip-directory "/tmp/foo.txt")
          "foo.txt"
          > (path-strip-trailing-directory-separator "/usr/local/bin/")
          "/usr/local/bin"
          > (path-strip-trailing-directory-separator "/usr/local/bin")
          "/usr/local/bin"
          > (path-volume "/tmp/foo.txt")
          ""
          > (path-volume "C:/tmp/foo.txt")
          "" ; result is "C:" under Microsoft Windows
          > (path-strip-volume "C:/tmp/foo.txt")
          "C:/tmp/foo.txt" ; result is "/tmp/foo.txt" under Microsoft Windows



File: gambit-c.info,  Node: Filesystem operations,  Next: Shell command execution,  Prev: Handling of file names,  Up: Host environment

16.2 Filesystem operations
==========================

 -- procedure: create-directory PATH-OR-SETTINGS
     This procedure creates a directory.  The argument PATH-OR-SETTINGS
     is either a string denoting a filesystem path or a list of port
     settings which must contain a `path:' setting.  Here are the
     settings allowed:

        * `path:' STRING

          This setting indicates the location of the directory to
          create in the filesystem.  There is no default value for this
          setting.

        * `permissions:' 12-BIT-EXACT-INTEGER

          This setting controls the UNIX permissions that will be
          attached to the file if it is created.  The default value of
          this setting is `#o777'.


     For example:

          > (create-directory "newdir")
          > (create-directory "newdir")
          *** ERROR IN (console)@2.1 -- File exists
          (create-directory "newdir")


 -- procedure: create-fifo PATH-OR-SETTINGS
     This procedure creates a FIFO.  The argument PATH-OR-SETTINGS is
     either a string denoting a filesystem path or a list of port
     settings which must contain a `path:' setting.  Here are the
     settings allowed:

        * `path:' STRING

          This setting indicates the location of the FIFO to create in
          the filesystem.  There is no default value for this setting.

        * `permissions:' 12-BIT-EXACT-INTEGER

          This setting controls the UNIX permissions that will be
          attached to the file if it is created.  The default value of
          this setting is `#o666'.


     For example:

          > (create-fifo "fifo")
          > (define a (open-input-file "fifo"))
          > (define b (open-output-file "fifo"))
          > (display "1 22 333" b)
          > (force-output b)
          > (read a)
          1
          > (read a)
          22


 -- procedure: create-link SOURCE-PATH DESTINATION-PATH
     This procedure creates a hard link between SOURCE-PATH and
     DESTINATION-PATH.  The argument SOURCE-PATH must be a string
     denoting the path of an existing file.  The argument
     DESTINATION-PATH must be a string denoting the path of the link to
     create.


 -- procedure: create-symbolic-link SOURCE-PATH DESTINATION-PATH
     This procedure creates a symbolic link between SOURCE-PATH and
     DESTINATION-PATH.  The argument SOURCE-PATH must be a string
     denoting the path of an existing file.  The argument
     DESTINATION-PATH must be a string denoting the path of the
     symbolic link to create.


 -- procedure: rename-file SOURCE-PATH DESTINATION-PATH
     This procedure renames the file SOURCE-PATH to DESTINATION-PATH.
     The argument SOURCE-PATH must be a string denoting the path of an
     existing file.  The argument DESTINATION-PATH must be a string
     denoting the new path of the file.


 -- procedure: copy-file SOURCE-PATH DESTINATION-PATH
     This procedure copies the file SOURCE-PATH to DESTINATION-PATH.
     The argument SOURCE-PATH must be a string denoting the path of an
     existing file.  The argument DESTINATION-PATH must be a string
     denoting the path of the file to create.


 -- procedure: delete-file PATH
     This procedure deletes the file PATH.  The argument PATH must be a
     string denoting the path of an existing file.


 -- procedure: delete-directory PATH
     This procedure deletes the directory PATH.  The argument PATH must
     be a string denoting the path of an existing directory.


 -- procedure: directory-files [PATH-OR-SETTINGS]
     This procedure returns the list of the files in a directory.  The
     argument PATH-OR-SETTINGS is either a string denoting a filesystem
     path to a directory or a list of settings which must contain a
     `path:' setting.  If it is not specified, PATH-OR-SETTINGS
     defaults to the current directory (the value bound to the
     `current-directory' parameter object).  Here are the settings
     allowed:

        * `path:' STRING

          This setting indicates the location of the directory in the
          filesystem.  There is no default value for this setting.

        * `ignore-hidden:' ( `#f' | `#t' | `dot-and-dot-dot' )

          This setting controls whether hidden-files will be returned.
          Under UNIX and Mac OS X hidden-files are those that start
          with a period (such as `.', `..', and `.profile').  Under
          Microsoft Windows hidden files are the `.' and `..' entries
          and the files whose "hidden file" attribute is set.  A
          setting of `#f' will enumerate all the files.  A setting of
          `#t' will only enumerate the files that are not hidden.  A
          setting of `dot-and-dot-dot' will enumerate all the files
          except for the `.' and `..' hidden files.  The default value
          of this setting is `#t'.


     For example:

          > (directory-files)
          ("complex" "README" "simple")
          > (directory-files "../include")
          ("config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")
          > (directory-files (list path: "../include" ignore-hidden: #f))
          ("." ".." "config.h" "config.h.in" "gambit.h" "makefile" "makefile.in")



File: gambit-c.info,  Node: Shell command execution,  Next: Process termination,  Prev: Filesystem operations,  Up: Host environment

16.3 Shell command execution
============================

 -- procedure: shell-command COMMAND
     The procedure `shell-command' calls up the shell to execute
     COMMAND which must be a string.  This procedure returns the exit
     status of the shell in the form that the C library's `system'
     routine returns.

     For example under UNIX:

          > (shell-command "ls -sk f*.scm")
          4 fact.scm   4 fib.scm
          0



File: gambit-c.info,  Node: Process termination,  Next: Command line arguments,  Prev: Shell command execution,  Up: Host environment

16.4 Process termination
========================

 -- procedure: exit [STATUS]
     The procedure `exit' causes the process to terminate with the
     status STATUS which must be an exact integer in the range 0 to
     255.  If it is not specified, STATUS defaults to 0.

     For example under UNIX:

          $ gsi
          Gambit v4.2.8

          > (exit 42)
          $ echo $?
          42



File: gambit-c.info,  Node: Command line arguments,  Next: Environment variables,  Prev: Process termination,  Up: Host environment

16.5 Command line arguments
===========================

 -- procedure: command-line
     This procedure returns a list of strings corresponding to the
     command line arguments, including the program file name as the
     first element of the list.  When the interpreter executes a Scheme
     script, the list returned by `command-line' contains the script's
     absolute path followed by the remaining command line arguments.

     For example under UNIX:

          $ gsi -:d -e "(pretty-print (command-line))"
          ("gsi" "-e" "(pretty-print (command-line))")
          $ cat foo
          #!/usr/local/Gambit-C/current/bin/gsi-script
          (pretty-print (command-line))
          $ ./foo 1 2 "3 4"
          ("/u/feeley/./foo" "1" "2" "3 4")



File: gambit-c.info,  Node: Environment variables,  Next: Measuring time,  Prev: Command line arguments,  Up: Host environment

16.6 Environment variables
==========================

 -- procedure: getenv NAME [DEFAULT]
 -- procedure: setenv NAME [NEW-VALUE]
     The procedure `getenv' returns the value of the environment
     variable NAME of the current process.  Variable names are denoted
     with strings.  A string is returned if the environment variable is
     bound, otherwise DEFAULT is returned if it is specified, otherwise
     an exception is raised.

     The procedure `setenv' changes the binding of the environment
     variable NAME to NEW-VALUE which must be a string.  If NEW-VALUE
     is not specified the binding is removed.

     For example under UNIX:

          > (getenv "HOME")
          "/Users/feeley"
          > (getenv "DOES_NOT_EXIST" #f)
          #f
          > (setenv "DOES_NOT_EXIST" "it does now")
          > (getenv "DOES_NOT_EXIST" #f)
          "it does now"
          > (setenv "DOES_NOT_EXIST")
          > (getenv "DOES_NOT_EXIST" #f)
          #f
          > (getenv "DOES_NOT_EXIST")
          *** ERROR IN (console)@7.1 -- Unbound OS environment variable
          (getenv "DOES_NOT_EXIST")



File: gambit-c.info,  Node: Measuring time,  Next: File information,  Prev: Environment variables,  Up: Host environment

16.7 Measuring time
===================

Procedures are available for measuring real time (aka "wall" time) and
cpu time (the amount of time the cpu has been executing the process).
The resolution of the real time and cpu time clock is operating system
dependent.  Typically the resolution of the cpu time clock is rather
coarse (measured in "ticks" of 1/60th or 1/100th of a second).  Real
time is internally computed relative to some arbitrary point in time
using floating point numbers, which means that there is a gradual loss
of resolution as time elapses.  Moreover, some operating systems report
time in number of ticks using a 32 bit integer so the value returned by
the time related procedures may wraparound much before any significant
loss of resolution occurs (for example 2.7 years if ticks are 1/50th of
a second).

 -- procedure: current-time
 -- procedure: time? OBJ
 -- procedure: time->seconds TIME
 -- procedure: seconds->time X
     The procedure `current-time' returns a "time object" representing
     the current point in real time.

     The procedure `time?' returns `#t' when OBJ is a time object and
     `#f' otherwise.

     The procedure `time->seconds' converts the time object TIME into
     an inexact real number representing the number of seconds elapsed
     since the "epoch" (which is 00:00:00 Coordinated Universal Time
     01-01-1970).

     The procedure `seconds->time' converts the real number X
     representing the number of seconds elapsed since the "epoch" into a
     time object.

     For example:

          > (current-time)
          #<time #2>
          > (time? (current-time))
          #t
          > (time? 123)
          #f
          > (time->seconds (current-time))
          1083118758.63973
          > (time->seconds (current-time))
          1083118759.909163
          > (seconds->time (+ 10 (time->seconds (current-time))
          #<time #3>  ; a time object representing 10 seconds in the future


 -- procedure: process-times
 -- procedure: cpu-time
 -- procedure: real-time
     The procedure `process-times' returns a three element f64vector
     containing the cpu time that has been used by the program and the
     real time that has elapsed since it was started.  The first element
     corresponds to "user" time in seconds, the second element
     corresponds to "system" time in seconds and the third element is
     the elapsed real time in seconds.  On operating systems that can't
     differentiate user and system time, the system time is zero.  On
     operating systems that can't measure cpu time, the user time is
     equal to the elapsed real time and the system time is zero.

     The procedure `cpu-time' returns the cpu time in seconds that has
     been used by the program (user time plus system time).

     The procedure `real-time' returns the real time that has elapsed
     since the program was started.

     For example:

          > (process-times)
          #f64(.02794 .021754 .159926176071167)
          > (cpu-time)
          .051223
          > (real-time)
          .40660619735717773


 -- special form: time expr
     The `time' special form evaluates expr and returns the result.  As
     a side effect it displays a message on the interaction channel
     which indicates how long the evaluation took (in real time and cpu
     time), how much time was spent in the garbage collector, how much
     memory was allocated during the evaluation and how many minor and
     major page faults occured (0 is reported if not running under
     UNIX).

     For example:

          > (define (f x)
              (let loop ((x x) (lst '()))
                (if (= x 0)
                    lst
                    (loop (- x 1) (cons x lst)))))
          > (length (time (f 100000)))
          (time (f 100000))
              683 ms real time
              558 ms cpu time (535 user, 23 system)
              8 collections accounting for 102 ms real time (70 user, 5 system)
              6400160 bytes allocated
              no minor faults
              no major faults
          100000



File: gambit-c.info,  Node: File information,  Next: Group information,  Prev: Measuring time,  Up: Host environment

16.8 File information
=====================

 -- procedure: file-exists? PATH [CHASE?]
     The PATH argument must be a string.  This procedure returns `#t'
     when a file by that name exists, and returns `#f' otherwise.

     When CHASE? is present and `#f', symbolic links will not be
     chased, in other words if PATH refers to a symbolic link,
     `file-exists?' will return `#t' whether or not it points to an
     existing file.

     For example:

          > (file-exists? "nofile")
          #f


 -- procedure: file-info PATH [CHASE?]
     This procedure accesses the filesystem to get information about the
     file whose location is given by the string PATH.  A
     file-information record is returned that contains the file's type,
     the device number, the inode number, the mode (permission bits),
     the number of links, the file's user id, the file's group id, the
     file's size in bytes, the times of last-access, last-modification
     and last-change, the attributes, and the creation time.

     When CHASE? is present and `#f', symbolic links will not be
     chased, in other words if PATH refers to a symbolic link the
     `file-info' procedure will return information about the link
     rather than the file it links to.

     For example:

          > (file-info "/dev/tty")
          #<file-info #2
             type: character-special
             device: 19513156
             inode: 20728196
             mode: 438
             number-of-links: 1
             owner: 0
             group: 0
             size: 0
             last-access-time: #<time #3>
             last-modification-time: #<time #4>
             last-change-time: #<time #5>
             attributes: 128
             creation-time: #<time #6>>


 -- procedure: file-info? OBJ
     This procedure returns `#t' when OBJ is a file-information record
     and `#f' otherwise.

     For example:

          > (file-info? (file-info "/dev/tty"))
          #t
          > (file-info? 123)
          #f


 -- procedure: file-info-type FILE-INFO
     Returns the type field of the file-information record FILE-INFO.
     The type is denoted by a symbol.  The following types are possible:

    `regular'
          Regular file

    `directory'
          Directory

    `character-special'
          Character special device

    `block-special'
          Block special device

    `fifo'
          FIFO

    `symbolic-link'
          Symbolic link

    `socket'
          Socket

    `unknown'
          File is of an unknown type

     For example:

          > (file-info-type (file-info "/dev/tty"))
          character-special
          > (file-info-type (file-info "/dev"))
          directory


 -- procedure: file-info-device FILE-INFO
     Returns the device field of the file-information record FILE-INFO.

     For example:

          > (file-info-device (file-info "/dev/tty"))
          19513156


 -- procedure: file-info-inode FILE-INFO
     Returns the inode field of the file-information record FILE-INFO.

     For example:

          > (file-info-inode (file-info "/dev/tty"))
          20728196


 -- procedure: file-info-mode FILE-INFO
     Returns the mode field of the file-information record FILE-INFO.

     For example:

          > (file-info-mode (file-info "/dev/tty"))
          438


 -- procedure: file-info-number-of-links FILE-INFO
     Returns the number-of-links field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-number-of-links (file-info "/dev/tty"))
          1


 -- procedure: file-info-owner FILE-INFO
     Returns the owner field of the file-information record FILE-INFO.

     For example:

          > (file-info-owner (file-info "/dev/tty"))
          0


 -- procedure: file-info-group FILE-INFO
     Returns the group field of the file-information record FILE-INFO.

     For example:

          > (file-info-group (file-info "/dev/tty"))
          0


 -- procedure: file-info-size FILE-INFO
     Returns the size field of the file-information record FILE-INFO.

     For example:

          > (file-info-size (file-info "/dev/tty"))
          0


 -- procedure: file-info-last-access-time FILE-INFO
     Returns the last-access-time field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-last-access-time (file-info "/dev/tty"))
          #<time #2>


 -- procedure: file-info-last-modification-time FILE-INFO
     Returns the last-modification-time field of the file-information
     record FILE-INFO.

     For example:

          > (file-info-last-modification-time (file-info "/dev/tty"))
          #<time #2>


 -- procedure: file-info-last-change-time FILE-INFO
     Returns the last-change-time field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-last-change-time (file-info "/dev/tty"))
          #<time #2>


 -- procedure: file-info-attributes FILE-INFO
     Returns the attributes field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-attributes (file-info "/dev/tty"))
          128


 -- procedure: file-info-creation-time FILE-INFO
     Returns the creation-time field of the file-information record
     FILE-INFO.

     For example:

          > (file-info-creation-time (file-info "/dev/tty"))
          #<time #2>


 -- procedure: file-type PATH
 -- procedure: file-device PATH
 -- procedure: file-inode PATH
 -- procedure: file-mode PATH
 -- procedure: file-number-of-links PATH
 -- procedure: file-owner PATH
 -- procedure: file-group PATH
 -- procedure: file-size PATH
 -- procedure: file-last-access-time PATH
 -- procedure: file-last-modification-time PATH
 -- procedure: file-last-change-time PATH
 -- procedure: file-attributes PATH
 -- procedure: file-creation-time PATH
     These procedures combine a call to the `file-info' procedure and a
     call to a file-information record field accessor.  For instance
     `(file-type PATH)' is equivalent to `(file-info-type (file-info
     PATH))'.



File: gambit-c.info,  Node: Group information,  Next: User information,  Prev: File information,  Up: Host environment

16.9 Group information
======================

 -- procedure: group-info GROUP-NAME-OR-ID
     This procedure accesses the group database to get information
     about the group identified by GROUP-NAME-OR-ID, which is the
     group's symbolic name (string) or the group's GID (exact integer).
     A group-information record is returned that contains the group's
     symbolic name, the group's id (GID), and the group's members (list
     of symbolic user names).

     For example:

          > (group-info "staff")
          #<group-info #2 name: "staff" gid: 20 members: ("root")>
          > (group-info 29)
          #<group-info #3
             name: "certusers"
             gid: 29
             members: ("root" "jabber" "postfix" "cyrusimap")>
          > (group-info 5000)
          *** ERROR IN (console)@3.1 -- Resource temporarily unavailable
          (group-info 5000)


 -- procedure: group-info? OBJ
     This procedure returns `#t' when OBJ is a group-information record
     and `#f' otherwise.

     For example:

          > (group-info? (group-info "daemon"))
          #t
          > (group-info? 123)
          #f


 -- procedure: group-info-name GROUP-INFO
     Returns the symbolic name field of the group-information record
     GROUP-INFO.

     For example:

          > (group-info-name (group-info 29))
          "certusers"


 -- procedure: group-info-gid GROUP-INFO
     Returns the group id field of the group-information record
     GROUP-INFO.

     For example:

          > (group-info-gid (group-info "staff"))
          20


 -- procedure: group-info-members GROUP-INFO
     Returns the members field of the group-information record
     GROUP-INFO.

     For example:

          > (group-info-members (group-info "staff"))
          ("root")



File: gambit-c.info,  Node: User information,  Next: Host information,  Prev: Group information,  Up: Host environment

16.10 User information
======================

 -- procedure: user-name
     This procedure returns the user's name as a string.

     For example:

          > (user-name)
          "feeley"


 -- procedure: user-info USER-NAME-OR-ID
     This procedure accesses the user database to get information about
     the user identified by USER-NAME-OR-ID, which is the user's
     symbolic name (string) or the user's UID (exact integer).  A
     user-information record is returned that contains the user's
     symbolic name, the user's id (UID), the user's group id (GID), the
     path to the user's home directory, and the user's login shell.

     For example:

          > (user-info "feeley")
          #<user-info #2
             name: "feeley"
             uid: 506
             gid: 506
             home: "/Users/feeley"
             shell: "/bin/bash">
          > (user-info 0)
          #<user-info #3 name: "root" uid: 0 gid: 0 home: "/var/root" shell: "/bin/sh">
          > (user-info 5000)
          *** ERROR IN (console)@3.1 -- Resource temporarily unavailable
          (user-info 5000)


 -- procedure: user-info? OBJ
     This procedure returns `#t' when OBJ is a user-information record
     and `#f' otherwise.

     For example:

          > (user-info? (user-info "feeley"))
          #t
          > (user-info? 123)
          #f


 -- procedure: user-info-name USER-INFO
     Returns the symbolic name field of the user-information record
     USER-INFO.

     For example:

          > (user-info-name (user-info 0))
          "root"


 -- procedure: user-info-uid USER-INFO
     Returns the user id field of the user-information record USER-INFO.

     For example:

          > (user-info-uid (user-info "feeley"))
          506


 -- procedure: user-info-gid USER-INFO
     Returns the group id field of the user-information record
     USER-INFO.

     For example:

          > (user-info-gid (user-info "feeley"))
          506


 -- procedure: user-info-home USER-INFO
     Returns the home directory field of the user-information record
     USER-INFO.

     For example:

          > (user-info-home (user-info 0))
          "/var/root"


 -- procedure: user-info-shell USER-INFO
     Returns the shell field of the user-information record USER-INFO.

     For example:

          > (user-info-shell (user-info 0))
          "/bin/sh"



File: gambit-c.info,  Node: Host information,  Next: Service information,  Prev: User information,  Up: Host environment

16.11 Host information
======================

 -- procedure: host-name
     This procedure returns the machine's host name as a string.

     For example:

          > (host-name)
          "mega.iro.umontreal.ca"


 -- procedure: host-info HOST-NAME
     This procedure accesses the internet host database to get
     information about the machine whose name is denoted by the string
     HOST-NAME.  A host-information record is returned that contains
     the official name of the machine, a list of aliases (alternative
     names), and a non-empty list of IP addresses for this machine.  An
     exception is raised when HOST-NAME does not appear in the database.

     For example:

          > (host-info "www.google.com")
          #<host-info #2
             name: "www.l.google.com"
             aliases: ("www.google.com")
             addresses: (#u8(66 249 85 99) #u8(66 249 85 104))>
          > (host-info "unknown.domain")
          *** ERROR IN (console)@2.1 -- Unknown host
          (host-info "unknown.domain")


 -- procedure: host-info? OBJ
     This procedure returns `#t' when OBJ is a host-information record
     and `#f' otherwise.

     For example:

          > (host-info? (host-info "www.google.com"))
          #t
          > (host-info? 123)
          #f


 -- procedure: host-info-name HOST-INFO
     Returns the official name field of the host-information record
     HOST-INFO.

     For example:

          > (host-info-name (host-info "www.google.com"))
          "www.l.google.com"


 -- procedure: host-info-aliases HOST-INFO
     Returns the aliases field of the host-information record
     HOST-INFO.  This field is a possibly empty list of strings.

     For example:

          > (host-info-aliases (host-info "www.google.com"))
          ("www.google.com")


 -- procedure: host-info-addresses HOST-INFO
     Returns the addresses field of the host-information record
     HOST-INFO.  This field is a non-empty list of u8vectors denoting
     IP addresses.

     For example:

          > (host-info-addresses (host-info "www.google.com"))
          (#u8(66 249 85 99) #u8(66 249 85 104))



File: gambit-c.info,  Node: Service information,  Next: Protocol information,  Prev: Host information,  Up: Host environment

16.12 Service information
=========================

 -- procedure: service-info SERVICE-NAME-OR-ID
     This procedure accesses the service database to get information
     about the service identified by SERVICE-NAME-OR-ID, which is the
     service's symbolic name (string) or the service's port number
     (exact integer).  A service-information record is returned that
     contains the service's symbolic name, a list of aliases
     (alternative names), the port number (exact integer), and the
     protocol name (string).  An exception is raised when
     SERVICE-NAME-OR-ID does not appear in the database.

     For example:

          > (service-info "http")
          #<service-info #2
             name: "http"
             aliases: ("www" "www-http")
             port: 80
             protocol: "udp">
          > (service-info 80)
          #<service-info #3
             name: "http"
             aliases: ("www" "www-http")
             port: 80
             protocol: "udp">


 -- procedure: service-info? OBJ
     This procedure returns `#t' when OBJ is a service-information
     record and `#f' otherwise.

     For example:

          > (service-info? (service-info "http"))
          #t
          > (service-info? 123)
          #f


 -- procedure: service-info-name SERVICE-INFO
     Returns the symbolic name field of the service-information record
     SERVICE-INFO.

     For example:

          > (service-info-name (service-info 80))
          "http"


 -- procedure: service-info-aliases SERVICE-INFO
     Returns the aliases field of the service-information record
     SERVICE-INFO.  This field is a possibly empty list of strings.

     For example:

          > (service-info-aliases (service-info "http"))
          ("www" "www-http")


 -- procedure: service-info-number SERVICE-INFO
     Returns the service number field of the service-information record
     SERVICE-INFO.

     For example:

          > (service-info-number (service-info "http"))
          80



File: gambit-c.info,  Node: Protocol information,  Next: Network information,  Prev: Service information,  Up: Host environment

16.13 Protocol information
==========================

 -- procedure: protocol-info PROTOCOL-NAME-OR-ID
     This procedure accesses the protocol database to get information
     about the protocol identified by PROTOCOL-NAME-OR-ID, which is the
     protocol's symbolic name (string) or the protocol's number (exact
     integer).  A protocol-information record is returned that contains
     the protocol's symbolic name, a list of aliases (alternative
     names), and the protocol number (32 bit unsigned exact integer).
     An exception is raised when PROTOCOL-NAME-OR-ID does not appear in
     the database.

     For example:

          > (protocol-info "tcp")
          #<protocol-info #2 name: "tcp" aliases: ("TCP") number: 6>
          > (protocol-info 6)
          #<protocol-info #2 name: "tcp" aliases: ("TCP") number: 6>


 -- procedure: protocol-info? OBJ
     This procedure returns `#t' when OBJ is a protocol-information
     record and `#f' otherwise.

     For example:

          > (protocol-info? (protocol-info "tcp"))
          #t
          > (protocol-info? 123)
          #f


 -- procedure: protocol-info-name PROTOCOL-INFO
     Returns the symbolic name field of the protocol-information record
     PROTOCOL-INFO.

     For example:

          > (protocol-info-name (protocol-info 6))
          "tcp"


 -- procedure: protocol-info-aliases PROTOCOL-INFO
     Returns the aliases field of the protocol-information record
     PROTOCOL-INFO.  This field is a possibly empty list of strings.

     For example:

          > (protocol-info-aliases (protocol-info "tcp"))
          ("TCP")


 -- procedure: protocol-info-number PROTOCOL-INFO
     Returns the protocol number field of the protocol-information
     record PROTOCOL-INFO.

     For example:

          > (protocol-info-number (protocol-info "tcp"))
          6



File: gambit-c.info,  Node: Network information,  Prev: Protocol information,  Up: Host environment

16.14 Network information
=========================

 -- procedure: network-info NETWORK-NAME-OR-ID
     This procedure accesses the network database to get information
     about the network identified by NETWORK-NAME-OR-ID, which is the
     network's symbolic name (string) or the network's number (exact
     integer).  A network-information record is returned that contains
     the network's symbolic name, a list of aliases (alternative
     names), and the network number (32 bit unsigned exact integer).
     An exception is raised when NETWORK-NAME-OR-ID does not appear in
     the database.

     For example:

          > (network-info "loopback")
          #<network-info #2
             name: "loopback"
             aliases: ("loopback-net")
             number: 127>
          > (network-info 127)
          #<network-info #3
             name: "loopback"
             aliases: ("loopback-net")
             number: 127>


 -- procedure: network-info? OBJ
     This procedure returns `#t' when OBJ is a network-information
     record and `#f' otherwise.

     For example:

          > (network-info? (network-info "loopback"))
          #t
          > (network-info? 123)
          #f


 -- procedure: network-info-name NETWORK-INFO
     Returns the symbolic name field of the network-information record
     NETWORK-INFO.

     For example:

          > (network-info-name (network-info 127))
          "loopback"


 -- procedure: network-info-aliases NETWORK-INFO
     Returns the aliases field of the network-information record
     NETWORK-INFO.  This field is a possibly empty list of strings.

     For example:

          > (network-info-aliases (network-info "loopback"))
          ("loopback-net")


 -- procedure: network-info-number NETWORK-INFO
     Returns the network number field of the network-information record
     NETWORK-INFO.

     For example:

          > (network-info-number (network-info "loopback"))
          127



File: gambit-c.info,  Node: I/O and ports,  Next: Lexical syntax and readtables,  Prev: Host environment,  Up: Top

17 I/O and ports
****************

* Menu:

* Unidirectional and bidirectional ports::  Unidirectional and bidirectional ports
* Port classes::                            Port classes
* Port settings::                           Port settings
* Object-ports::                            Object-ports
* Character-ports::                         Character-ports
* Byte-ports::                              Byte-ports
* Device-ports::                            Device-ports
* Directory-ports::                         Directory-ports
* Vector-ports::                            Vector-ports
* String-ports::                            String-ports
* U8vector-ports::                          U8vector-ports
* Parameter objects related to I/O::        Parameter objects related to I/O


File: gambit-c.info,  Node: Unidirectional and bidirectional ports,  Next: Port classes,  Prev: I/O and ports,  Up: I/O and ports

17.1 Unidirectional and bidirectional ports
===========================================

Unidirectional ports allow communication between a producer of
information and a consumer.  An input-port's producer is typically a
resource managed by the operating system (such as a file, a process or
a network connection) and the consumer is the Scheme program.  The
roles are reversed for an output-port.

   Associated with each port are settings that affect I/O operations on
that port (encoding of characters to bytes, end-of-line encoding, type
of buffering, etc).  Port settings are specified when the port is
created.  Some port settings can be changed after a port is created.

   Bidirectional ports, also called input-output-ports, allow
communication in both directions.  They are best viewed as an object
that groups two separate unidirectional ports (one in each direction).
Each direction has its own port settings and can be closed
independently from the other direction.


File: gambit-c.info,  Node: Port classes,  Next: Port settings,  Prev: Unidirectional and bidirectional ports,  Up: I/O and ports

17.2 Port classes
=================

The four classes of ports listed below form an inheritance hierarchy.
Operations possible for a certain class of port are also possible for
the subclasses.  Only device-ports are connected to a device managed by
the operating system.  For instance it is possible to create ports that
behave as a FIFO where the Scheme program is both the producer and
consumer of information (possibly one thread is the producer and
another thread is the consumer).

  1. An "object-port" (or simply a port) provides operations to read
     and write Scheme data (i.e. any Scheme object) to/from the port.
     It also provides operations to force output to occur, to change
     the way threads block on the port, and to close the port.  Note
     that the class of objects for which write/read invariance is
     guaranteed depends on the particular class of port.

  2. A "character-port" provides all the operations of an object-port,
     and also operations to read and write individual characters to/from
     the port.  When a Scheme object is written to a character-port, it
     is converted into the sequence of characters that corresponds to
     its external-representation.  When reading a Scheme object, an
     inverse conversion occurs.  Note that some Scheme objects do not
     have an external textual representation that can be read back.

  3. A "byte-port" provides all the operations of a character-port, and
     also operations to read and write individual bytes to/from the
     port.  When a character is written to a byte-port, some encoding
     of that character into a sequence of bytes will occur (for example,
     `#\newline' will be encoded as the 2 bytes CR-LF when using
     ISO-8859-1 character encoding and `cr-lf' end-of-line encoding, and
     a non-ASCII character will generate more than 1 byte when using
     UTF-8 character encoding).  When reading a character, a similar
     decoding occurs.

  4. A "device-port" provides all the operations of a byte-port, and
     also operations to control the operating system managed device
     (file, network connection, terminal, etc) that is connected to the
     port.



File: gambit-c.info,  Node: Port settings,  Next: Object-ports,  Prev: Port classes,  Up: I/O and ports

17.3 Port settings
==================

Some port settings are only valid for specific port classes whereas
some others are valid for all ports.  Port settings are specified when
a port is created.  The settings that are not specified will default to
some reasonable values.  Keyword objects are used to name the settings
to be set.  As a simple example, a device-port connected to the file
`"foo"' can be created using the call

     (open-input-file "foo")

   This will use default settings for the character encoding, buffering,
etc.  If the UTF-8 character encoding is desired, then the port could
be opened using the call

     (open-input-file (list path: "foo" char-encoding: 'UTF-8))

   Here the argument of the procedure `open-input-file' has been
replaced by a "port settings list" which specifies the value of each
port setting that should not be set to the default value.  Note that
some port settings have no useful default and it is therefore required
to specify a value for them, such as the `path:' in the case of the
file opening procedures.  All port creation procedures (i.e. named
`open-...') take a single argument that can either be a port settings
list or a value of a type that depends on the kind of port being
created (a path string for files, an IP port number for socket servers,
etc).


File: gambit-c.info,  Node: Object-ports,  Next: Character-ports,  Prev: Port settings,  Up: I/O and ports

17.4 Object-ports
=================

* Menu:

* Object-port settings::             Object-port settings
* Object-port operations::           Object-port operations


File: gambit-c.info,  Node: Object-port settings,  Next: Object-port operations,  Prev: Object-ports,  Up: Object-ports

17.4.1 Object-port settings
---------------------------

The following is a list of port settings that are valid for all types
of ports.

   * `direction:' ( `input' | `output' | `input-output' )

     This setting controls the direction of the port.  The symbol
     `input' indicates a unidirectional input-port, the symbol `output'
     indicates a unidirectional output-port, and the symbol
     `input-output' indicates a bidirectional port.  The default value
     of this setting depends on the port creation procedure.

   * `buffering:' ( `#f' | `#t' | `line' )

     This setting controls the buffering of the port.  To set each
     direction separately the keywords `input-buffering:' and
     `output-buffering:' must be used instead of `buffering:'.  The
     value `#f' selects unbuffered I/O, the value `#t' selects fully
     buffered I/O, and the symbol `line' selects line buffered I/O (the
     output buffer is drained when a `#\newline' character is written).
     Line buffered I/O only applies to character-ports.  The default
     value of this setting is operating system dependent except
     consoles which are unbuffered.



File: gambit-c.info,  Node: Object-port operations,  Prev: Object-port settings,  Up: Object-ports

17.4.2 Object-port operations
-----------------------------

 -- procedure: input-port? OBJ
 -- procedure: output-port? OBJ
 -- procedure: port? OBJ
     The procedure `input-port?' returns `#t' when OBJ is a
     unidirectional input-port or a bidirectional port and `#f'
     otherwise.

     The procedure `output-port?' returns `#t' when OBJ is a
     unidirectional output-port or a bidirectional port and `#f'
     otherwise.

     The procedure `port?' returns `#t' when OBJ is a port (either
     unidirectional or bidirectional) and `#f' otherwise.

     For example:

          > (input-port? (current-input-port))
          #t
          > (call-with-input-string "some text" output-port?)
          #f
          > (port? (current-output-port))
          #t


 -- procedure: read [PORT]
     This procedure reads and returns the next Scheme datum from the
     input-port PORT.  The end-of-file object is returned when the end
     of the stream is reached.  If it is not specified, PORT defaults
     to the current input-port.

     For example:

          > (call-with-input-string "some text" read)
          some
          > (call-with-input-string "" read)
          #!eof


 -- procedure: read-all [PORT [READER]]
     This procedure repeatedly calls the procedure READER with PORT as
     the sole argument and accumulates a list of each value returned up
     to the end-of-file object.  The procedure `read-all' returns the
     accumulated list without the end-of-file object.  If it is not
     specified, PORT defaults to the current input-port.  If it is not
     specified, READER defaults to the procedure `read'.

     For example:

          > (call-with-input-string "3,2,1\ngo!" read-all)
          (3 ,2 ,1 go!)
          > (call-with-input-string "3,2,1\ngo!"
                                    (lambda (p) (read-all p read-char)))
          (#\3 #\, #\2 #\, #\1 #\newline #\g #\o #\!)
          > (call-with-input-string "3,2,1\ngo!"
                                    (lambda (p) (read-all p read-line)))
          ("3,2,1" "go!")


 -- procedure: write OBJ [PORT]
     This procedure writes the Scheme datum OBJ to the output-port PORT
     and the value returned is unspecified.  If it is not specified,
     PORT defaults to the current output-port.

     For example:

          > (write (list 'compare (list 'quote '@x) 'and (list 'unquote '@x)))
          (compare '@x and , @x)>


 -- procedure: newline [PORT]
     This procedure writes an "object separator" to the output-port
     PORT and the value returned is unspecified.  The separator ensures
     that the next Scheme datum written with the `write' procedure will
     not be confused with the latest datum that was written.  On
     character-ports this is done by writing the character `#\newline'.
     On ports where successive objects are implicitly distinct (such as
     "vector ports") this procedure does nothing.

     Regardless of the class of a port P and assuming that the external
     textual representation of the object X is readable, the expression
     `(begin (write X P) (newline P))' will write to P a representation
     of X that can be read back with the procedure `read'.  If it is
     not specified, PORT defaults to the current output-port.

     For example:

          > (begin (write 123) (newline) (write 456) (newline))
          123
          456


 -- procedure: force-output [PORT]
     The procedure `force-output' causes the output buffers of the
     output-port PORT to be drained (i.e. the data is sent to its
     destination).  If PORT is not specified, the current output-port
     is used.

     For example:

          > (define p (open-tcp-client
                        (list server-address: "www.iro.umontreal.ca"
                              port-number: 80)))
          > (display "GET /\n" p)
          > (force-output p)
          > (read-line p)
          "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""


 -- procedure: close-input-port PORT
 -- procedure: close-output-port PORT
 -- procedure: close-port PORT
     The PORT argument of these procedures must be a unidirectional or
     a bidirectional port.  For all three procedures the value returned
     is unspecified.

     The procedure `close-input-port' closes the input-port side of
     PORT, which must not be a unidirectional output-port.

     The procedure `close-output-port' closes the output-port side of
     PORT, which must not be a unidirectional input-port.  The ouput
     buffers are drained before PORT is closed.

     The procedure `close-port' closes all sides of the PORT.  Unless
     PORT is a unidirectional input-port, the output buffers are
     drained before PORT is closed.

     For example:

          > (define p (open-tcp-client
                        (list server-address: "www.iro.umontreal.ca"
                              port-number: 80)))
          > (display "GET /\n" p)
          > (close-output-port p)
          > (read-line p)
          "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""


 -- procedure: input-port-timeout-set! PORT TIMEOUT [THUNK]
 -- procedure: output-port-timeout-set! PORT TIMEOUT [THUNK]
     When a thread tries to perform an I/O operation on a port, the
     requested operation may not be immediately possible and the thread
     must wait.  For example, the thread may be trying to read a line of
     text from the console and the user has not typed anything yet, or
     the thread may be trying to write to a network connection faster
     than the network can handle.  In such situations the thread
     normally blocks until the operation becomes possible.

     It is sometimes necessary to guarantee that the thread will not
     block too long.  For this purpose, to each input-port and
     output-port is attached a "timeout" and "timeout-thunk".  The
     timeout indicates the point in time beyond which the thread should
     stop waiting on an input and output operation respectively.  When
     the timeout is reached, the thread calls the port's timeout-thunk.
     If the timeout-thunk returns `#f' the thread abandons trying to
     perform the operation (in the case of an input operation an
     end-of-file is read and in the case of an output operation an
     exception is raised).  Otherwise, the thread will block again
     waiting for the operation to become possible (note that if the
     port's timeout has not changed the thread will immediately call
     the timeout-thunk again).

     The procedure `input-port-timeout-set!' sets the timeout of the
     input-port PORT to TIMEOUT and the timeout-thunk to THUNK.  The
     procedure `output-port-timeout-set!' sets the timeout of the
     output-port PORT to TIMEOUT and the timeout-thunk to THUNK.  If it
     is not specified, the THUNK defaults to a thunk that returns `#f'.
     The TIMEOUT is either a time object indicating an absolute point
     in time, or it is a real number which indicates the number of
     seconds relative to the moment the procedure is called.  For both
     procedures the value returned is unspecified.

     When a port is created the timeout is set to infinity (`+inf.0').
     This causes the thread to wait as long as needed for the operation
     to become possible.  Setting the timeout to a point in the past
     (`-inf.0') will cause the thread to attempt the I/O operation and
     never block (i.e. the timeout-thunk is called if the operation is
     not immediately possible).

     The following example shows how to cause the REPL to terminate
     when the user does not enter an expression within the next 60
     seconds.

          > (input-port-timeout-set! (repl-input-port) 60)
          >
          *** EOF again to exit



File: gambit-c.info,  Node: Character-ports,  Next: Byte-ports,  Prev: Object-ports,  Up: I/O and ports

17.5 Character-ports
====================

* Menu:

* Character-port settings::          Character-port settings
* Character-port operations::        Character-port operations


File: gambit-c.info,  Node: Character-port settings,  Next: Character-port operations,  Prev: Character-ports,  Up: Character-ports

17.5.1 Character-port settings
------------------------------

The following is a list of port settings that are valid for
character-ports.

   * `readtable:' READTABLE

     This setting determines the readtable attached to the
     character-port.  To set each direction separately the keywords
     `input-readtable:' and `output-readtable:' must be used instead of
     `readtable:'.  Readtables control the external textual
     representation of Scheme objects, that is the encoding of Scheme
     objects using characters.  The behavior of the `read' procedure
     depends on the port's input-readtable and the behavior of the
     procedures `write', `pretty-print', and related procedures is
     affected by the port's output-readtable.  The default value of this
     setting is the value bound to the parameter object
     `current-readtable'.

   * `output-width:' POSITIVE-INTEGER

     This setting indicates the width of the character output-port in
     number of characters.  This information is used by the
     pretty-printer.  The default value of this setting is 80.



File: gambit-c.info,  Node: Character-port operations,  Prev: Character-port settings,  Up: Character-ports

17.5.2 Character-port operations
--------------------------------

 -- procedure: input-port-line PORT
 -- procedure: input-port-column PORT
 -- procedure: output-port-line PORT
 -- procedure: output-port-column PORT
     The current character location of a character input-port is the
     location of the next character to read.  The current character
     location of a character output-port is the location of the next
     character to write.  Location is denoted by a line number (the
     first line is line 1) and a column number, that is the location on
     the current line (the first column is column 1).  The procedures
     `input-port-line' and `input-port-column' return the line location
     and the column location respectively of the character input-port
     PORT.  The procedures `output-port-line' and `output-port-column'
     return the line location and the column location respectively of
     the character output-port PORT.

     For example:

          > (call-with-output-string
              '()
              (lambda (p)
                (display "abc\n123def" p)
                (write (list (output-port-line p) (output-port-column p))
                       p)))
          "abc\n123def(2 7)"


 -- procedure: output-port-width PORT
     This procedure returns the width, in characters, of the character
     output-port PORT.  The value returned is the port's output-width
     setting.

     For example:

          > (output-port-width (repl-output-port))
          80


 -- procedure: read-char [PORT]
     This procedure reads the character input-port PORT and returns the
     character at the current character location and advances the
     current character location to the next character, unless the PORT
     is already at end-of-file in which case `read-char' returns the
     end-of-file object.  If it is not specified, PORT defaults to the
     current input-port.

     For example:

          > (call-with-input-string
              "some text"
              (lambda (p)
                (let ((a (read-char p))) (list a (read-char p)))))
          (#\s #\o)
          > (call-with-input-string "" read-char)
          #!eof


 -- procedure: peek-char [PORT]
     This procedure returns the same result as `read-char' but it does
     not advance the current character location of the input-port PORT.
     If it is not specified, PORT defaults to the current input-port.

     For example:

          > (call-with-input-string
              "some text"
              (lambda (p)
                (let ((a (peek-char p))) (list a (read-char p)))))
          (#\s #\s)
          > (call-with-input-string "" peek-char)
          #!eof


 -- procedure: write-char CHAR [PORT]
     This procedure writes the character CHAR to the character
     output-port PORT and advances the current character location of
     that output-port.  The value returned is unspecified.  If it is not
     specified, PORT defaults to the current output-port.

     For example:

          > (write-char #\=)
          =>


 -- procedure: read-line [PORT [SEPARATOR [INCLUDE-SEPARATOR?]]]
     This procedure reads characters from the character input-port PORT
     until a specific SEPARATOR or the end-of-file is encountered and
     returns a string containing the sequence of characters read.  The
     SEPARATOR is included at the end of the string only if it was the
     last character read and INCLUDE-SEPARATOR? is not `#f'.  The
     SEPARATOR must be a character or `#f' (in which case all the
     characters until the end-of-file are read).  If it is not
     specified, PORT defaults to the current input-port.  If it is not
     specified, SEPARATOR defaults to `#\newline'.  If it is not
     specified, INCLUDE-SEPARATOR? defaults to `#f'.

     For example:

          > (define (split sep)
              (lambda (str)
                (call-with-input-string
                  str
                  (lambda (p)
                    (read-all p (lambda (p) (read-line p sep)))))))
          > ((split #\,) "a,b,c")
          ("a" "b" "c")
          > (map (split #\,)
                 (call-with-input-string "1,2,3\n4,5"
                                         (lambda (p) (read-all p read-line))))
          (("1" "2" "3") ("4" "5"))


 -- procedure: read-substring STRING START END [PORT]
 -- procedure: write-substring STRING START END [PORT]
     These procedures support bulk character I/O.  The part of the
     string STRING starting at index START and ending just before index
     END is used as a character buffer that will be the target of
     `read-substring' or the source of the `write-substring'.  Up to
     END-START characters will be transferred.  The number of
     characters transferred, possibly zero, is returned by these
     procedures.  Fewer characters will be read by `read-substring' if
     an end-of-file is read, or a timeout occurs before all the
     requested characters are transferred and the timeout thunk returns
     `#f' (see the procedure `input-port-timeout-set!').  Fewer
     characters will be written by `write-substring' if a timeout
     occurs before all the requested characters are transferred and the
     timeout thunk returns `#f' (see the procedure
     `output-port-timeout-set!').  If it is not specified, PORT
     defaults to the current input-port and current output-port
     respectively.

     For example:

          > (define s (make-string 10 #\x))
          > (read-substring s 2 5)123456789
          3
          > 456789
          > s
          "xx123xxxxx"


 -- procedure: input-port-readtable PORT
 -- procedure: output-port-readtable PORT
     These procedures return the readtable attached to the
     character-port PORT.  The PORT parameter of `input-port-readtable'
     must be an input-port.  The PORT parameter of
     `output-port-readtable' must be an output-port.


 -- procedure: input-port-readtable-set! PORT READTABLE
 -- procedure: output-port-readtable-set! PORT READTABLE
     These procedures change the readtable attached to the
     character-port PORT to the readtable READTABLE.  The PORT parameter
     of `input-port-readtable-set!'  must be an input-port.  The PORT
     parameter of `output-port-readtable-set!' must be an output-port.
     The value returned is unspecified.



File: gambit-c.info,  Node: Byte-ports,  Next: Device-ports,  Prev: Character-ports,  Up: I/O and ports

17.6 Byte-ports
===============

* Menu:

* Byte-port settings::               Byte-port settings
* Byte-port operations::             Byte-port operations


File: gambit-c.info,  Node: Byte-port settings,  Next: Byte-port operations,  Prev: Byte-ports,  Up: Byte-ports

17.6.1 Byte-port settings
-------------------------

The following is a list of port settings that are valid for byte-ports.

   * `char-encoding:' ENCODING

     This setting controls the character encoding of the byte-port.  For
     bidirectional byte-ports, the character encoding for input and
     output is set.  To set each direction separately the keywords
     `input-char-encoding:' and `output-char-encoding:' must be used
     instead of `char-encoding:'.  The default value of this setting is
     operating system dependent, but this can be overridden through the
     runtime options (*note Runtime options::).  The following
     encodings are supported:

    `ISO-8859-1'
          ISO-8859-1 character encoding.  Each character is encoded by
          a single byte.  Only Unicode characters with a code in the
          range 0 to 255 are allowed.

    `ASCII'
          ASCII character encoding.  Each character is encoded by a
          single byte.  In principle only Unicode characters with a
          code in the range 0 to 127 are allowed but most types of
          ports treat this exactly like `ISO-8859-1'.

    `UTF-8'
          UTF-8 character encoding.  Each character is encoded by a
          sequence of one to four bytes.  The minimum length UTF-8
          encoding is used.  If a BOM is needed at the beginning of the
          stream then it must be explicitly written.

    `UTF-16'
          UTF-16 character encoding.  Each character is encoded by one
          or two 16 bit integers (2 or 4 bytes).  The 16 bit integers
          may be encoded using little-endian encoding or big-endian
          encoding.  If the port is an input-port and the first two
          bytes read are a BOM ("Byte Order Mark" character with
          hexadecimal code FEFF) then the BOM will be discarded and the
          endianness will be set accordingly, otherwise the endianness
          depends on the operating system and how the Gambit runtime was
          compiled.  If the port is an output-port then a BOM will be
          output at the beginning of the stream and the endianness
          depends on the operating system and how the Gambit runtime
          was compiled.

    `UTF-16LE'
          UTF-16 character encoding with little-endian endianness.  It
          is like `UTF-16' except the endianness is set to
          little-endian and there is no BOM processing.  If a BOM is
          needed at the beginning of the stream then it must be
          explicitly written.

    `UTF-16BE'
          UTF-16 character encoding with big-endian endianness.  It is
          like `UTF-16LE' except the endianness is set to big-endian.

    `UTF'
          This encoding combines the UTF-8 and UTF-16 encodings.  When
          `UTF' is used for an output port, characters will be encoded
          using the UTF-8 encoding.  The first character, if there is
          one, is prefixed with a UTF-8 BOM (the three byte sequence EF
          BB BF in hexadecimal).  When `UTF' is used for an input port,
          the character encoding depends on the first few bytes.  If
          the first bytes of the stream are a UTF-16LE BOM (FF FE in
          hexadecimal), or a UTF-16BE BOM (FE FF in hexadecimal), or a
          UTF-8 BOM (EF BB BF in hexadecimal), then the BOM is
          discarded and the remaining bytes of the stream are decoded
          using the corresponding character encoding.  If a BOM is not
          present, then the stream is decoded using the UTF-8 encoding.
          Note that this character encoding for input will correctly
          handle streams produced using the encodings `UTF', `UTF-8',
          `UTF-16', `ASCII', and if an explicit BOM is output, the
          encodings `UTF-16LE', and `UTF-16BE'.

    `UCS-2'
          UCS-2 character encoding.  Each character is encoded by a 16
          bit integer (2 bytes).  The 16 bit integers may be encoded
          using little-endian encoding or big-endian encoding.  If the
          port is an input-port and the first two bytes read are a BOM
          ("Byte Order Mark" character with hexadecimal code FEFF) then
          the BOM will be discarded and the endianness will be set
          accordingly, otherwise the endianness depends on the
          operating system and how the Gambit runtime was compiled.  If
          the port is an output-port then a BOM will be output at the
          beginning of the stream and the endianness depends on the
          operating system and how the Gambit runtime was compiled.

    `UCS-2LE'
          UCS-2 character encoding with little-endian endianness.  It
          is like `UCS-2' except the endianness is set to little-endian
          and there is no BOM processing.  If a BOM is needed at the
          beginning of the stream then it must be explicitly written.

    `UCS-2BE'
          UCS-2 character encoding with big-endian endianness.  It is
          like `UCS-2LE' except the endianness is set to big-endian.

    `UCS-4'
          UCS-4 character encoding.  Each character is encoded by a 32
          integer (4 bytes).  The 32 bit integers may be encoded using
          little-endian encoding or big-endian encoding.  If the port
          is an input-port and the first four bytes read are a BOM
          ("Byte Order Mark" character with hexadecimal code 0000FEFF)
          then the BOM will be discarded and the endianness will be set
          accordingly, otherwise the endianness depends on the
          operating system and how the Gambit runtime was compiled.  If
          the port is an output-port then a BOM will be output at the
          beginning of the stream and the endianness depends on the
          operating system and how the Gambit runtime was compiled.

    `UCS-4LE'
          UCS-4 character encoding with little-endian endianness.  It
          is like `UCS-4' except the endianness is set to little-endian
          and there is no BOM processing.  If a BOM is needed at the
          beginning of the stream then it must be explicitly written.

    `UCS-4BE'
          UCS-4 character encoding with big-endian endianness.  It is
          like `UCS-4LE' except the endianness is set to big-endian.


   * `char-encoding-errors:' ( `#f' | `#t' )

     This setting controls whether illegal character encodings are
     silently replaced with the Unicode character #xfffd (replacement
     character) or raise an error.  To set each direction separately
     the keywords `input-char-encoding-errors:' and
     `output-char-encoding-errors:' must be used instead of
     `char-encoding-errors:'.  The default value of this setting is
     `#t'.

   * `eol-encoding:' ENCODING

     This setting controls the end-of-line encoding of the byte-port.
     To set each direction separately the keywords `input-eol-encoding:'
     and `output-eol-encoding:' must be used instead of
     `eol-encoding:'.  The default value of this setting is operating
     system dependent, but this can be overridden through the runtime
     options (*note Runtime options::).  Note that for output-ports the
     end-of-line encoding is applied before the character encoding, and
     for input-ports it is applied after.  The following encodings are
     supported:

    `lf'
          For an output-port, writing a `#\newline' character outputs a
          `#\linefeed' character to the stream (Unicode character code
          10).  For an input-port, a `#\newline' character is read when
          a `#\linefeed' character is encountered on the stream.  Note
          that `#\linefeed' and `#\newline' are two names for the same
          character, so this end-of-line encoding is actually the
          identity function.  Text files created by UNIX applications
          typically use this end-of-line encoding.

    `cr'
          For an output-port, writing a `#\newline' character outputs a
          `#\return' character to the stream (Unicode character code
          13).  For an input-port, a `#\newline' character is read when
          a `#\linefeed' character or a `#\return' character is
          encountered on the stream.  Text files created by Classic Mac
          OS applications typically use this end-of-line encoding.

    `cr-lf'
          For an output-port, writing a `#\newline' character outputs to
          the stream a `#\return' character followed by a `#\linefeed'
          character.  For an input-port, a `#\newline' character is read
          when a `#\linefeed' character or a `#\return' character is
          encountered on the stream.  Moreover, if this character is
          immediately followed by the opposite character (`#\linefeed'
          followed by `#\return' or `#\return' followed by
          `#\linefeed') then the second character is ignored.  In other
          words, all four possible end-of-line encodings are read as a
          single `#\newline' character.  Text files created by DOS and
          Microsoft Windows applications typically use this end-of-line
          encoding.




File: gambit-c.info,  Node: Byte-port operations,  Prev: Byte-port settings,  Up: Byte-ports

17.6.2 Byte-port operations
---------------------------

 -- procedure: read-u8 [PORT]
     This procedure reads the byte input-port PORT and returns the byte
     at the current byte location and advances the current byte
     location to the next byte, unless the PORT is already at
     end-of-file in which case `read-u8' returns the end-of-file
     object.  If it is not specified, PORT defaults to the current
     input-port.

     This procedure must be called when the port's input character
     buffer is empty otherwise the character-stream and byte-stream may
     be out of sync due to buffering.  The input character buffer is
     used for bulk decoding of encoded characters (i.e. to translate
     the byte-stream into a character-stream).  The input character
     buffer is initially empty.  It is only when characters are read
     that it is filled with characters obtained by decoding the
     byte-stream.

     One way to ensure that the port's input character buffer is empty
     is to call `read-u8' strictly before any use of the port in a
     character input operation (i.e. a call to the procedures `read',
     `read-char', `peek-char', etc).  Alternatively
     `input-port-characters-buffered' can be used to get the number of
     characters in the port's input character buffer, and to empty the
     buffer with calls to `read-char' or `read-substring'.

     For example:

          > (call-with-input-u8vector
              '#u8(11 22 33 44)
              (lambda (p)
                (let ((a (read-u8 p))) (list a (read-u8 p)))))
          (11 22)
          > (call-with-input-u8vector '#u8() read-u8)
          #!eof


 -- procedure: write-u8 N [PORT]
     This procedure writes the byte N to the byte output-port PORT and
     advances the current byte location of that output-port.  The value
     returned is unspecified.  If it is not specified, PORT defaults to
     the current output-port.

     For example:

          > (call-with-output-u8vector '() (lambda (p) (write-u8 33 p)))
          #u8(33)


 -- procedure: read-subu8vector U8VECTOR START END [PORT]
 -- procedure: write-subu8vector U8VECTOR START END [PORT]
     These procedures support bulk byte I/O.  The part of the u8vector
     U8VECTOR starting at index START and ending just before index END
     is used as a byte buffer that will be the target of
     `read-subu8vector' or the source of the `write-subu8vector'.  Up
     to END-START bytes will be transferred.  The number of bytes
     transferred, possibly zero, is returned by these procedures.
     Fewer bytes will be read by `read-subu8vector' if an end-of-file
     is read, or a timeout occurs before all the requested bytes are
     transferred and the timeout thunk returns `#f' (see the procedure
     `input-port-timeout-set!').  Fewer bytes will be written by
     `write-subu8vector' if a timeout occurs before all the requested
     bytes are transferred and the timeout thunk returns `#f' (see the
     procedure `output-port-timeout-set!').  If it is not specified,
     PORT defaults to the current input-port and current output-port
     respectively.

     The procedure `read-subu8vector' must be called before any use of
     the port in a character input operation (i.e. a call to the
     procedures `read', `read-char', `peek-char', etc) because
     otherwise the character-stream and byte-stream may be out of sync
     due to the port buffering.

     For example:

          > (define v (make-u8vector 10))
          > (read-subu8vector v 2 5)123456789
          3
          > 456789
          > v
          #u8(0 0 49 50 51 0 0 0 0 0)



File: gambit-c.info,  Node: Device-ports,  Next: Directory-ports,  Prev: Byte-ports,  Up: I/O and ports

17.7 Device-ports
=================

* Menu:

* Filesystem devices::            Filesystem devices
* Process devices::               Process devices
* Network devices::               Network devices


File: gambit-c.info,  Node: Filesystem devices,  Next: Process devices,  Prev: Device-ports,  Up: Device-ports

17.7.1 Filesystem devices
-------------------------

 -- procedure: open-file PATH-OR-SETTINGS
 -- procedure: open-input-file PATH-OR-SETTINGS
 -- procedure: open-output-file PATH-OR-SETTINGS
 -- procedure: call-with-input-file PATH-OR-SETTINGS PROC
 -- procedure: call-with-output-file PATH-OR-SETTINGS PROC
 -- procedure: with-input-from-file PATH-OR-SETTINGS THUNK
 -- procedure: with-output-to-file PATH-OR-SETTINGS THUNK
     All of these procedures create a port to interface to a byte-stream
     device (such as a file, console, serial port, named pipe, etc)
     whose name is given by a path of the filesystem.  The `direction:'
     setting will default to the value `input' for the procedures
     `open-input-file', `call-with-input-file' and
     `with-input-from-file', to the value `output' for the procedures
     `open-output-file', `call-with-output-file' and
     `with-output-to-file', and to the value `input-output' for the
     procedure `open-file'.  The procedures `open-file',
     `open-input-file' and `open-output-file' return the port that is
     created.  The procedures `call-with-input-file' and
     `call-with-output-file' call the procedure PROC with the port as
     single argument, and then return the value(s) of this call after
     closing the port.  The procedures `with-input-from-file' and
     `with-output-to-file' dynamically bind the current input-port and
     current output-port respectively to the port created for the
     duration of a call to the procedure THUNK with no argument.  The
     value(s) of the call to THUNK are returned after closing the port.

     The first argument of these procedures is either a string denoting
     a filesystem path or a list of port settings which must contain a
     `path:' setting.  Here are the settings allowed in addition to the
     generic settings of byte-ports:

        * `path:' STRING

          This setting indicates the location of the file in the
          filesystem.  There is no default value for this setting.

        * `append:' ( `#f' | `#t' )

          This setting controls whether output will be added to the end
          of the file.  This is useful for writing to log files that
          might be open by more than one process.  The default value of
          this setting is `#f'.

        * `create:' ( `#f' | `#t' | `maybe' )

          This setting controls whether the file will be created when
          it is opened.  A setting of `#f' requires that the file exist
          (otherwise an exception is raised).  A setting of `#t'
          requires that the file does not exist (otherwise an exception
          is raised).  A setting of `maybe' will create the file if it
          does not exist.  The default value of this setting is `maybe'
          for output-ports and `#f' for input-ports and bidirectional
          ports.

        * `permissions:' 12-BIT-EXACT-INTEGER

          This setting controls the UNIX permissions that will be
          attached to the file if it is created.  The default value of
          this setting is `#o666'.

        * `truncate:' ( `#f' | `#t' )

          This setting controls whether the file will be truncated when
          it is opened.  For input-ports, the default value of this
          setting is `#f'.  For output-ports, the default value of this
          setting is `#t' when the `append:' setting is `#f', and `#f'
          otherwise.


     For example:

          > (with-output-to-file
              (list path: "nofile"
                    create: #f)
              (lambda ()
                (display "hello world!\n")))
          *** ERROR IN (console)@1.1 -- No such file or directory
          (with-output-to-file '(path: "nofile" create: #f) '#<procedure #2>)


 -- procedure: input-port-byte-position PORT [POSITION [WHENCE]]
 -- procedure: output-port-byte-position PORT [POSITION [WHENCE]]
     When called with a single argument these procedures return the byte
     position where the next I/O operation would take place in the file
     attached to the given PORT (relative to the beginning of the
     file).  When called with two or three arguments, the byte position
     for subsequent I/O operations on the given PORT is changed to
     POSITION, which must be an exact integer.  When WHENCE is omitted
     or is 0, the POSITION is relative to the beginning of the file.
     When WHENCE is 1, the POSITION is relative to the current byte
     position of the file.  When WHENCE is 2, the POSITION is relative
     to the end of the file.  The return value is the new byte
     position.  On most operating systems the byte position for reading
     and writing of a given bidirectional port are the same.

     When `input-port-byte-position' is called to change the byte
     position of an input-port, all input buffers will be flushed so
     that the next byte read will be the one at the given position.

     When `output-port-byte-position' is called to change the byte
     position of an output-port, there is an implicit call to
     `force-output' before the position is changed.

     For example:

          > (define p  ; p is an input-output-port
              (open-file '(path: "test" char-encoding: ISO-8859-1 create: maybe)))
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (0 0)
          > (display "abcdefghij\n" p)
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (0 0)
          > (force-output p)
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (11 11)
          > (input-port-byte-position p 2)
          2
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (2 2)
          > (peek-char p)
          #\c
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (11 11)
          > (output-port-byte-position p -7 2)
          4
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (4 4)
          > (write-char #\! p)
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (4 4)
          > (force-output p)
          > (list (input-port-byte-position p) (output-port-byte-position p))
          (5 5)
          > (input-port-byte-position p 1)
          1
          > (read p)
          bcd!fghij



File: gambit-c.info,  Node: Process devices,  Next: Network devices,  Prev: Filesystem devices,  Up: Device-ports

17.7.2 Process devices
----------------------

 -- procedure: open-process PATH-OR-SETTINGS
     This procedure starts a new process and returns a port that allows
     communication with that process on its standard input and standard
     output.  The default value of the `direction:' setting is
     `input-output', i.e. the Scheme program can write to the process'
     standard input and can read from the process' standard output.

     The first argument of this procedure is either a string denoting a
     filesystem path of an executable program or a list of port settings
     which must contain a `path:' setting.  Here are the settings
     allowed in addition to the generic settings of byte-ports:

        * `path:' STRING

          This setting indicates the location of the executable program
          in the filesystem.  There is no default value for this
          setting.

        * `arguments:' LIST-OF-STRINGS

          This setting indicates the string arguments that are passed
          to the program.  The default value of this setting is the
          empty list (i.e. no arguments).

        * `environment:' LIST-OF-STRINGS

          This setting indicates the set of environment variable
          bindings that the process receives.  Each element of the list
          is a string of the form "`VAR=VALUE'", where `VAR' is the
          name of the variable and `VALUE' is its binding.  When
          LIST-OF-STRINGS is `#f', the process inherits the environment
          variable bindings of the Scheme program.  The default value
          of this setting is `#f'.

        * `directory:' DIR

          This setting indicates the current working directory of the
          process.  When DIR is `#f', the process uses the value of
          `(current-directory)'.  The default value of this setting is
          `#f'.

        * `stdin-redirection:' ( `#f' | `#t' )

          This setting indicates how the standard input of the process
          is redirected.  A setting of `#t' will redirect the standard
          input from the process-port (i.e. what is written to the
          process-port will be available on the standard input).  A
          setting of `#f' will leave the standard input as-is, which
          typically results in input coming from the console.  The
          default value of this setting is `#t'.

        * `stdout-redirection:' ( `#f' | `#t' )

          This setting indicates how the standard output of the process
          is redirected.  A setting of `#t' will redirect the standard
          output to the process-port (i.e. all output to standard
          output can be read from the process-port).  A setting of `#f'
          will leave the standard output as-is, which typically results
          in the output going to the console.  The default value of
          this setting is `#t'.

        * `stderr-redirection:' ( `#f' | `#t' )

          This setting indicates how the standard error of the process
          is redirected.  A setting of `#t' will redirect the standard
          error to the process-port (i.e. all output to standard error
          can be read from the process-port).  A setting of `#f' will
          leave the standard error as-is, which typically results in
          error messages being output to the console.  The default
          value of this setting is `#f'.

        * `pseudo-terminal:' ( `#f' | `#t' )

          This setting applies to UNIX.  It indicates what type of
          device will be bound to the process' standard input and
          standard output.  A setting of `#t' will use a
          pseudo-terminal device (this is a device that behaves like a
          tty device even though there is no real terminal or user
          directly involved).  A setting of `#f' will use a pair of
          pipes.  The difference is important for programs which behave
          differently when they are used interactively, for example
          shells.  The default value of this setting is `#f'.

        * `show-console:' ( `#f' | `#t' )

          This setting applies to Microsoft Windows.  It controls
          whether the process' console window will be hidden or
          visible.  The default value of this setting is `#t' (i.e.
          show the console window).


     For example:

          > (define p (open-process (list path: "ls"
                                          arguments: '("../examples"))))
          > (read-line p)
          "README"
          > (read-line p)
          "Xlib-simple"
          > (close-port p)
          > (define p (open-process "/usr/bin/dc"))
          > (display "2 100 ^ p\n" p)
          > (force-output p)
          > (read-line p)
          "1267650600228229401496703205376"



File: gambit-c.info,  Node: Network devices,  Prev: Process devices,  Up: Device-ports

17.7.3 Network devices
----------------------

 -- procedure: open-tcp-client SETTINGS
     This procedure opens a network connection to a socket server and
     returns a tcp-client-port (a subtype of device-port) that
     represents this connection and allows communication with that
     server.  The default value of the `direction:' setting is
     `input-output', i.e. the Scheme program can send information to
     the server and receive information from the server.  The sending
     direction can be "shutdown" using the `close-output-port'
     procedure and the receiving direction can be "shutdown" using the
     `close-input-port' procedure.  The `close-port' procedure closes
     both directions of the connection.

     The first argument of this procedure is a list of port settings
     which must contain a `server-address:' setting and a
     `port-number:' setting.  Here are the settings allowed in addition
     to the generic settings of byte-ports:

        * `server-address:' STRING-OR-IP-ADDRESS

          This setting indicates the internet address of the server.
          It can be a string denoting a host name, which will be
          translated to an IP address by the `host-info' procedure, or
          a 4 element u8vector which contains the 32-bit IPv4 address
          or an 8 element u16vector which contains the 128-bit IPv6
          address.  There is no default value for this setting.

        * `port-number:' 16-BIT-EXACT-INTEGER

          This setting indicates the IP port-number of the server to
          connect to (e.g. 80 for the standard HTTP server, 23 for the
          standard telnet server).  There is no default value for this
          setting.

        * `keep-alive:' ( `#f' | `#t' )

          This setting controls the use of the "keep alive" option on
          the connection.  The "keep alive" option will periodically
          send control packets on otherwise idle network connections to
          ensure that the server host is active and reachable.  The
          default value of this setting is `#f'.

        * `coalesce:' ( `#f' | `#t' )

          This setting controls the use of TCP's "Nagle algorithm" which
          reduces the number of small packets by delaying their
          transmission and coalescing them into larger packets.  A
          setting of `#t' will coalesce small packets into larger ones.
          A setting of `#f' will transmit packets as soon as possible.
          The default value of this setting is `#t'.  Note that this
          setting does not affect the buffering of the port.


     Here is an example of the client-side code that opens a connection
     to an HTTP server on port 8080 on the same computer (for the
     server-side code see the example for the procedure
     `open-tcp-server'):

          > (define p (open-tcp-client (list server-address: '#u8(127 0 0 1)
                                             port-number: 8080
                                             eol-encoding: 'cr-lf)))
          > p
          #<input-output-port #2 (tcp-client #u8(127 0 0 1) 8080)>
          > (display "GET /\n" p)
          > (force-output p)
          > (read-line p)
          "<HTML>"


 -- procedure: open-tcp-server PORT-NUMBER-OR-SETTINGS
     This procedure sets up a socket to accept network connection
     requests from clients and returns a tcp-server-port from which
     network connections to clients are obtained.  Tcp-server-ports are
     a direct subtype of object-ports (i.e. they are not
     character-ports) and are input-ports.  Reading from a
     tcp-server-port with the `read' procedure will block until a
     network connection request is received from a client.  The `read'
     procedure will then return a tcp-client-port (a subtype of
     device-port) that represents this connection and allows
     communication with that client.  Closing a tcp-server-port with
     either the `close-input-port' or `close-port' procedures will
     cause the network subsystem to stop accepting connections on that
     socket.

     The first argument of this procedure is an IP port-number (16-bit
     nonnegative exact integer) or a list of port settings which must
     contain a `port-number:' setting.  Below is a list of the settings
     allowed in addition to the settings `keep-alive:' and `coalesce:'
     allowed by the `open-tcp-client' procedure and the generic
     settings of byte-ports.  The settings which are not listed below
     apply to the tcp-client-port that is returned by `read' when a
     connection is accepted and have the same meaning as if they were
     used in a call to the `open-tcp-client' procedure.

        * `server-address:' STRING-OR-IP-ADDRESS

          This setting indicates the internet address of the network
          interface on which connections requests are accepted.  When
          this parameter is not specified or is `#f', the connection
          requests are accepted on all network interfaces (i.e. address
          INADDR_ANY).  The parameter can be a string denoting a host
          name, which will be translated to an IP address by the
          `host-info' procedure, or a 4 element u8vector which contains
          the 32-bit IPv4 address or an 8 element u16vector which
          contains the 128-bit IPv6 address.

        * `port-number:' 16-BIT-EXACT-INTEGER

          This setting indicates the IP port-number assigned to the
          socket which accepts connection requests from clients.  So
          called "well-known ports", which are reserved for standard
          services, have a port-number below 1024 and can only be
          assigned to a socket by a process with superuser priviledges
          (e.g. 80 for the HTTP service, 23 for the telnet service).
          No special priviledges are needed to assign higher
          port-numbers to a socket.  The special value 0 requests that a
          currently unused port number be assigned to the socket (the
          port number assigned can be retrieved using the procedure
          `tcp-server-socket-info').  There is no default value for this
          setting.

        * `backlog:' POSITIVE-EXACT-INTEGER

          This setting indicates the maximum number of connection
          requests that can be waiting to be accepted by a call to
          `read' (technically it is the value passed as the second
          argument of the UNIX `listen()' function).  The default value
          of this setting is 128.

        * `reuse-address:' ( `#f' | `#t' )

          This setting controls whether it is possible to assign a
          port-number that is currently active.  Note that when a
          server process terminates, the socket it was using to accept
          connection requests does not become inactive immediately.
          Instead it remains active for a few minutes to ensure clean
          termination of the connections.  A setting of `#f' will cause
          an exception to be raised in that case.  A setting of `#t'
          will allow a port-number to be used even if it is active.
          The default value of this setting is `#t'.


     Here is an example of the server-side code that accepts
     connections on port 8080 (for the client-side code see the example
     for the procedure `open-tcp-client'):

          > (define s (open-tcp-server (list port-number: 8080
                                             eol-encoding: 'cr-lf)))
          > (define p (read s))  ; blocks until client connects
          > p
          #<input-output-port #2 (tcp-client 8080)>
          > (read-line p)
          "GET /"
          > (display "<HTML>\n" p)
          > (force-output p)



File: gambit-c.info,  Node: Directory-ports,  Next: Vector-ports,  Prev: Device-ports,  Up: I/O and ports

17.8 Directory-ports
====================

 -- procedure: open-directory PATH-OR-SETTINGS
     This procedure opens a directory of the filesystem for reading its
     entries and returns a directory-port from which the entries can be
     enumerated.  Directory-ports are a direct subtype of object-ports
     (i.e. they are not character-ports) and are input-ports.  Reading
     from a directory-port with the `read' procedure returns the next
     file name in the directory as a string.  The end-of-file object is
     returned when all the file names have been enumerated.  Another
     way to get the list of all files in a directory is the
     `directory-files' procedure which returns a list of the files in
     the directory.  The advantage of using directory-ports is that it
     allows iterating over the files in a directory in constant space,
     which is interesting when the number of files in the directory is
     not known in advance and may be large.  Note that the order in
     which the names are returned is operating-system dependent.

     The first argument of this procedure is either a string denoting a
     filesystem path to a directory or a list of port settings which
     must contain a `path:' setting.  Here are the settings allowed in
     addition to the generic settings of object-ports:

        * `path:' STRING

          This setting indicates the location of the directory in the
          filesystem.  There is no default value for this setting.

        * `ignore-hidden:' ( `#f' | `#t' | `dot-and-dot-dot' )

          This setting controls whether hidden-files will be returned.
          Under UNIX and Mac OS X hidden-files are those that start
          with a period (such as `.', `..', and `.profile').  Under
          Microsoft Windows hidden files are the `.' and `..' entries
          and the files whose "hidden file" attribute is set.  A
          setting of `#f' will enumerate all the files.  A setting of
          `#t' will only enumerate the files that are not hidden.  A
          setting of `dot-and-dot-dot' will enumerate all the files
          except for the `.' and `..' hidden files.  The default value
          of this setting is `#t'.


     For example:

          > (let ((p (open-directory (list path: "../examples"
                                           ignore-hidden: #f))))
              (let loop ()
                (let ((fn (read p)))
                  (if (string? fn)
                      (begin
                        (pp (path-expand fn))
                        (loop)))))
              (close-input-port p))
          "/u/feeley/examples/."
          "/u/feeley/examples/.."
          "/u/feeley/examples/complex"
          "/u/feeley/examples/README"
          "/u/feeley/examples/simple"
          > (define x (open-directory "../examples"))
          > (read-all x)
          ("complex" "README" "simple")



File: gambit-c.info,  Node: Vector-ports,  Next: String-ports,  Prev: Directory-ports,  Up: I/O and ports

17.9 Vector-ports
=================

 -- procedure: open-vector [VECTOR-OR-SETTINGS]
 -- procedure: open-input-vector [VECTOR-OR-SETTINGS]
 -- procedure: open-output-vector [VECTOR-OR-SETTINGS]
 -- procedure: call-with-input-vector VECTOR-OR-SETTINGS PROC
 -- procedure: call-with-output-vector VECTOR-OR-SETTINGS PROC
 -- procedure: with-input-from-vector VECTOR-OR-SETTINGS THUNK
 -- procedure: with-output-to-vector VECTOR-OR-SETTINGS THUNK
     Vector-ports represent streams of Scheme objects.  They are a
     direct subtype of object-ports (i.e. they are not
     character-ports).  All of these procedures create vector-ports
     that are either unidirectional or bidirectional.  The `direction:'
     setting will default to the value `input' for the procedures
     `open-input-vector', `call-with-input-vector' and
     `with-input-from-vector', to the value `output' for the procedures
     `open-output-vector', `call-with-output-vector' and
     `with-output-to-vector', and to the value `input-output' for the
     procedure `open-vector'.  Bidirectional vector-ports behave like
     FIFOs: data written to the port is added to the end of the stream
     that is read.  It is only when a bidirectional vector-port's
     output-side is closed with a call to the `close-output-port'
     procedure that the stream's end is known (when the stream's end is
     reached, reading the port returns the end-of-file object).

     The procedures `open-vector', `open-input-vector' and
     `open-output-vector' return the port that is created.  The
     procedures `call-with-input-vector' and `call-with-output-vector'
     call the procedure PROC with the port as single argument, and then
     return the value(s) of this call after closing the port.  The
     procedures `with-input-from-vector' and `with-output-to-vector'
     dynamically bind the current input-port and current output-port
     respectively to the port created for the duration of a call to the
     procedure THUNK with no argument.  The value(s) of the call to
     THUNK are returned after closing the port.

     The first argument of these procedures is either a vector of the
     elements used to initialize the stream or a list of port settings.
     If it is not specified, the argument of the `open-vector',
     `open-input-vector', and `open-output-vector' procedures defaults
     to an empty list of port settings.  Here are the settings allowed
     in addition to the generic settings of object-ports:

        * `init:' VECTOR

          This setting indicates the initial content of the stream.
          The default value of this setting is an empty vector.

        * `permanent-close:' ( `#f' | `#t' )

          This setting controls whether a call to the procedures
          `close-output-port' will close the output-side of a
          bidirectional vector-port permanently or not.  A permanently
          closed bidirectional vector-port whose end-of-file has been
          reached on the input-side will return the end-of-file object
          for all subsequent calls to the `read' procedure.  A
          non-permanently closed bidirectional vector-port will return
          to its opened state when its end-of-file is read.  The
          default value of this setting is `#t'.


     For example:

          > (define p (open-vector))
          > (write 1 p)
          > (write 2 p)
          > (write 3 p)
          > (read p)
          1
          > (read p)
          2
          > (close-output-port p)
          > (read p)
          3
          > (read p)
          #!eof


 -- procedure: open-vector-pipe [VECTOR-OR-SETTINGS1
          [VECTOR-OR-SETTINGS2]]
     The procedure `open-vector-pipe' creates two vector-ports and
     returns these two ports.  The two ports are interrelated as
     follows: the first port's output-side is connected to the second
     port's input-side and the first port's input-side is connected to
     the second port's output-side.  The value VECTOR-OR-SETTINGS1 is
     used to setup the first vector-port and VECTOR-OR-SETTINGS2 is
     used to setup the second vector-port.  The same settings as for
     `open-vector' are allowed.  The default `direction:' setting is
     `input-output' (i.e. a bidirectional port is created).  If it is
     not specified VECTOR-OR-SETTINGS1 defaults to the empty list.  If
     it is not specified VECTOR-OR-SETTINGS2 defaults to
     VECTOR-OR-SETTINGS1 but with the `init:' setting set to the empty
     vector and with the input and output settings exchanged (e.g. if
     the first port is an input-port then the second port is an
     output-port, if the first port's input-side is non-buffered then
     the second port's output-side is non-buffered).

     For example:

          > (define (server op)
              (receive (c s) (open-vector-pipe)  ; client-side and server-side ports
                (thread-start!
                  (make-thread
                    (lambda ()
                      (let loop ()
                        (let ((request (read s)))
                          (if (not (eof-object? request))
                              (begin
                                (write (op request) s)
                                (newline s)
                                (force-output s)
                                (loop))))))))
                c))
          > (define a (server (lambda (x) (expt 2 x))))
          > (define b (server (lambda (x) (expt 10 x))))
          > (write 100 a)
          > (write 30 b)
          > (read a)
          1267650600228229401496703205376
          > (read b)
          1000000000000000000000000000000


 -- procedure: get-output-vector VECTOR-PORT
     The procedure `get-output-vector' takes an output vector-port or a
     bidirectional vector-port as argument and removes all the objects
     currently on the output-side, returning them in a vector.  The port
     remains open and subsequent output to the port and calls to the
     procedure `get-output-vector' are possible.

     For example:

          > (define p (open-vector '#(1 2 3)))
          > (write 4 p)
          > (get-output-vector p)
          #(1 2 3 4)
          > (write 5 p)
          > (write 6 p)
          > (get-output-vector p)
          #(5 6)



File: gambit-c.info,  Node: String-ports,  Next: U8vector-ports,  Prev: Vector-ports,  Up: I/O and ports

17.10 String-ports
==================

 -- procedure: open-string [STRING-OR-SETTINGS]
 -- procedure: open-input-string [STRING-OR-SETTINGS]
 -- procedure: open-output-string [STRING-OR-SETTINGS]
 -- procedure: call-with-input-string STRING-OR-SETTINGS PROC
 -- procedure: call-with-output-string STRING-OR-SETTINGS PROC
 -- procedure: with-input-from-string STRING-OR-SETTINGS THUNK
 -- procedure: with-output-to-string STRING-OR-SETTINGS THUNK
 -- procedure: open-string-pipe [STRING-OR-SETTINGS1
          [STRING-OR-SETTINGS2]]
 -- procedure: get-output-string STRING-PORT
     String-ports represent streams of characters.  They are a direct
     subtype of character-ports.  These procedures are the string-port
     analog of the procedures specified in the vector-ports section.
     Note that these procedures are a superset of the procedures
     specified in the "Basic String Ports SRFI" (SRFI 6).


 -- procedure: object->string OBJ [N]
     This procedure converts the object OBJ to its external
     representation and returns it in a string.  The parameter N
     specifies the maximal width of the resulting string.  If the
     external representation is wider than N, the resulting string will
     be truncated to N characters and the last 3 characters will be set
     to periods.  Note that the current readtable is used.



File: gambit-c.info,  Node: U8vector-ports,  Next: Parameter objects related to I/O,  Prev: String-ports,  Up: I/O and ports

17.11 U8vector-ports
====================

 -- procedure: open-u8vector [U8VECTOR-OR-SETTINGS]
 -- procedure: open-input-u8vector [U8VECTOR-OR-SETTINGS]
 -- procedure: open-output-u8vector [U8VECTOR-OR-SETTINGS]
 -- procedure: call-with-input-u8vector U8VECTOR-OR-SETTINGS PROC
 -- procedure: call-with-output-u8vector U8VECTOR-OR-SETTINGS PROC
 -- procedure: with-input-from-u8vector U8VECTOR-OR-SETTINGS THUNK
 -- procedure: with-output-to-u8vector U8VECTOR-OR-SETTINGS THUNK
 -- procedure: open-u8vector-pipe [U8VECTOR-OR-SETTINGS1
          [U8VECTOR-OR-SETTINGS2]]
 -- procedure: get-output-u8vector U8VECTOR-PORT
     U8vector-ports represent streams of bytes.  They are a direct
     subtype of byte-ports.  These procedures are the u8vector-port
     analog of the procedures specified in the vector-ports section.



File: gambit-c.info,  Node: Parameter objects related to I/O,  Prev: U8vector-ports,  Up: I/O and ports

17.12 Parameter objects related to I/O
======================================

 -- procedure: current-input-port [NEW-VALUE]
 -- procedure: current-output-port [NEW-VALUE]
 -- procedure: current-error-port [NEW-VALUE]
 -- procedure: current-readtable [NEW-VALUE]
     These procedures are parameter objects which represent
     respectively: the current input-port, the current output-port, the
     current error-port, and the current readtable.



File: gambit-c.info,  Node: Lexical syntax and readtables,  Next: C-interface,  Prev: I/O and ports,  Up: Top

18 Lexical syntax and readtables
********************************

* Menu:

* Readtables::                        Readtables
* Boolean syntax::                    Boolean syntax
* Character syntax::                  Character syntax
* String syntax::                     String syntax
* Symbol syntax::                     Symbol syntax
* Keyword syntax::                    Keyword syntax
* Box syntax::                        Box syntax
* Number syntax::                     Number syntax
* Homogeneous vector syntax::         Homogeneous vector syntax
* Special #! syntax::                 Special #! syntax
* Multiline comment syntax::          Multiline comment syntax
* Scheme infix syntax extension::     Scheme infix syntax extension


File: gambit-c.info,  Node: Readtables,  Next: Boolean syntax,  Prev: Lexical syntax and readtables,  Up: Lexical syntax and readtables

18.1 Readtables
===============

Readtables control the external textual representation of Scheme
objects, that is the encoding of Scheme objects using characters.
Readtables affect the behavior of the reader (i.e. the `read' procedure
and the parser used by the `load' procedure and the interpreter and
compiler) and the printer (i.e. the procedures `write', `display',
`pretty-print', and `pp', and the procedure used by the REPL to print
results).  To preserve write/read invariance the printer and reader
must be using compatible readtables.  For example a symbol which
contains upper case letters will be printed with special escapes if the
readtable indicates that the reader is case-insensitive.

   Readtables are immutable records whose fields specify various textual
representation aspects.  There are accessor procedures to retrieve the
content of specific fields.  There are also functional update
procedures that create a copy of a readtable, with a specific field set
to a new value.

 -- procedure: readtable? OBJ
     This procedure returns `#t' when OBJ is a readtable and `#f'
     otherwise.

     For example:

          > (readtable? (current-readtable))
          #t
          > (readtable? 123)
          #f


 -- procedure: readtable-case-conversion? READTABLE
 -- procedure: readtable-case-conversion?-set READTABLE NEW-VALUE
     The procedure `readtable-case-conversion?' returns the content of
     the `case-conversion?' field of READTABLE.  When the content of
     this field is `#f', the reader preserves the case of symbols and
     keyword objects that are read (i.e. `Ice' and `ice' are distinct
     symbols).  When the content of this field is the symbol `upcase',
     the reader converts lowercase letters to uppercase when reading
     symbols and keywords (i.e. `Ice' is read as the symbol
     `(string->symbol "ICE")').  Otherwise the reader converts
     uppercase letters to lowercase when reading symbols and keywords
     (i.e. `Ice' is read as the symbol `(string->symbol "ice")').

     The procedure `readtable-case-conversion?-set' returns a copy of
     READTABLE where only the `case-conversion?' field has been changed
     to NEW-VALUE.

     For example:

          > (output-port-readtable-set!
              (repl-output-port)
              (readtable-case-conversion?-set
                (output-port-readtable (repl-output-port))
                #f))
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-case-conversion?-set
                (input-port-readtable (repl-input-port))
                #f))
          > 'Ice
          Ice
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-case-conversion?-set
                (input-port-readtable (repl-input-port))
                #t))
          > 'Ice
          ice
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-case-conversion?-set
                (input-port-readtable (repl-input-port))
                'upcase))
          > 'Ice
          ICE


 -- procedure: readtable-keywords-allowed? READTABLE
 -- procedure: readtable-keywords-allowed?-set READTABLE NEW-VALUE
     The procedure `readtable-keywords-allowed?' returns the content of
     the `keywords-allowed?' field of READTABLE.  When the content of
     this field is `#f', the reader does not recognize keyword objects
     (i.e. `:foo' and `foo:' are read as the symbols `(string->symbol
     ":foo")' and `(string->symbol "foo:")' respectively).  When the
     content of this field is the symbol `prefix', the reader
     recognizes keyword objects that start with a colon, as in Common
     Lisp (i.e. `:foo' is read as the keyword `(string->keyword
     "foo")').  Otherwise the reader recognizes keyword objects that
     end with a colon, as in DSSSL (i.e. `foo:' is read as the symbol
     `(string->symbol "foo")').

     The procedure `readtable-keywords-allowed?-set' returns a copy of
     READTABLE where only the `keywords-allowed?' field has been
     changed to NEW-VALUE.

     For example:

          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-keywords-allowed?-set
                (input-port-readtable (repl-input-port))
                #f))
          > (map keyword? '(foo :foo foo:))
          (#f #f #f)
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-keywords-allowed?-set
                (input-port-readtable (repl-input-port))
                #t))
          > (map keyword? '(foo :foo foo:))
          (#f #f #t)
          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-keywords-allowed?-set
                (input-port-readtable (repl-input-port))
                'prefix))
          > (map keyword? '(foo :foo foo:))
          (#f #t #f)


 -- procedure: readtable-sharing-allowed? READTABLE
 -- procedure: readtable-sharing-allowed?-set READTABLE NEW-VALUE
     The procedure `readtable-sharing-allowed?' returns the content of
     the `sharing-allowed?' field of READTABLE.  The reader recognizes
     the `#N#' and `#N=DATUM' notation for circular structures and the
     printer uses this notation if and only if the content of the
     `sharing-allowed?' field is not `#f'.  Moreover when the content
     of the `sharing-allowed?' field is the symbol `serialize', the
     printer uses a special external representation that the reader
     understands and that extends write/read invariance to the
     following types: records, procedures and continuations.  Note that
     an object can be serialized and deserialized if and only if all of
     its components are serializable.

     The procedure `readtable-sharing-allowed?-set' returns a copy of
     READTABLE where only the `sharing-allowed?' field has been changed
     to NEW-VALUE.

     Here is a simple example:

          > (define (wr obj allow?)
              (call-with-output-string
                '()
                (lambda (p)
                  (output-port-readtable-set!
                    p
                    (readtable-sharing-allowed?-set
                      (output-port-readtable p)
                      allow?))
                  (write obj p))))
          > (define (rd str allow?)
              (call-with-input-string
                str
                (lambda (p)
                  (input-port-readtable-set!
                    p
                    (readtable-sharing-allowed?-set
                      (input-port-readtable p)
                      allow?))
                  (read p))))
          > (define x (list 1 2 3))
          > (set-car! (cdr x) (cddr x))
          > (wr x #f)
          "(1 (3) 3)"
          > (wr x #t)
          "(1 #0=(3) . #0#)"
          > (define y (rd (wr x #t) #t))
          > y
          (1 (3) 3)
          > (eq? (cadr y) (cddr y))
          #t
          > (define f #f)
          > (let ((free (expt 2 10)))
            (set! f (lambda (x) (+ x free))))
          > (define s (wr f 'serialize))
          > (string-length s)
          4196
          > (define g (rd s 'serialize))
          > (eq? f g)
          #f
          > (g 4)
          1028

     Continuations are tricky to serialize because they contain a
     dynamic environment and this dynamic environment may contain
     non-serializable objects, in particular ports attached to
     operating-system streams such as files, the console or standard
     input/output.  Indeed, all dynamic environments contain a binding
     for the `current-input-port' and `current-output-port'.  Moreover,
     any thread that has started a REPL has a continuation which refers
     to the "repl-context" object in its dynamic environment.  A
     repl-context object contains the interaction channel, which is
     typically connected to a non-serializable port, such as the
     console.  Another problem is that the `parameterize' form saves
     the old binding of the parameter in the continuation, so it is not
     possible to eliminate the references to these ports in the
     continuation by using the `parameterize' form alone.

     Serialization of continuations can be achieved dependably by taking
     advantage of string-ports, which are serializable objects (unless
     there is a blocked thread), and the following features of threads:
     they inherit the dynamic environment of the parent thread and they
     start with an initial continuation that contains only serializable
     objects.  So a thread created in a dynamic environment where
     `current-input-port' and `current-output-port' are bound to a
     dummy string-port has a serializable continuation.

     Here is an example where continuations are serialized:

          > (define (wr obj)
              (call-with-output-string
               '()
               (lambda (p)
                 (output-port-readtable-set!
                  p
                  (readtable-sharing-allowed?-set
                   (output-port-readtable p)
                   'serialize))
                 (write obj p))))
          > (define (rd str)
              (call-with-input-string
               str
               (lambda (p)
                 (input-port-readtable-set!
                  p
                  (readtable-sharing-allowed?-set
                   (input-port-readtable p)
                   'serialize))
                 (read p))))
          > (define fifo (open-vector))
          > (define (suspend-and-die!)
              (call-with-current-continuation
               (lambda (k)
                 (write (wr k) fifo)
                 (newline fifo)
                 (force-output fifo)
                 (thread-terminate! (current-thread)))))
          > (let ((dummy-port (open-string)))
              (parameterize ((current-input-port dummy-port)
                             (current-output-port dummy-port))
                (thread-start!
                 (make-thread
                  (lambda ()
                    (* 100
                       (suspend-and-die!)))))))
          #<thread #2>
          > (define s (read fifo))
          > (thread-join!
              (thread-start!
                (make-thread
                  (lambda ()
                    ((rd s) 111)))))
          11100
          > (thread-join!
              (thread-start!
                (make-thread
                  (lambda ()
                    ((rd s) 222)))))
          22200
          > (string-length s)
          13114


 -- procedure: readtable-eval-allowed? READTABLE
 -- procedure: readtable-eval-allowed?-set READTABLE NEW-VALUE
     The procedure `readtable-eval-allowed?' returns the content of the
     `eval-allowed?' field of READTABLE.  The reader recognizes the
     `#.EXPRESSION' notation for read-time evaluation if and only if
     the content of the `eval-allowed?' field is not `#f'.

     The procedure `readtable-eval-allowed?-set' returns a copy of
     READTABLE where only the `eval-allowed?' field has been changed to
     NEW-VALUE.

     For example:

          > (input-port-readtable-set!
              (repl-input-port)
              (readtable-eval-allowed?-set
                (input-port-readtable (repl-input-port))
                #t))
          > '(5 plus 7 is #.(+ 5 7))
          (5 plus 7 is 12)
          > '(buf = #.(make-u8vector 25))
          (buf = #u8(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))


 -- procedure: readtable-max-write-level READTABLE
 -- procedure: readtable-max-write-level-set READTABLE NEW-VALUE
     The procedure `readtable-max-write-level' returns the content of
     the `max-write-level' field of READTABLE.  The printer will
     display an ellipsis for the elements of lists and vectors that are
     nested deeper than this level.

     The procedure `readtable-max-write-level-set' returns a copy of
     READTABLE where only the `max-write-level' field has been changed
     to NEW-VALUE, which must be an nonnegative fixnum.

     For example:

          > (define (wr obj n)
              (call-with-output-string
                '()
                (lambda (p)
                  (output-port-readtable-set!
                    p
                    (readtable-max-write-level-set
                      (output-port-readtable p)
                      n))
                  (write obj p))))
          > (wr '(a #(b (c c) #u8(9 9 9) b) a) 3)
          "(a #(b (c c) #u8(9 9 9) b) a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) a) 2)
          "(a #(b (...) #u8(...) b) a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) a) 1)
          "(a #(...) a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) a) 0)
          "(...)"
          > (wr 'hello 0)
          "hello"


 -- procedure: readtable-max-write-length READTABLE
 -- procedure: readtable-max-write-length-set READTABLE NEW-VALUE
     The procedure `readtable-max-write-length' returns the content of
     the `max-write-length' field of READTABLE.  The printer will
     display an ellipsis for the elements of lists and vectors that are
     at an index beyond that length.

     The procedure `readtable-max-write-length-set' returns a copy of
     READTABLE where only the `max-write-length' field has been changed
     to NEW-VALUE, which must be an nonnegative fixnum.

     For example:

          > (define (wr obj n)
              (call-with-output-string
                '()
                (lambda (p)
                  (output-port-readtable-set!
                    p
                    (readtable-max-write-length-set
                      (output-port-readtable p)
                      n))
                  (write obj p))))
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 4)
          "(a #(b (c c) #u8(9 9 9) b) . a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 3)
          "(a #(b (c c) #u8(9 9 9) ...) . a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 2)
          "(a #(b (c c) ...) . a)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 1)
          "(a ...)"
          > (wr '(a #(b (c c) #u8(9 9 9) b) . a) 0)
          "(...)"


 -- procedure: readtable-max-unescaped-char READTABLE
 -- procedure: readtable-max-unescaped-char-set READTABLE NEW-VALUE
     The procedure `readtable-max-unescaped-char' returns the content
     of the `max-unescaped-char' field of READTABLE.  The printer will
     display using an escape sequence any character within symbols,
     strings and character objects greater than `max-unescaped-char'

     The procedure `readtable-max-unescaped-char-set' returns a copy of
     READTABLE where only the `max-unescaped-char' field has been
     changed to NEW-VALUE, which must be a character.

     For example:

          > (define rt (output-port-readtable (repl-output-port)))
          > (readtable-max-unescaped-char rt)
          #\delete
          > (string (integer->char 233))
          "\351"
          > (define (f c)
              (with-output-to-string
               (list readtable: (readtable-max-unescaped-char-set rt c))
               (lambda () (write (string (integer->char 233))))))
          > (f #\delete)
          "\"\\351\""
          > (string-length (f #\delete))
          6
          > (f #\U0010ffff)
          "\"\351\""
          > (string-length (f #\U0010ffff))
          3
          > (output-port-readtable-set!
             (repl-output-port)
             (readtable-max-unescaped-char-set rt #\U0010ffff))
          > (string (integer->char 233))
          "é"


 -- procedure: readtable-start-syntax READTABLE
 -- procedure: readtable-start-syntax-set READTABLE NEW-VALUE
     The procedure `readtable-start-syntax' returns the content of the
     `start-syntax' field of READTABLE.  The reader uses this field to
     determine in which syntax to start parsing the input.  When the
     content of this field is the symbol `six', the reader starts in
     the infix syntax.  Otherwise the reader starts in the prefix
     syntax.

     The procedure `readtable-start-syntax-set' returns a copy of
     READTABLE where only the `start-syntax' field has been changed to
     NEW-VALUE.

     For example:

          > (+ 2 3)
          5
          > (input-port-readtable-set!
             (repl-input-port)
             (readtable-start-syntax-set
               (input-port-readtable (repl-input-port))
               'six))
          > 2+3;
          5
          > exit();



File: gambit-c.info,  Node: Boolean syntax,  Next: Character syntax,  Prev: Readtables,  Up: Lexical syntax and readtables

18.2 Boolean syntax
===================

Booleans are required to be followed by a delimiter (i.e. `#f64()' is
not the boolean `#f' followed by the number `64' and the empty list).


File: gambit-c.info,  Node: Character syntax,  Next: String syntax,  Prev: Boolean syntax,  Up: Lexical syntax and readtables

18.3 Character syntax
=====================

Characters are required to be followed by a delimiter (i.e.
`#\spaceballs' is not the character `#\space' followed by the symbol
`balls').  The lexical syntax of characters is extended to allow the
following:

`#\nul'
     Unicode character 0

`#\alarm'
     Unicode character 7

`#\backspace'
     Unicode character 8

`#\tab'
     Unicode character 9

`#\newline'
     Unicode character 10 (newline character)

`#\linefeed'
     Unicode character 10

`#\vtab'
     Unicode character 11

`#\page'
     Unicode character 12

`#\return'
     Unicode character 13

`#\esc'
     Unicode character 27

`#\space'
     Unicode character 32 (space character)

`#\delete'
     Unicode character 127

`#\xHH'
     character encoded in hexadecimal (>= 1 hexadecimal digit)

`#\uHHHH'
     character encoded in hexadecimal (exactly 4 hexadecimal digits)

`#\UHHHHHHHH'
     character encoded in hexadecimal (exactly 8 hexadecimal digits)


File: gambit-c.info,  Node: String syntax,  Next: Symbol syntax,  Prev: Character syntax,  Up: Lexical syntax and readtables

18.4 String syntax
==================

The lexical syntax of quoted strings is extended to allow the following
escape codes:

`\a'
     Unicode character 7

`\b'
     Unicode character 8

`\t'
     Unicode character 9

`\n'
     Unicode character 10 (newline character)

`\v'
     Unicode character 11

`\f'
     Unicode character 12

`\r'
     Unicode character 13

`\"'
     `"'

`\\'
     `\'

`\|'
     `|'

`\?'
     `?'

`\OOO'
     character encoded in octal (1 to 3 octal digits, first digit must
     be less than 4 when there are 3 octal digits)

`\xHH'
     character encoded in hexadecimal (>= 1 hexadecimal digit)

`\uHHHH'
     character encoded in hexadecimal (exactly 4 hexadecimal digits)

`\UHHHHHHHH'
     character encoded in hexadecimal (exactly 8 hexadecimal digits)

`\<space>'
     Unicode character 32 (space character)

`\<newline><whitespace-except-newline>*'
     This sequence expands to nothing (it is useful for splitting a long
     string literal on multiple lines while respecting proper
     indentation of the source code)

   Gambit also supports a "here string" syntax that is similar to shell
"here documents".  For example:

     > (pretty-print #<<THE-END
     hello
     world
     THE-END
     )
     "hello\nworld"

   The here string starts with the sequence `#<<'.  The part of the
line after the `#<<' up to and including the newline character is the
key. The first line afterward that matches the key marks the end of the
here string.  The string contains all the characters between the start
key and the end key, with the exception of the newline character before
the end key.


File: gambit-c.info,  Node: Symbol syntax,  Next: Keyword syntax,  Prev: String syntax,  Up: Lexical syntax and readtables

18.5 Symbol syntax
==================

The lexical syntax of symbols is extended to allow a leading and
trailing vertical bar (e.g. `|a\|b"c:|').  The symbol's name
corresponds verbatim to the characters between the vertical bars except
for escaped characters.  The same escape sequences as for strings are
permitted except that `"' does not need to be escaped and `|' needs to
be escaped.

   For example:

     > (symbol->string '|a\|b"c:|)
     "a|b\"c:"


File: gambit-c.info,  Node: Keyword syntax,  Next: Box syntax,  Prev: Symbol syntax,  Up: Lexical syntax and readtables

18.6 Keyword syntax
===================

The lexical syntax of keywords is like symbols, but with a colon at the
end (note that this can be changed to a leading colon by setting the
`keywords-allowed?' field of the readtable to the symbol `prefix').  A
colon by itself is not a keyword, it is a symbol.  Vertical bars can be
used like symbols but the colon must be outside the vertical bars.
Note that the string returned by the `keyword->string' procedure does
not include the colon.

   For example:

     > (keyword->string 'foo:)
     "foo"
     > (map keyword? '(|ab()cd:| |ab()cd|: : ||:))
     (#f #t #f #t)


File: gambit-c.info,  Node: Box syntax,  Next: Number syntax,  Prev: Keyword syntax,  Up: Lexical syntax and readtables

18.7 Box syntax
===============

The lexical syntax of boxes is `#&OBJ' where OBJ is the content of the
box.

   For example:

     > (list '#&"hello" '#&123)
     (#&"hello" #&123)
     > (box (box (+ 10 20)))
     #&#&30


File: gambit-c.info,  Node: Number syntax,  Next: Homogeneous vector syntax,  Prev: Box syntax,  Up: Lexical syntax and readtables

18.8 Number syntax
==================

The lexical syntax of the special inexact real numbers is as follows:

`+inf.0'
     positive infinity

`-inf.0'
     negative infinity

`+nan.0'
     "not a number"

`-0.'
     negative zero (`0.' is the positive zero)


File: gambit-c.info,  Node: Homogeneous vector syntax,  Next: Special #! syntax,  Prev: Number syntax,  Up: Lexical syntax and readtables

18.9 Homogeneous vector syntax
==============================

Homogeneous vectors are vectors containing raw numbers of the same type
(signed or unsigned exact integers or inexact reals).  There are 10
types of homogeneous vectors: `s8vector' (vector of 8 bit signed
integers), `u8vector' (vector of 8 bit unsigned integers), `s16vector'
(vector of 16 bit signed integers), `u16vector' (vector of 16 bit
unsigned integers), `s32vector' (vector of 32 bit signed integers),
`u32vector' (vector of 32 bit unsigned integers), `s64vector' (vector
of 64 bit signed integers), `u64vector' (vector of 64 bit unsigned
integers), `f32vector' (vector of 32 bit floating point numbers), and
`f64vector' (vector of 64 bit floating point numbers).

   The external representation of homogeneous vectors is similar to
normal vectors but with the `#(' prefix replaced respectively with
`#s8(', `#u8(', `#s16(', `#u16(', `#s32(', `#u32(', `#s64(', `#u64(',
`#f32(', and `#f64('.

   The elements of the integer homogeneous vectors must be exact
integers fitting in the given precision.  The elements of the floating
point homogeneous vectors must be inexact reals.


File: gambit-c.info,  Node: Special #! syntax,  Next: Multiline comment syntax,  Prev: Homogeneous vector syntax,  Up: Lexical syntax and readtables

18.10 Special `#!' syntax
=========================

The lexical syntax of the special `#!' objects is as follows:

`#!eof'
     end-of-file object

`#!void'
     void object

`#!optional'
     optional object

`#!rest'
     rest object

`#!key'
     key object


File: gambit-c.info,  Node: Multiline comment syntax,  Next: Scheme infix syntax extension,  Prev: Special #! syntax,  Up: Lexical syntax and readtables

18.11 Multiline comment syntax
==============================

Multiline comments are delimited by the tokens `#|' and `|#'.  These
comments can be nested.


File: gambit-c.info,  Node: Scheme infix syntax extension,  Prev: Multiline comment syntax,  Up: Lexical syntax and readtables

18.12 Scheme infix syntax extension
===================================

The reader supports an infix syntax extension which is called SIX
(Scheme Infix eXtension).  This extension is both supported by the
`read' procedure and in program source code.

   The backslash character is a delimiter that marks the beginning of a
single datum expressed in the infix syntax (the details are given
below).  One way to think about it is that the backslash character
escapes the prefix syntax temporarily to use the infix syntax.  For
example a three element list could be written as `(X \Y Z)', the
elements X and Z are expressed using the normal prefix syntax and Y is
expressed using the infix syntax.

   When the reader encounters an infix datum, it constructs a syntax
tree for that particular datum.  Each node of this tree is represented
with a list whose first element is a symbol indicating the type of node.
For example, `(six.identifier abc)' is the representation of the infix
identifier `abc' and `(six.index (six.identifier abc) (six.identifier
i))' is the representation of the infix datum `abc[i];'.

18.12.1 SIX grammar
-------------------

The SIX grammar is given below.  On the left hand side are the
production rules.  On the right hand side is the datum that is
constructed by the reader.  The notation $I denotes the datum that is
constructed by the reader for the Ith part of the production rule.

<infix datum> ::=                           
<stat>                                      $1
<stat> ::=                                  
<if stat>                                   $1
| <for stat>                                $1
| <while stat>                              $1
| <do stat>                                 $1
| <switch stat>                             $1
| <case stat>                               $1
| <break stat>                              $1
| <continue stat>                           $1
| <label stat>                              $1
| <goto stat>                               $1
| <return stat>                             $1
| <expression stat>                         $1
| <procedure definition>                    $1
| <variable definition> `;'                 $1
| <clause stat>                             $1
| <compound stat>                           $1
| `;'                                       `(six.compound)'
<if stat> ::=                               
`if' `(' <pexpr> `)' <stat>                 `(six.if $3 $5)'
| `if' `(' <pexpr> `)' <stat> `else'        `(six.if $3 $5 $7)'
<stat>                                      
<for stat> ::=                              
`for' `(' <stat> `;' <oexpr> `;' <oexpr>    `(six.for $3 $5 $7 $9)'
`)' <stat>                                  
<while stat> ::=                            
`while' `(' <pexpr> `)' <stat>              `(six.while $3 $5)'
<do stat> ::=                               
`do' <stat> `while' `(' <pexpr> `)' `;'     `(six.do-while $2 $5)'
<switch stat> ::=                           
`switch' `(' <pexpr> `)' <stat>             `(six.switch $3 $5)'
<case stat> ::=                             
`case' <expr> `:' <stat>                    `(six.case $2 $4)'
<break stat> ::=                            
`break' `;'                                 `(six.break)'
<continue stat> ::=                         
`continue' `;'                              `(six.continue)'
<label stat> ::=                            
<identifier> `:' <stat>                     `(six.label $1 $3)'
<goto stat> ::=                             
`goto' <expr> `;'                           `(six.goto $2)'
<return stat> ::=                           
`return' `;'                                `(six.return)'
| `return' <expr> `;'                       `(six.return $2)'
<expression stat> ::=                       
<expr> `;'                                  $1
<clause stat> ::=                           
<expr> `.'                                  `(six.clause $1)'
<pexpr> ::=                                 
<procedure definition>                      $1
| <variable definition>                     $1
| <expr>                                    $1
<procedure definition> ::=                  
<type> <id-or-prefix> `(' <parameters> `)'  `(six.define-procedure $2
<body>                                      (six.procedure $1 $4 $6))'
<variable definition> ::=                   
<type> <id-or-prefix> <dimensions> <iexpr>  `(six.define-variable $2 $1
                                            $3 $4)'
<iexpr> ::=                                 
`=' <expr>                                  $2
|                                           `#f'
<dimensions> ::=                            
| `[' <expr> `]' <dimensions>               `($2 . $4)'
|                                           `()'
<oexpr> ::=                                 
<expr>                                      $1
|                                           `#f'
<expr> ::=                                  
<expr18>                                    $1
<expr18> ::=                                
<expr17> `:-' <expr18>                      `(six.x:-y $1 $3)'
| <expr17>                                  $1
<expr17> ::=                                
<expr17> `,' <expr16>                       `(|six.x,y| $1 $3)'
| <expr16>                                  $1
<expr16> ::=                                
<expr15> `:=' <expr16>                      `(six.x:=y $1 $3)'
| <expr15>                                  $1
<expr15> ::=                                
<expr14> `%=' <expr15>                      `(six.x%=y $1 $3)'
| <expr14> `&=' <expr15>                    `(six.x&=y $1 $3)'
| <expr14> `*=' <expr15>                    `(six.x*=y $1 $3)'
| <expr14> `+=' <expr15>                    `(six.x+=y $1 $3)'
| <expr14> `-=' <expr15>                    `(six.x-=y $1 $3)'
| <expr14> `/=' <expr15>                    `(six.x/=y $1 $3)'
| <expr14> `<<=' <expr15>                   `(six.x<<=y $1 $3)'
| <expr14> `=' <expr15>                     `(six.x=y $1 $3)'
| <expr14> `>>=' <expr15>                   `(six.x>>=y $1 $3)'
| <expr14> `^=' <expr15>                    `(six.x^=y $1 $3)'
| <expr14> `|=' <expr15>                    `(|six.x\|=y| $1 $3)'
| <expr14>                                  $1
<expr14> ::=                                
<expr13> `:' <expr14>                       `(six.x:y $1 $3)'
| <expr13>                                  $1
<expr13> ::=                                
<expr12> `?' <expr> `:' <expr13>            `(six.x?y:z $1 $3 $5)'
| <expr12>                                  $1
<expr12> ::=                                
<expr12> `||' <expr11>                      `(|six.x\|\|y| $1 $3)'
| <expr11>                                  $1
<expr11> ::=                                
<expr11> `&&' <expr10>                      `(six.x&&y $1 $3)'
| <expr10>                                  $1
<expr10> ::=                                
<expr10> `|' <expr9>                        `(|six.x\|y| $1 $3)'
| <expr9>                                   $1
<expr9> ::=                                 
<expr9> `^' <expr8>                         `(six.x^y $1 $3)'
| <expr8>                                   $1
<expr8> ::=                                 
<expr8> `&' <expr7>                         `(six.x&y $1 $3)'
| <expr7>                                   $1
<expr7> ::=                                 
<expr7> `!=' <expr6>                        `(six.x!=y $1 $3)'
| <expr7> `==' <expr6>                      `(six.x==y $1 $3)'
| <expr6>                                   $1
<expr6> ::=                                 
<expr6> `<' <expr5>                         `(six.x<y $1 $3)'
| <expr6> `<=' <expr5>                      `(six.x<=y $1 $3)'
| <expr6> `>' <expr5>                       `(six.x>y $1 $3)'
| <expr6> `>=' <expr5>                      `(six.x>=y $1 $3)'
| <expr5>                                   $1
<expr5> ::=                                 
<expr5> `<<' <expr4>                        `(six.x<<y $1 $3)'
| <expr5> `>>' <expr4>                      `(six.x>>y $1 $3)'
| <expr4>                                   $1
<expr4> ::=                                 
<expr4> `+' <expr3>                         `(six.x+y $1 $3)'
| <expr4> `-' <expr3>                       `(six.x-y $1 $3)'
| <expr3>                                   $1
<expr3> ::=                                 
<expr3> `%' <expr2>                         `(six.x%y $1 $3)'
| <expr3> `*' <expr2>                       `(six.x*y $1 $3)'
| <expr3> `/' <expr2>                       `(six.x/y $1 $3)'
| <expr2>                                   $1
<expr2> ::=                                 
`&' <expr2>                                 `(six.&x $2)'
| `+' <expr2>                               `(six.+x $2)'
| `-' <expr2>                               `(six.-x $2)'
| `*' <expr2>                               `(six.*x $2)'
| `!' <expr2>                               `(six.!x $2)'
| `!'                                       `(six.!)'
| `++' <expr2>                              `(six.++x $2)'
| `--' <expr2>                              `(six.--x $2)'
| `~' <expr2>                               `(six.~x $2)'
| `new' <id-or-prefix> `(' <arguments> `)'  `(six.new $2 . $4)'
| <expr1>                                   $1
<expr1> ::=                                 
<expr1> `++'                                `(six.x++ $1)'
| <expr1> `--'                              `(six.x-- $1)'
| <expr1> `(' <arguments> `)'               `(six.call $1 . $3)'
| <expr1> `[' <expr> `]'                    `(six.index $1 $3)'
| <expr1> `->' <id-or-prefix>               `(six.arrow $1 $3)'
| <expr1> `.' <id-or-prefix>                `(six.dot $1 $3)'
| <expr0>                                   $1
<expr0> ::=                                 
<id-or-prefix>                              $1
| <string>                                  `(six.literal $1)'
| <char>                                    `(six.literal $1)'
| <number>                                  `(six.literal $1)'
| `(' <expr> `)'                            $2
| `(' <block stat> `)'                      $2
| <datum-starting-with-#-or-backquote>      `(six.prefix $1)'
| `[' <elements> `]'                        $2
| <type> `(' <parameters> `)' <body>        `(six.procedure $1 $3 $5)'
<block stat> ::=                            
`{' <stat list> `}'                         `(six.compound . $2)'
<body> ::=                                  
`{' <stat list> `}'                         `(six.procedure-body . $2)'
<stat list> ::=                             
<stat> <stat list>                          `($1 . $2)'
|                                           `()'
<parameters> ::=                            
<nonempty parameters>                       $1
|                                           `()'
<nonempty parameters> ::=                   
<parameter> `,' <nonempty parameters>       `($1 . $3)'
| <parameter>                               `($1)'
<parameter> ::=                             
<type> <id-or-prefix>                       `($2 $1)'
<arguments> ::=                             
<nonempty arguments>                        $1
|                                           `()'
<nonempty arguments> ::=                    
<expr> `,' <nonempty arguments>             `($1 . $3)'
| <expr>                                    `($1)'
<elements> ::=                              
<nonempty elements>                         $1
|                                           `(six.null)'
<nonempty elements> ::=                     
<expr>                                      `(six.list $1 (six.null))'
| <expr> `,' <nonempty elements>            `(six.list $1 $3)'
| <expr> `|' <expr>                         `(six.cons $1 $3)'
<id-or-prefix> ::=                          
<identifier>                                `(six.identifier $1)'
| `\' <datum>                               `(six.prefix $2)'
<type> ::=                                  
`int'                                       `int'
| `char'                                    `char'
| `bool'                                    `bool'
| `void'                                    `void'
| `float'                                   `float'
| `double'                                  `double'
| `obj'                                     `obj'

18.12.2 SIX semantics
---------------------

The semantics of SIX depends on the definition of the `six.XXX'
identifiers (as functions and macros).  Many of these identifiers are
predefined macros which give SIX a semantics that is close to C's.  The
user may override these definitions to change the semantics either
globally or locally.  For example, `six.x^y' is a predefined macro that
expands `(six.x^y x y)' into `(bitwise-xor x y)'.  If the user prefers
the `^' operator to express exponentiation in a specific function, then
in that function `six.x^y' can be redefined as a macro that expands
`(six.x^y x y)' into `(expt x y)'.  Note that the associativity and
precedence of operators cannot be changed as that is a syntactic issue.

   Note that the following identifiers are not predefined, and
consequently they do not have a predefined semantics: `six.label',
`six.goto', `six.switch', `six.case', `six.break', `six.continue',
`six.return', `six.clause', `six.x:-y', and `six.!'.

   The following is an example showing some of the predefined semantics
of SIX:

     > (list (+ 1 2) \3+4; (+ 5 6))
     (3 7 11)
     > \[ 1+2, \(+ 3 4), 5+6 ];
     (3 7 11)
     > (map (lambda (x) \(x*x-1)/log(x+1);) '(1 2 3 4))
     (0 2.730717679880512 5.7707801635558535 9.320024018394177)
     > \obj n = expt(10,5);
     > n
     100000
     > \obj t[3][10] = 88;
     > \t[0][9] = t[2][1] = 11;
     11
     > t
     #(#(88 88 88 88 88 88 88 88 88 11)
       #(88 88 88 88 88 88 88 88 88 88)
       #(88 11 88 88 88 88 88 88 88 88))
     > \obj radix = new parameter (10);
     > \radix(2);
     > \radix();
     2
     > \for (int i=0; i<5; i++) pp(1<<i*8);
     1
     256
     65536
     16777216
     4294967296
     > \obj \make-adder (obj x) { obj (obj y) { x+y; }; }
     > \map (new adder (100), [1,2,3,4]);
     (101 102 103 104)
     > (map (make-adder 100) (list 1 2 3 4))
     (101 102 103 104)


File: gambit-c.info,  Node: C-interface,  Next: System limitations,  Prev: Lexical syntax and readtables,  Up: Top

19 C-interface
**************

The Gambit Scheme system offers a mechanism for interfacing Scheme code
and C code called the "C-interface".  A Scheme program indicates which
C functions it needs to have access to and which Scheme procedures can
be called from C, and the C interface automatically constructs the
corresponding Scheme procedures and C functions.  The conversions needed
to transform data from the Scheme representation to the C representation
(and back), are generated automatically in accordance with the argument
and result types of the C function or Scheme procedure.

   The C-interface places some restrictions on the types of data that
can be exchanged between C and Scheme.  The mapping of data types
between C and Scheme is discussed in the next section.  The remaining
sections of this chapter describe each special form of the C-interface.

* Menu:

* mapping of types::                The mapping of types between C and Scheme
* c-declare::                       The `c-declare' special form
* c-initialize::                    The `c-initialize' special form
* c-lambda::                        The `c-lambda' special form
* c-define::                        The `c-define' special form
* c-define-type::                   The `c-define-type' special form
* continuations::                   Continuations and the C-interface


File: gambit-c.info,  Node: mapping of types,  Next: c-declare,  Prev: C-interface,  Up: C-interface

19.1 The mapping of types between C and Scheme
==============================================

Scheme and C do not provide the same set of built-in data types so it is
important to understand which Scheme type is compatible with which C
type and how values get mapped from one environment to the other.  To
improve compatibility a new type is added to Scheme, the `foreign'
object type, and the following data types are added to C:

`scheme-object'
     denotes the universal type of Scheme objects (type `___SCMOBJ'
     defined in `gambit.h')

`bool'
     denotes the C++ `bool' type or the C `int' type (type `___BOOL'
     defined in `gambit.h')

`int8'
     8 bit signed integer (type `___S8' defined in `gambit.h')

`unsigned-int8'
     8 bit unsigned integer (type `___U8' defined in `gambit.h')

`int16'
     16 bit signed integer (type `___S16' defined in `gambit.h')

`unsigned-int16'
     16 bit unsigned integer (type `___U16' defined in `gambit.h')

`int32'
     32 bit signed integer (type `___S32' defined in `gambit.h')

`unsigned-int32'
     32 bit unsigned integer (type `___U32' defined in `gambit.h')

`int64'
     64 bit signed integer (type `___S64' defined in `gambit.h')

`unsigned-int64'
     64 bit unsigned integer (type `___U64' defined in `gambit.h')

`float32'
     32 bit floating point number (type `___F32' defined in `gambit.h')

`float64'
     64 bit floating point number (type `___F64' defined in `gambit.h')

`ISO-8859-1'
     denotes ISO-8859-1 encoded characters (8 bit unsigned integer,
     type `___ISO_8859_1' defined in `gambit.h')

`UCS-2'
     denotes UCS-2 encoded characters (16 bit unsigned integer, type
     `___UCS_2' defined in `gambit.h')

`UCS-4'
     denotes UCS-4 encoded characters (32 bit unsigned integer, type
     `___UCS_4' defined in `gambit.h')

`char-string'
     denotes the C `char*' type when used as a null terminated string

`nonnull-char-string'
     denotes the nonnull C `char*' type when used as a null terminated
     string

`nonnull-char-string-list'
     denotes an array of nonnull C `char*' terminated with a null
     pointer

`ISO-8859-1-string'
     denotes ISO-8859-1 encoded strings (null terminated string of 8
     bit unsigned integers, i.e. `___ISO_8859_1*')

`nonnull-ISO-8859-1-string'
     denotes nonnull ISO-8859-1 encoded strings (null terminated string
     of 8 bit unsigned integers, i.e. `___ISO_8859_1*')

`nonnull-ISO-8859-1-stringlist'
     denotes an array of nonnull ISO-8859-1 encoded strings terminated
     with a null pointer

`UTF-8-string'
     denotes UTF-8 encoded strings (null terminated string of `char',
     i.e. `char*')

`nonnull-UTF-8-string'
     denotes nonnull UTF-8 encoded strings (null terminated string of
     `char', i.e. `char*')

`nonnull-UTF-8-string-list'
     denotes an array of nonnull UTF-8 encoded strings terminated with
     a null pointer

`UTF-16-string'
     denotes UTF-16 encoded strings (null terminated string of `char',
     i.e. `char*')

`nonnull-UTF-16-string'
     denotes nonnull UTF-16 encoded strings (null terminated string of
     `char', i.e. `char*')

`nonnull-UTF-16-string-list'
     denotes an array of nonnull UTF-16 encoded strings terminated with
     a null pointer

`UCS-2-string'
     denotes UCS-2 encoded strings (null terminated string of 16 bit
     unsigned integers, i.e. `___UCS_2*')

`nonnull-UCS-2-string'
     denotes nonnull UCS-2 encoded strings (null terminated string of
     16 bit unsigned integers, i.e. `___UCS_2*')

`nonnull-UCS-2-string-list'
     denotes an array of nonnull UCS-2 encoded strings terminated with
     a null pointer

`UCS-4-string'
     denotes UCS-4 encoded strings (null terminated string of 32 bit
     unsigned integers, i.e. `___UCS_4*')

`nonnull-UCS-4-string'
     denotes nonnull UCS-4 encoded strings (null terminated string of
     32 bit unsigned integers, i.e. `___UCS_4*')

`nonnull-UCS-4-string-list'
     denotes an array of nonnull UCS-4 encoded strings terminated with
     a null pointer

`wchar_t-string'
     denotes `wchar_t' encoded strings (null terminated string of
     `wchar_t', i.e. `wchar_t*')

`nonnull-wchar_t-string'
     denotes nonnull `wchar_t' encoded strings (null terminated string
     of `wchar_t', i.e. `wchar_t*')

`nonnull-wchar_t-string-list'
     denotes an array of nonnull `wchar_t' encoded strings terminated
     with a null pointer

   To specify a particular C type inside the `c-lambda', `c-define' and
`c-define-type' forms, the following "Scheme notation" is used:

`Scheme notation'
     C type

`void'
     `void'

`bool'
     `bool'

`char'
     `char'  (may be signed or unsigned depending on the C compiler)

`signed-char'
     `signed char'

`unsigned-char'
     `unsigned char'

`ISO-8859-1'
     `ISO-8859-1'

`UCS-2'
     `UCS-2'

`UCS-4'
     `UCS-4'

`wchar_t'
     `wchar_t'

`short'
     `short'

`unsigned-short'
     `unsigned short'

`int'
     `int'

`unsigned-int'
     `unsigned int'

`long'
     `long'

`unsigned-long'
     `unsigned long'

`long-long'
     `long long'

`unsigned-long-long'
     `unsigned long long'

`float'
     `float'

`double'
     `double'

`int8'
     `int8'

`unsigned-int8'
     `unsigned-int8'

`int16'
     `int16'

`unsigned-int16'
     `unsigned-int16'

`int32'
     `int32'

`unsigned-int32'
     `unsigned-int32'

`int64'
     `int64'

`unsigned-int64'
     `unsigned-int64'

`float32'
     `float32'

`float64'
     `float64'

`(struct "C-STRUCT-ID" [TAGS [RELEASE-FUNCTION]])'
     `struct C-STRUCT-ID'  (where C-STRUCT-ID is the name of a C
     structure; see below for the meaning of TAGS and RELEASE-FUNCTION)

`(union "C-UNION-ID" [TAGS [RELEASE-FUNCTION]])'
     `union C-UNION-ID'  (where C-UNION-ID is the name of a C union;
     see below for the meaning of TAGS and RELEASE-FUNCTION)

`(type "C-TYPE-ID" [TAGS [RELEASE-FUNCTION]])'
     `C-TYPE-ID'  (where C-TYPE-ID is an identifier naming a C type;
     see below for the meaning of TAGS and RELEASE-FUNCTION)

`(pointer TYPE [TAGS [RELEASE-FUNCTION]])'
     `T*'  (where T is the C equivalent of TYPE which must be the
     Scheme notation of a C type; see below for the meaning of TAGS and
     RELEASE-FUNCTION)

`(nonnull-pointer TYPE [TAGS [RELEASE-FUNCTION]])'
     same as `(pointer TYPE [TAGS [RELEASE-FUNCTION]])' except the
     `NULL' pointer is not allowed

`(function (TYPE1...) RESULT-TYPE)'
     function with the given argument types and result type

`(nonnull-function (TYPE1...) RESULT-TYPE)'
     same as `(function (TYPE1...) RESULT-TYPE)' except the `NULL'
     pointer is not allowed

`char-string'
     `char-string'

`nonnull-char-string'
     `nonnull-char-string'

`nonnull-char-string-list'
     `nonnull-char-string-list'

`ISO-8859-1-string'
     `ISO-8859-1-string'

`nonnull-ISO-8859-1-string'
     `nonnull-ISO-8859-1-string'

`nonnull-ISO-8859-1-string-list'
     `nonnull-ISO-8859-1-string-list'

`UTF-8-string'
     `UTF-8-string'

`nonnull-UTF-8-string'
     `nonnull-UTF-8-string'

`nonnull-UTF-8-string-list'
     `nonnull-UTF-8-string-list'

`UTF-16-string'
     `UTF-16-string'

`nonnull-UTF-16-string'
     `nonnull-UTF-16-string'

`nonnull-UTF-16-string-list'
     `nonnull-UTF-16-string-list'

`UCS-2-string'
     `UCS-2-string'

`nonnull-UCS-2-string'
     `nonnull-UCS-2-string'

`nonnull-UCS-2-string-list'
     `nonnull-UCS-2-string-list'

`UCS-4-string'
     `UCS-4-string'

`nonnull-UCS-4-string'
     `nonnull-UCS-4-string'

`nonnull-UCS-4-string-list'
     `nonnull-UCS-4-string-list'

`wchar_t-string'
     `wchar_t-string'

`nonnull-wchar_t-string'
     `nonnull-wchar_t-string'

`nonnull-wchar_t-string-list'
     `nonnull-wchar_t-string-list'

`scheme-object'
     `scheme-object'

`NAME'
     appropriate translation of NAME (where NAME is a C type defined
     with `c-define-type')

`"C-TYPE-ID"'
     C-TYPE-ID (this form is equivalent to `(type "C-TYPE-ID")')

   The `struct', `union', `type', `pointer' and `nonnull-pointer' types
are "foreign types" and they are represented on the Scheme side as
"foreign objects".  A foreign object is internally represented as a
pointer.  This internal pointer is identical to the C pointer being
represented in the case of the `pointer' and `nonnull-pointer' types.

   In the case of the `struct', `union' and `type' types, the internal
pointer points to a copy of the C data type being represented.  When an
instance of one of these types is converted from C to Scheme, a block
of memory is allocated from the C heap and initialized with the
instance and then a foreign object is allocated from the Scheme heap
and initialized with the pointer to this copy.  This approach may
appear overly complex, but it allows the conversion of C++ classes that
do not have a zero parameter constructor or an assignment method (i.e.
when compiling with a C++ compiler an instance is copied using `new
TYPE (INSTANCE)', which calls the copy-constructor of TYPE if it is a
class; TYPE's assignment operator is never used).  Conversion from
Scheme to C simply dereferences the internal pointer (no allocation
from the C heap is performed).  Deallocation of the copy on the C heap
is under the control of the release function attached to the foreign
object (see below).

   The optional TAGS field of foreign type specifications is used for
type checking on the Scheme side.  The TAGS field must be `#f', a
symbol or a non-empty list of symbols.  When it is not specified the
TAGS field defaults to a symbol whose name, as returned by
`symbol->string', is the C type declaration for that type.  For example
the symbol `char**' is the default for the type `(pointer (pointer
char))'.  A TAGS field that is a single symbol is equivalent to a list
containing only that symbol.  The first symbol in the list of tags is
the primary tag.  For example the primary tag of the type `(pointer
char)' is `char*' and the primary tag of the type `(pointer char (foo
bar))' is `foo'.

   Type compatibility between two foreign types depends on their tags.
An instance of a foreign type T can be used where a foreign type E is
expected if and only if

   * T's TAGS field is `#f', or

   * E's TAGS field is `#f', or

   * T's primary tag is a member of E's tags.


   For the safest code a TAGS field of `#f' should be used sparingly,
as it completely bypasses type checking.  The external representation
of Scheme foreign objects (used by the `write' procedure) contains the
primary tag (if the TAGS field is not `#f'), and the hexadecimal
address denoted by the internal pointer, for example `#<char** #2
0x2AAC535C>'.  Note that the hexadecimal address is in C notation,
which can be easily transferred to a C debugger with a "cut-and-paste".

   A RELEASE-FUNCTION can also be specified within a foreign type
specification.  The RELEASE-FUNCTION must be `#f' or a string naming a
C function with a single parameter of type `void*' (in which the
internal pointer is passed) and with a result of type `___SCMOBJ' (for
returning an error code).  When the RELEASE-FUNCTION is not specified
or is `#f' a default function is constructed by the C-interface.  This
default function does nothing in the case of the `pointer' and
`nonnull-pointer' types (deallocation is not the responsibility of the
C-interface) and returns the fixnum `___FIX(___NO_ERR)' to indicate no
error.  In the case of the `struct', `union' and `type' types, the
default function reclaims the copy on the C heap referenced by the
internal pointer (when using a C++ compiler this is done using `delete
(TYPE*)INTERNAL-POINTER', which calls the destructor of TYPE if it is a
class) and returns `___FIX(___NO_ERR)'.  In many situations the default
RELEASE-FUNCTION will perform the appropriate cleanup for the foreign
type.  However, in certain cases special operations (such as
decrementing a reference count, removing the object from a table, etc)
must be performed.  For such cases a user supplied RELEASE-FUNCTION is
needed.

   The RELEASE-FUNCTION is invoked at most once for any foreign object.
After the RELEASE-FUNCTION is invoked, the foreign object is considered
"released" and can no longer be used in a foreign type conversion.
When the garbage collector detects that a foreign object is no longer
reachable by the program, it will invoke the RELEASE-FUNCTION if the
foreign object is not yet released.  When there is a need to release
the foreign object promptly, the program can explicitly call
`(foreign-release! OBJ)' which invokes the RELEASE-FUNCTION if the
foreign object is not yet released, and does nothing otherwise.  The
call `(foreign-released? OBJ)' returns a boolean indicating whether the
foreign object OBJ has been released yet or not.  The call
`(foreign-address OBJ)' returns the address denoted by the internal
pointer of foreign object OBJ or 0 if it has been released.  The call
`(foreign? OBJ)' tests that OBJ is a foreign object.  Finally the call
`(foreign-tags OBJ)' returns the list of tags of foreign object OBJ, or
`#f'.

   The following table gives the C types to which each Scheme type can
be converted:

Scheme type
     Allowed target C types

boolean `#f'
     `scheme-object'; `bool'; `pointer'; `function'; `char-string';
     `ISO-8859-1-string'; `UTF-8-string'; `UTF-16-string';
     `UCS-2-string'; `UCS-4-string'; `wchar_t-string'

boolean `#t'
     `scheme-object'; `bool'

character
     `scheme-object'; `bool'; [`[un]signed'] `char'; `ISO-8859-1';
     `UCS-2'; `UCS-4'; `wchar_t'

exact integer
     `scheme-object'; `bool'; [`unsigned-']
     `int8'/`int16'/`int32'/`int64'; [`unsigned'] `short'/`int'/`long'

inexact real
     `scheme-object'; `bool'; `float'; `double'; `float32'; `float64'

string
     `scheme-object'; `bool'; `char-string'; `nonnull-char-string';
     `ISO-8859-1-string'; `nonnull-ISO-8859-1-string'; `UTF-8-string';
     `nonnull-UTF-8-string'; `UTF-16-string'; `nonnull-UTF-16-string';
     `UCS-2-string'; `nonnull-UCS-2-string'; `UCS-4-string';
     `nonnull-UCS-4-string'; `wchar_t-string'; `nonnull-wchar_t-string'

foreign object
     `scheme-object'; `bool';
     `struct'/`union'/`type'/`pointer'/`nonnull-pointer' with the
     appropriate tags

vector
     `scheme-object'; `bool'

symbol
     `scheme-object'; `bool'

procedure
     `scheme-object'; `bool'; `function'; `nonnull-function'

other objects
     `scheme-object'; `bool'

   The following table gives the Scheme types to which each C type will
be converted:

C type
     Resulting Scheme type

scheme-object
     the Scheme object encoded

bool
     boolean

[`[un]signed'] `char'; `ISO-8859-1'; `UCS-2'; `UCS-4'; `wchar_t'
     character

[`unsigned-'] `int8'/`int16'/`int32'/`int64'; [`unsigned'] `short'/`int'/`long'
     exact integer

`float'; `double'; `float32'; `float64'
     inexact real

`char-string'; `ISO-8859-1-string'; `UTF-8-string'; `UTF-16-string'; `UCS-2-string'; `UCS-4-string'; `wchar_t-string'
     string or `#f' if it is equal to `NULL'

`nonnull-char-string'; `nonnull-ISO-8859-1-string'; `nonnull-UTF-8-string'; `nonnull-UTF-16-string'; `nonnull-UCS-2-string'; `nonnull-UCS-4-string'; `nonnull-wchar_t-string'
     string

`struct'/`union'/`type'/`pointer'/`nonnull-pointer'
     foreign object with the appropriate tags or `#f' in the case of a
     `pointer' equal to `NULL'

`function'
     procedure or `#f' if it is equal to `NULL'

`nonnull-function'
     procedure

`void'
     void object

   All Scheme types are compatible with the C types `scheme-object' and
`bool'.  Conversion to and from the C type `scheme-object' is the
identity function on the object encoding.  This provides a low-level
mechanism for accessing Scheme's object representation from C (with the
help of the macros in the `gambit.h' header file).  When a C `bool'
type is expected, an extended Scheme boolean can be passed (`#f' is
converted to 0 and all other values are converted to 1).

   The Scheme boolean `#f' can be passed to the C environment where a
`char-string', `ISO-8859-1-string', `UTF-8-string', `UTF-16-string',
`UCS-2-string', `UCS-4-string', `wchar_t-string', `pointer' or
`function' type is expected.  In this case, `#f' is converted to the
`NULL' pointer.  C `bool's are extended booleans so any value different
from 0 represents true.  Thus, a C `bool' passed to the Scheme
environment is mapped as follows: 0 to `#f' and all other values to
`#t'.

   A Scheme character passed to the C environment where any C character
type is expected is converted to the corresponding character in the C
environment.  An error is signaled if the Scheme character does not fit
in the C character.  Any C character type passed to Scheme is converted
to the corresponding Scheme character.  An error is signaled if the C
character does not fit in the Scheme character.

   A Scheme exact integer passed to the C environment where a C integer
type (other than `char') is expected is converted to the corresponding
integral value.  An error is signaled if the value falls outside of the
range representable by that integral type.  C integer values passed to
the Scheme environment are mapped to the same Scheme exact integer.  If
the value is outside the fixnum range, a bignum is created.

   A Scheme inexact real passed to the C environment is converted to the
corresponding `float', `double', `float32' or `float64' value.  C
`float', `double', `float32' and `float64' values passed to the Scheme
environment are mapped to the closest Scheme inexact real.

   Scheme's rational numbers and complex numbers are not compatible with
any C numeric type.

   A Scheme string passed to the C environment where any C string type
is expected is converted to a null terminated string using the
appropriate encoding.  The C string is a fresh copy of the Scheme
string.  If the C string was created for an argument of a `c-lambda',
the C string will be reclaimed when the `c-lambda' returns.  If the C
string was created for returning the result of a `c-define' to C, the
caller is responsible for reclaiming the C string with a call to the
`___release_string' function (see below for an example).  Any C string
type passed to the Scheme environment causes the creation of a fresh
Scheme string containing a copy of the C string (unless the C string is
equal to `NULL', in which case it is converted to `#f').

   A foreign type passed to the Scheme environment causes the creation
and initialization of a Scheme foreign object with the appropriate tags
(except for the case of a `pointer' equal to `NULL' which is converted
to `#f').  A Scheme foreign object can be passed where a foreign type
is expected, on the condition that the tags are compatible and the
Scheme foreign object is not yet released.  The value `#f' is also
acceptable for a `pointer' type, and is converted to `NULL'.

   Scheme procedures defined with the `c-define' special form can be
passed where the `function' and `nonnull-function' types are expected.
The value `#f' is also acceptable for a `function' type, and is
converted to `NULL'.  No other Scheme procedures are acceptable.
Conversion from the `function' and `nonnull-function' types to Scheme
procedures is not currently implemented.


File: gambit-c.info,  Node: c-declare,  Next: c-initialize,  Prev: mapping of types,  Up: C-interface

19.2 The `c-declare' special form
=================================

Synopsis:

     (c-declare c-declaration)

   Initially, the C file produced by `gsc' contains only an `#include'
of `gambit.h'.  This header file provides a number of macro and
procedure declarations to access the Scheme object representation.  The
special form `c-declare' adds c-declaration (which must be a string
containing the C declarations) to the C file.  This string is copied to
the C file on a new line so it can start with preprocessor directives.
All types of C declarations are allowed (including type declarations,
variable declarations, function declarations, `#include' directives,
`#define's, and so on).  These declarations are visible to subsequent
`c-declare's, `c-initialize's, and `c-lambda's, and `c-define's in the
same module.  The most common use of this special form is to declare
the external functions that are referenced in `c-lambda' special forms.
Such functions must either be declared explicitly or by including a
header file which contains the appropriate C declarations.

   The `c-declare' special form does not return a value.  It can only
appear at top level.

   For example:

     (c-declare #<<c-declare-end

     #include <stdio.h>

     extern char *getlogin ();

     #ifdef sparc
     char *host = "sparc";
     #else
     char *host = "unknown";
     #endif

     FILE *tfile;

     c-declare-end
     )


File: gambit-c.info,  Node: c-initialize,  Next: c-lambda,  Prev: c-declare,  Up: C-interface

19.3 The `c-initialize' special form
====================================

Synopsis:

     (c-initialize c-code)

   Just after the program is loaded and before control is passed to the
Scheme code, each C file is initialized by calling its associated
initialization function.  The body of this function is normally empty
but it can be extended by using the `c-initialize' form.  Each
occurence of the `c-initialize' form adds code to the body of the
initialization function in the order of appearance in the source file.
c-code must be a string containing the C code to execute.  This string
is copied to the C file on a new line so it can start with preprocessor
directives.

   The `c-initialize' special form does not return a value.  It can
only appear at top level.

   For example:

     (c-initialize "tfile = tmpfile ();")


File: gambit-c.info,  Node: c-lambda,  Next: c-define,  Prev: c-initialize,  Up: C-interface

19.4 The `c-lambda' special form
================================

Synopsis:

     (c-lambda (type1...) result-type c-name-or-code)

   The `c-lambda' special form makes it possible to create a Scheme
procedure that will act as a representative of some C function or C code
sequence.  The first subform is a list containing the type of each
argument.  The type of the function's result is given next.  Finally,
the last subform is a string that either contains the name of the C
function to call or some sequence of C code to execute.  Variadic C
functions are not supported.  The resulting Scheme procedure takes
exactly the number of arguments specified and delivers them in the same
order to the C function.  When the Scheme procedure is called, the
arguments will be converted to their C representation and then the C
function will be called.  The result returned by the C function will be
converted to its Scheme representation and this value will be returned
from the Scheme procedure call.  An error will be signaled if some
conversion is not possible.  The temporary memory allocated from the C
heap for the conversion of the arguments and result will be reclaimed
whether there is an error or not.

   When c-name-or-code is not a valid C identifier, it is treated as an
arbitrary piece of C code.  Within the C code the variables `___arg1',
`___arg2', etc. can be referenced to access the converted arguments.
Similarly, the result to be returned from the call should be assigned
to the variable `___result' except when the result is of type `struct',
`union', `type', `pointer', `nonnull-pointer', `function' or
`nonnull-function' in which case a pointer must be assigned to the
variable `___result_voidstar' which is of type `void*'.  For results of
type `pointer', `nonnull-pointer', `function' and `nonnull-function',
the value assigned to the variable `___result_voidstar' must be the
pointer or function cast to `void*'.  For results of type `struct',
`union', and `type', the value assigned to the variable
`___result_voidstar' must be a pointer to a memory allocated block
containing a copy of the result.  Note that this block will be
reclaimed by the RELEASE-FUNCTION associated with the type.  If no
result needs to be returned, the result-type should be `void' and no
assignment to the variable `___result' or `___result_voidstar' should
take place.  Note that the C code should not contain `return'
statements as this is meaningless.  Control must always fall off the
end of the C code.  The C code is copied to the C file on a new line so
it can start with preprocessor directives.  Moreover the C code is
always placed at the head of a compound statement whose lifetime
encloses the C to Scheme conversion of the result.  Consequently,
temporary storage (strings in particular) declared at the head of the C
code can be returned by assigning them to `___result' or
`___result_voidstar'.  In the c-name-or-code, the macro `___AT_END' may
be defined as the piece of C code to execute before control is returned
to Scheme but after the result is converted to its Scheme
representation.  This is mainly useful to deallocate temporary storage
contained in the result.

   When passed to the Scheme environment, the C `void' type is
converted to the void object.

   For example:

     (define fopen
       (c-lambda (nonnull-char-string nonnull-char-string)
                 (pointer "FILE")
        "fopen"))

     (define fgetc
       (c-lambda ((pointer "FILE"))
                 int
        "fgetc"))

     (let ((f (fopen "datafile" "r")))
       (if f (write (fgetc f))))

     (define char-code
       (c-lambda (char) int "___result = ___arg1;"))

     (define host
       ((c-lambda () nonnull-char-string "___result = host;")))

     (define stdin
       ((c-lambda () (pointer "FILE") "___result_voidstar = stdin;")))

     ((c-lambda () void
     #<<c-lambda-end
       printf( "hello\n" );
       printf( "world\n" );
     c-lambda-end
     ))

     (define pack-1-char
       (c-lambda (char)
                 nonnull-char-string
     #<<c-lambda-end
        ___result = malloc (2);
        if (___result != NULL) { ___result[0] = ___arg1; ___result[1] = 0; }
        #define ___AT_END if (___result != NULL) free (___result);
     c-lambda-end
     ))

     (define pack-2-chars
       (c-lambda (char char)
                 nonnull-char-string
     #<<c-lambda-end
        char s[3];
        s[0] = ___arg1;
        s[1] = ___arg2;
        s[2] = 0;
        ___result = s;
     c-lambda-end
     ))


File: gambit-c.info,  Node: c-define,  Next: c-define-type,  Prev: c-lambda,  Up: C-interface

19.5 The `c-define' special form
================================

Synopsis:

     (c-define (variable define-formals) (type1...) result-type c-name scope
       body)

   The `c-define' special form makes it possible to create a C function
that will act as a representative of some Scheme procedure.  A C
function named c-name as well as a Scheme procedure bound to the
variable variable are defined.  The parameters of the Scheme procedure
are define-formals and its body is at the end of the form.  The type of
each argument of the C function, its result type and c-name (which must
be a string) are specified after the parameter specification of the
Scheme procedure.  When the C function c-name is called from C, its
arguments are converted to their Scheme representation and passed to
the Scheme procedure.  The result of the Scheme procedure is then
converted to its C representation and the C function c-name returns it
to its caller.

   The scope of the C function can be changed with the scope parameter,
which must be a string.  This string is placed immediately before the
declaration of the C function.  So if scope is the string `"static"',
the scope of c-name is local to the module it is in, whereas if scope
is the empty string, c-name is visible from other modules.

   The `c-define' special form does not return a value.  It can only
appear at top level.

   For example:

     (c-define (proc x #!optional (y x) #!rest z) (int int char float) int "f" ""
       (write (cons x (cons y z)))
       (newline)
       (+ x y))

     (proc 1 2 #\x 1.5) => 3 and prints (1 2 #\x 1.5)
     (proc 1)           => 2 and prints (1 1)

     ; if f is called from C with the call  f (1, 2, 'x', 1.5)
     ; the value 3 is returned and (1 2 #\x 1.5) is printed.
     ; f has to be called with 4 arguments.

   The `c-define' special form is particularly useful when the driving
part of an application is written in C and Scheme procedures are called
directly from C.  The Scheme part of the application is in a sense a
"server" that is providing services to the C part.  The Scheme
procedures that are to be called from C need to be defined using the
`c-define' special form.  Before it can be used, the Scheme part must
be initialized with a call to the function `___setup'.  Before the
program terminates, it must call the function `___cleanup' so that the
Scheme part may do final cleanup.  A sample application is given in the
file `tests/server.scm'.


File: gambit-c.info,  Node: c-define-type,  Next: continuations,  Prev: c-define,  Up: C-interface

19.6 The `c-define-type' special form
=====================================

Synopsis:

     (c-define-type name type [c-to-scheme scheme-to-c [cleanup]])

   This form associates the type identifier name to the C type type.
The name must not clash with predefined types (e.g. `char-string',
`ISO-8859-1', etc.) or with types previously defined with
`c-define-type' in the same file.  The `c-define-type' special form
does not return a value.  It can only appear at top level.

   If only the two parameters name and type are supplied then after
this definition, the use of name in a type specification is synonymous
to type.

   For example:

     (c-define-type FILE "FILE")
     (c-define-type FILE* (pointer FILE))
     (c-define-type time-struct-ptr (pointer (struct "tms")))
     (define fopen (c-lambda (char-string char-string) FILE* "fopen"))
     (define fgetc (c-lambda (FILE*) int "fgetc"))

   Note that identifiers are not case-sensitive in standard Scheme but
it is good programming practice to use a name with the same case as in
C.

   If four or more parameters are supplied, then type must be a string
naming the C type, c-to-scheme and scheme-to-c must be strings
suffixing the C macros that convert data of that type between C and
Scheme.  If cleanup is supplied it must be a boolean indicating whether
it is necessary to perform a cleanup operation (such as freeing memory)
when data of that type is converted from Scheme to C (it defaults to
`#t').  The cleanup information is used when the C stack is unwound due
to a continuation invocation (see *note continuations::).  Although it
is safe to always specify `#t', it is more efficient in time and space
to specify `#f' because the unwinding mechanism can skip C-interface
frames which only contain conversions of data types requiring no
cleanup.  Two pairs of C macros need to be defined for conversions
performed by `c-lambda' forms and two pairs for conversions performed
by `c-define' forms:

     ___BEGIN_CFUN_scheme-to-c(___SCMOBJ, type, int)
     ___END_CFUN_scheme-to-c(___SCMOBJ, type, int)

     ___BEGIN_CFUN_c-to-scheme(type, ___SCMOBJ)
     ___END_CFUN_c-to-scheme(type, ___SCMOBJ)

     ___BEGIN_SFUN_c-to-scheme(type, ___SCMOBJ, int)
     ___END_SFUN_c-to-scheme(type, ___SCMOBJ, int)

     ___BEGIN_SFUN_scheme-to-c(___SCMOBJ, type)
     ___END_SFUN_scheme-to-c(___SCMOBJ, type)

   The macros prefixed with `___BEGIN' perform the conversion and those
prefixed with `___END' perform any cleanup necessary (such as freeing
memory temporarily allocated for the conversion).  The macro
`___END_CFUN_scheme-to-c' must free the result of the conversion if it
is memory allocated, and `___END_SFUN_scheme-to-c' must not (i.e. it is
the responsibility of the caller to free the result).

   The first parameter of these macros is the C variable that contains
the value to be converted, and the second parameter is the C variable in
which to store the converted value.  The third parameter, when present,
is the index (starting at 1) of the parameter of the `c-lambda' or
`c-define' form that is being converted (this is useful for reporting
precise error information when a conversion is impossible).

   To allow for type checking, the first three `___BEGIN' macros must
expand to an unterminated compound statement prefixed by an `if',
conditional on the absence of type check error:

     if ((___err = CONVERSION_OPERATION) == ___FIX(___NO_ERR)) {

   The last `___BEGIN' macro must expand to an unterminated compound
statement:

     { ___err = CONVERSION_OPERATION;

   If type check errors are impossible then a `___BEGIN' macro can
simply expand to an unterminated compound statement performing the
conversion:

     { CONVERSION_OPERATION;

   The `___END' macros must expand to a statement, or to nothing if no
cleanup is required, followed by a closing brace (to terminate the
compound statement started at the corresponding `___BEGIN' macro).

   The CONVERSION_OPERATION is typically a function call that returns
an error code value of type `___SCMOBJ' (the error codes are defined in
`gambit.h', and the error code `___FIX(___UNKNOWN_ERR)' is available
for generic errors).  CONVERSION_OPERATION can also set the variable
`___errmsg' of type `___SCMOBJ' to a specific Scheme string error
message.

   Below is a simple example showing how to interface to an `EBCDIC'
character type.  Memory allocation is not needed for conversion and type
check errors are impossible when converting EBCDIC to Scheme characters,
but they are possible when converting from Scheme characters to EBCDIC
since Gambit supports Unicode characters.

     (c-declare #<<c-declare-end

     typedef char EBCDIC; /* EBCDIC encoded characters */

     void put_char (EBCDIC c) { ... } /* EBCDIC I/O functions */
     EBCDIC get_char (void) { ... }

     char EBCDIC_to_ISO_8859_1[256] = { ... }; /* conversion tables */
     char ISO_8859_1_to_EBCDIC[256] = { ... };

     ___SCMOBJ SCMOBJ_to_EBCDIC (___SCMOBJ src, EBCDIC *dst)
     {
       int x = ___INT(src); /* convert from Scheme character to int */
       if (x > 255) return ___FIX(___UNKNOWN_ERR);
       *dst = ISO_8859_1_to_EBCDIC[x];
       return ___FIX(___NO_ERR);
     }

     #define ___BEGIN_CFUN_SCMOBJ_to_EBCDIC(src,dst,i) \
     if ((___err = SCMOBJ_to_EBCDIC (src, &dst)) == ___FIX(___NO_ERR)) {
     #define ___END_CFUN_SCMOBJ_to_EBCDIC(src,dst,i) }

     #define ___BEGIN_CFUN_EBCDIC_to_SCMOBJ(src,dst) \
     { dst = ___CHR(EBCDIC_to_ISO_8859_1[src]);
     #define ___END_CFUN_EBCDIC_to_SCMOBJ(src,dst) }

     #define ___BEGIN_SFUN_EBCDIC_to_SCMOBJ(src,dst,i) \
     { dst = ___CHR(EBCDIC_to_ISO_8859_1[src]);
     #define ___END_SFUN_EBCDIC_to_SCMOBJ(src,dst,i) }

     #define ___BEGIN_SFUN_SCMOBJ_to_EBCDIC(src,dst) \
     { ___err = SCMOBJ_to_EBCDIC (src, &dst);
     #define ___END_SFUN_SCMOBJ_to_EBCDIC(src,dst) }

     c-declare-end
     )

     (c-define-type EBCDIC "EBCDIC" "EBCDIC_to_SCMOBJ" "SCMOBJ_to_EBCDIC" #f)

     (define put-char (c-lambda (EBCDIC) void "put_char"))
     (define get-char (c-lambda () EBCDIC "get_char"))

     (c-define (write-EBCDIC c) (EBCDIC) void "write_EBCDIC" ""
       (write-char c))

     (c-define (read-EBCDIC) () EBCDIC "read_EBCDIC" ""
       (read-char))

   Below is a more complex example that requires memory allocation when
converting from C to Scheme.  It is an interface to a 2D `point' type
which is represented in Scheme by a pair of integers.  The conversion
of the `x' and `y' components is done by calls to the conversion macros
for the `int' type (defined in `gambit.h').  Note that no cleanup is
necessary when converting from Scheme to C (i.e. the last parameter of
the `c-define-type' is `#f').

     (c-declare #<<c-declare-end

     typedef struct { int x, y; } point;

     void line_to (point p) { ... }
     point get_mouse (void) { ... }
     point add_points (point p1, point p2) { ... }

     ___SCMOBJ SCMOBJ_to_POINT (___SCMOBJ src, point *dst, int arg_num)
     {
       ___SCMOBJ ___err = ___FIX(___NO_ERR);
       if (!___PAIRP(src))
         ___err = ___FIX(___UNKNOWN_ERR);
       else
         {
           ___SCMOBJ car = ___CAR(src);
           ___SCMOBJ cdr = ___CDR(src);
           ___BEGIN_CFUN_SCMOBJ_TO_INT(car,dst->x,arg_num)
           ___BEGIN_CFUN_SCMOBJ_TO_INT(cdr,dst->y,arg_num)
           ___END_CFUN_SCMOBJ_TO_INT(cdr,dst->y,arg_num)
           ___END_CFUN_SCMOBJ_TO_INT(car,dst->x,arg_num)
         }
       return ___err;
     }

     ___SCMOBJ POINT_to_SCMOBJ (point src, ___SCMOBJ *dst, int arg_num)
     {
       ___SCMOBJ ___err = ___FIX(___NO_ERR);
       ___SCMOBJ x_scmobj;
       ___SCMOBJ y_scmobj;
       ___BEGIN_SFUN_INT_TO_SCMOBJ(src.x,x_scmobj,arg_num)
       ___BEGIN_SFUN_INT_TO_SCMOBJ(src.y,y_scmobj,arg_num)
       *dst = ___EXT(___make_pair) (x_scmobj, y_scmobj, ___STILL);
       if (___FIXNUMP(*dst))
         ___err = *dst; /* return allocation error */
       ___END_SFUN_INT_TO_SCMOBJ(src.y,y_scmobj,arg_num)
       ___END_SFUN_INT_TO_SCMOBJ(src.x,x_scmobj,arg_num)
       return ___err;
     }

     #define ___BEGIN_CFUN_SCMOBJ_to_POINT(src,dst,i) \
     if ((___err = SCMOBJ_to_POINT (src, &dst, i)) == ___FIX(___NO_ERR)) {
     #define ___END_CFUN_SCMOBJ_to_POINT(src,dst,i) }

     #define ___BEGIN_CFUN_POINT_to_SCMOBJ(src,dst) \
     if ((___err = POINT_to_SCMOBJ (src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) {
     #define ___END_CFUN_POINT_to_SCMOBJ(src,dst) \
     ___EXT(___release_scmobj) (dst); }

     #define ___BEGIN_SFUN_POINT_to_SCMOBJ(src,dst,i) \
     if ((___err = POINT_to_SCMOBJ (src, &dst, i)) == ___FIX(___NO_ERR)) {
     #define ___END_SFUN_POINT_to_SCMOBJ(src,dst,i) \
     ___EXT(___release_scmobj) (dst); }

     #define ___BEGIN_SFUN_SCMOBJ_to_POINT(src,dst) \
     { ___err = SCMOBJ_to_POINT (src, &dst, ___RETURN_POS);
     #define ___END_SFUN_SCMOBJ_to_POINT(src,dst) }

     c-declare-end
     )

     (c-define-type point "point" "POINT_to_SCMOBJ" "SCMOBJ_to_POINT" #f)

     (define line-to (c-lambda (point) void "line_to"))
     (define get-mouse (c-lambda () point "get_mouse"))
     (define add-points (c-lambda (point point) point "add_points"))

     (c-define (write-point p) (point) void "write_point" ""
       (write p))

     (c-define (read-point) () point "read_point" ""
       (read))

   An example that requires memory allocation when converting from C to
Scheme and Scheme to C is shown below.  It is an interface to a
"null-terminated array of strings" type which is represented in Scheme
by a list of strings.  Note that some cleanup is necessary when
converting from Scheme to C.

     (c-declare #<<c-declare-end

     #include <stdlib.h>
     #include <unistd.h>

     extern char **environ;

     char **get_environ (void) { return environ; }

     void free_strings (char **strings)
     {
       char **ptr = strings;
       while (*ptr != NULL)
         {
           ___EXT(___release_string) (*ptr);
           ptr++;
         }
       free (strings);
     }

     ___SCMOBJ SCMOBJ_to_STRINGS (___SCMOBJ src, char ***dst, int arg_num)
     {
       /*
        * Src is a list of Scheme strings.  Dst will be a null terminated
        * array of C strings.
        */

       int i;
       ___SCMOBJ lst = src;
       int len = 4; /* start with a small result array */
       char **result = (char**) malloc (len * sizeof (char*));

       if (result == NULL)
         return ___FIX(___HEAP_OVERFLOW_ERR);

       i = 0;
       result[i] = NULL; /* always keep array null terminated */

       while (___PAIRP(lst))
         {
           ___SCMOBJ scm_str = ___CAR(lst);
           char *c_str;
           ___SCMOBJ ___err;

           if (i >= len-1) /* need to grow the result array? */
             {
               char **new_result;
               int j;

               len = len * 3 / 2;
               new_result = (char**) malloc (len * sizeof (char*));
               if (new_result == NULL)
                 {
                   free_strings (result);
                   return ___FIX(___HEAP_OVERFLOW_ERR);
                 }
               for (j=i; j>=0; j--)
                 new_result[j] = result[j];
               free (result);
               result = new_result;
             }

           ___err = ___EXT(___SCMOBJ_to_CHARSTRING) (scm_str, &c_str, arg_num);

           if (___err != ___FIX(___NO_ERR))
             {
               free_strings (result);
               return ___err;
             }

           result[i++] = c_str;
           result[i] = NULL;
           lst = ___CDR(lst);
         }

       if (!___NULLP(lst))
         {
           free_strings (result);
           return ___FIX(___UNKNOWN_ERR);
         }

       /*
        * Note that the caller is responsible for calling free_strings
        * when it is done with the result.
        */

       *dst = result;
       return ___FIX(___NO_ERR);
     }

     ___SCMOBJ STRINGS_to_SCMOBJ (char **src, ___SCMOBJ *dst, int arg_num)
     {
       ___SCMOBJ ___err = ___FIX(___NO_ERR);
       ___SCMOBJ result = ___NUL; /* start with the empty list */
       int i = 0;

       while (src[i] != NULL)
         i++;

       /* build the list of strings starting at the tail */

       while (--i >= 0)
         {
           ___SCMOBJ scm_str;
           ___SCMOBJ new_result;

           /*
            * Invariant: result is either the empty list or a ___STILL pair
            * with reference count equal to 1.  This is important because
            * it is possible that ___CHARSTRING_to_SCMOBJ and ___make_pair
            * will invoke the garbage collector and we don't want the
            * reference in result to become invalid (which would be the
            * case if result was a ___MOVABLE pair or if it had a zero
            * reference count).
            */

           ___err = ___EXT(___CHARSTRING_to_SCMOBJ) (src[i], &scm_str, arg_num);

           if (___err != ___FIX(___NO_ERR))
             {
               ___EXT(___release_scmobj) (result); /* allow GC to reclaim result */
               return ___FIX(___UNKNOWN_ERR);
             }

           /*
            * Note that scm_str will be a ___STILL object with reference
            * count equal to 1, so there is no risk that it will be
            * reclaimed or moved if ___make_pair invokes the garbage
            * collector.
            */

           new_result = ___EXT(___make_pair) (scm_str, result, ___STILL);

           /*
            * We can zero the reference count of scm_str and result (if
            * not the empty list) because the pair now references these
            * objects and the pair is reachable (it can't be reclaimed
            * or moved by the garbage collector).
            */

           ___EXT(___release_scmobj) (scm_str);
           ___EXT(___release_scmobj) (result);

           result = new_result;

           if (___FIXNUMP(result))
             return result; /* allocation failed */
         }

       /*
        * Note that result is either the empty list or a ___STILL pair
        * with a reference count equal to 1.  There will be a call to
        * ___release_scmobj later on (in ___END_CFUN_STRINGS_to_SCMOBJ
        * or ___END_SFUN_STRINGS_to_SCMOBJ) that will allow the garbage
        * collector to reclaim the whole list of strings when the Scheme
        * world no longer references it.
        */

       *dst = result;
       return ___FIX(___NO_ERR);
     }

     #define ___BEGIN_CFUN_SCMOBJ_to_STRINGS(src,dst,i) \
     if ((___err = SCMOBJ_to_STRINGS (src, &dst, i)) == ___FIX(___NO_ERR)) {
     #define ___END_CFUN_SCMOBJ_to_STRINGS(src,dst,i) \
     free_strings (dst); }

     #define ___BEGIN_CFUN_STRINGS_to_SCMOBJ(src,dst) \
     if ((___err = STRINGS_to_SCMOBJ (src, &dst, ___RETURN_POS)) == ___FIX(___NO_ERR)) {
     #define ___END_CFUN_STRINGS_to_SCMOBJ(src,dst) \
     ___EXT(___release_scmobj) (dst); }

     #define ___BEGIN_SFUN_STRINGS_to_SCMOBJ(src,dst,i) \
     if ((___err = STRINGS_to_SCMOBJ (src, &dst, i)) == ___FIX(___NO_ERR)) {
     #define ___END_SFUN_STRINGS_to_SCMOBJ(src,dst,i) \
     ___EXT(___release_scmobj) (dst); }

     #define ___BEGIN_SFUN_SCMOBJ_to_STRINGS(src,dst) \
     { ___err = SCMOBJ_to_STRINGS (src, &dst, ___RETURN_POS);
     #define ___END_SFUN_SCMOBJ_to_STRINGS(src,dst) }

     c-declare-end
     )

     (c-define-type char** "char**" "STRINGS_to_SCMOBJ" "SCMOBJ_to_STRINGS")

     (define execv (c-lambda (char-string char**) int "execv"))
     (define get-environ (c-lambda () char** "get_environ"))

     (c-define (write-strings x) (char**) void "write_strings" ""
       (write x))

     (c-define (read-strings) () char** "read_strings" ""
       (read))


File: gambit-c.info,  Node: continuations,  Prev: c-define-type,  Up: C-interface

19.7 Continuations and the C-interface
======================================

The C-interface allows C to Scheme calls to be nested.  This means that
during a call from C to Scheme another call from C to Scheme can be
performed.  This case occurs in the following program:

     (c-declare #<<c-declare-end

     int p (char *); /* forward declarations */
     int q (void);

     int a (char *x) { return 2 * p (x+1); }
     int b (short y) { return y + q (); }

     c-declare-end
     )

     (define a (c-lambda (char-string) int "a"))
     (define b (c-lambda (short) int "b"))

     (c-define (p z) (char-string) int "p" ""
       (+ (b 10) (string-length z)))

     (c-define (q) () int "q" ""
       123)

     (write (a "hello"))

   In this example, the main Scheme program calls the C function `a'
which calls the Scheme procedure `p' which in turn calls the C function
`b' which finally calls the Scheme procedure `q'.

   Gambit-C maintains the Scheme continuation separately from the C
stack, thus allowing the Scheme continuation to be unwound
independently from the C stack.  The C stack frame created for the C
function `f' is only removed from the C stack when control returns from
`f' or when control returns to a C function "above" `f'.  Special care
is required for programs which escape to Scheme (using first-class
continuations) from a Scheme to C (to Scheme) call because the C stack
frame will remain on the stack.  The C stack may overflow if this
happens in a loop with no intervening return to a C function.  To avoid
this problem make sure the C stack gets cleaned up by executing a normal
return from a Scheme to C call.


File: gambit-c.info,  Node: System limitations,  Next: Copyright and license,  Prev: C-interface,  Up: Top

20 System limitations
*********************

   * On some systems floating point overflows will cause the program to
     terminate with a floating point exception.

   * On some systems floating point operations involving `+nan.0'
     `+inf.0', `-inf.0', or `-0.' do not return the value required by
     the IEEE 754 floating point standard.

   * The compiler will not properly compile files with more than one
     definition (with `define') of the same procedure.  Replace all but
     the first `define' with assignments (`set!').

   * The maximum number of arguments that can be passed to a procedure
     by the `apply' procedure is 8192.



File: gambit-c.info,  Node: Copyright and license,  Next: General index,  Prev: System limitations,  Up: Top

21 Copyright and license
************************

The Gambit-C system release v4.2.8 is Copyright (C) 1994-2008 by Marc
Feeley, all rights reserved.  The Gambit-C system release v4.2.8 is
licensed under two licenses: the Apache License, Version 2.0, and the
GNU LESSER GENERAL PUBLIC LICENSE, Version 2.1.  You have the option to
choose which of these two licenses to abide by.  The licenses are
copied below.


                                   Apache License
                             Version 2.0, January 2004
                          http://www.apache.org/licenses/

     TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

     1. Definitions.

        "License" shall mean the terms and conditions for use, reproduction,
        and distribution as defined by Sections 1 through 9 of this document.

        "Licensor" shall mean the copyright owner or entity authorized by
        the copyright owner that is granting the License.

        "Legal Entity" shall mean the union of the acting entity and all
        other entities that control, are controlled by, or are under common
        control with that entity. For the purposes of this definition,
        "control" means (i) the power, direct or indirect, to cause the
        direction or management of such entity, whether by contract or
        otherwise, or (ii) ownership of fifty percent (50%) or more of the
        outstanding shares, or (iii) beneficial ownership of such entity.

        "You" (or "Your") shall mean an individual or Legal Entity
        exercising permissions granted by this License.

        "Source" form shall mean the preferred form for making modifications,
        including but not limited to software source code, documentation
        source, and configuration files.

        "Object" form shall mean any form resulting from mechanical
        transformation or translation of a Source form, including but
        not limited to compiled object code, generated documentation,
        and conversions to other media types.

        "Work" shall mean the work of authorship, whether in Source or
        Object form, made available under the License, as indicated by a
        copyright notice that is included in or attached to the work
        (an example is provided in the Appendix below).

        "Derivative Works" shall mean any work, whether in Source or Object
        form, that is based on (or derived from) the Work and for which the
        editorial revisions, annotations, elaborations, or other modifications
        represent, as a whole, an original work of authorship. For the purposes
        of this License, Derivative Works shall not include works that remain
        separable from, or merely link (or bind by name) to the interfaces of,
        the Work and Derivative Works thereof.

        "Contribution" shall mean any work of authorship, including
        the original version of the Work and any modifications or additions
        to that Work or Derivative Works thereof, that is intentionally
        submitted to Licensor for inclusion in the Work by the copyright owner
        or by an individual or Legal Entity authorized to submit on behalf of
        the copyright owner. For the purposes of this definition, "submitted"
        means any form of electronic, verbal, or written communication sent
        to the Licensor or its representatives, including but not limited to
        communication on electronic mailing lists, source code control systems,
        and issue tracking systems that are managed by, or on behalf of, the
        Licensor for the purpose of discussing and improving the Work, but
        excluding communication that is conspicuously marked or otherwise
        designated in writing by the copyright owner as "Not a Contribution."

        "Contributor" shall mean Licensor and any individual or Legal Entity
        on behalf of whom a Contribution has been received by Licensor and
        subsequently incorporated within the Work.

     2. Grant of Copyright License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        copyright license to reproduce, prepare Derivative Works of,
        publicly display, publicly perform, sublicense, and distribute the
        Work and such Derivative Works in Source or Object form.

     3. Grant of Patent License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        (except as stated in this section) patent license to make, have made,
        use, offer to sell, sell, import, and otherwise transfer the Work,
        where such license applies only to those patent claims licensable
        by such Contributor that are necessarily infringed by their
        Contribution(s) alone or by combination of their Contribution(s)
        with the Work to which such Contribution(s) was submitted. If You
        institute patent litigation against any entity (including a
        cross-claim or counterclaim in a lawsuit) alleging that the Work
        or a Contribution incorporated within the Work constitutes direct
        or contributory patent infringement, then any patent licenses
        granted to You under this License for that Work shall terminate
        as of the date such litigation is filed.

     4. Redistribution. You may reproduce and distribute copies of the
        Work or Derivative Works thereof in any medium, with or without
        modifications, and in Source or Object form, provided that You
        meet the following conditions:

        (a) You must give any other recipients of the Work or
            Derivative Works a copy of this License; and

        (b) You must cause any modified files to carry prominent notices
            stating that You changed the files; and

        (c) You must retain, in the Source form of any Derivative Works
            that You distribute, all copyright, patent, trademark, and
            attribution notices from the Source form of the Work,
            excluding those notices that do not pertain to any part of
            the Derivative Works; and

        (d) If the Work includes a "NOTICE" text file as part of its
            distribution, then any Derivative Works that You distribute must
            include a readable copy of the attribution notices contained
            within such NOTICE file, excluding those notices that do not
            pertain to any part of the Derivative Works, in at least one
            of the following places: within a NOTICE text file distributed
            as part of the Derivative Works; within the Source form or
            documentation, if provided along with the Derivative Works; or,
            within a display generated by the Derivative Works, if and
            wherever such third-party notices normally appear. The contents
            of the NOTICE file are for informational purposes only and
            do not modify the License. You may add Your own attribution
            notices within Derivative Works that You distribute, alongside
            or as an addendum to the NOTICE text from the Work, provided
            that such additional attribution notices cannot be construed
            as modifying the License.

        You may add Your own copyright statement to Your modifications and
        may provide additional or different license terms and conditions
        for use, reproduction, or distribution of Your modifications, or
        for any such Derivative Works as a whole, provided Your use,
        reproduction, and distribution of the Work otherwise complies with
        the conditions stated in this License.

     5. Submission of Contributions. Unless You explicitly state otherwise,
        any Contribution intentionally submitted for inclusion in the Work
        by You to the Licensor shall be under the terms and conditions of
        this License, without any additional terms or conditions.
        Notwithstanding the above, nothing herein shall supersede or modify
        the terms of any separate license agreement you may have executed
        with Licensor regarding such Contributions.

     6. Trademarks. This License does not grant permission to use the trade
        names, trademarks, service marks, or product names of the Licensor,
        except as required for reasonable and customary use in describing the
        origin of the Work and reproducing the content of the NOTICE file.

     7. Disclaimer of Warranty. Unless required by applicable law or
        agreed to in writing, Licensor provides the Work (and each
        Contributor provides its Contributions) on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        implied, including, without limitation, any warranties or conditions
        of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        PARTICULAR PURPOSE. You are solely responsible for determining the
        appropriateness of using or redistributing the Work and assume any
        risks associated with Your exercise of permissions under this License.

     8. Limitation of Liability. In no event and under no legal theory,
        whether in tort (including negligence), contract, or otherwise,
        unless required by applicable law (such as deliberate and grossly
        negligent acts) or agreed to in writing, shall any Contributor be
        liable to You for damages, including any direct, indirect, special,
        incidental, or consequential damages of any character arising as a
        result of this License or out of the use or inability to use the
        Work (including but not limited to damages for loss of goodwill,
        work stoppage, computer failure or malfunction, or any and all
        other commercial damages or losses), even if such Contributor
        has been advised of the possibility of such damages.

     9. Accepting Warranty or Additional Liability. While redistributing
        the Work or Derivative Works thereof, You may choose to offer,
        and charge a fee for, acceptance of support, warranty, indemnity,
        or other liability obligations and/or rights consistent with this
        License. However, in accepting such obligations, You may act only
        on Your own behalf and on Your sole responsibility, not on behalf
        of any other Contributor, and only if You agree to indemnify,
        defend, and hold each Contributor harmless for any liability
        incurred by, or claims asserted against, such Contributor by reason
        of your accepting any such warranty or additional liability.

     END OF TERMS AND CONDITIONS

     APPENDIX: How to apply the Apache License to your work.

        To apply the Apache License to your work, attach the following
        boilerplate notice, with the fields enclosed by brackets "[]"
        replaced with your own identifying information. (Don't include
        the brackets!)  The text should be enclosed in the appropriate
        comment syntax for the file format. We also recommend that a
        file or class name and description of purpose be included on the
        same "printed page" as the copyright notice for easier
        identification within third-party archives.

     Copyright [yyyy] [name of copyright owner]

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.

                       GNU LESSER GENERAL PUBLIC LICENSE
                            Version 2.1, February 1999

      Copyright (C) 1991, 1999 Free Software Foundation, Inc.
          51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
      Everyone is permitted to copy and distribute verbatim copies
      of this license document, but changing it is not allowed.

     [This is the first released version of the Lesser GPL.  It also counts
      as the successor of the GNU Library Public License, version 2, hence
      the version number 2.1.]

                                 Preamble

       The licenses for most software are designed to take away your
     freedom to share and change it.  By contrast, the GNU General Public
     Licenses are intended to guarantee your freedom to share and change
     free software--to make sure the software is free for all its users.

       This license, the Lesser General Public License, applies to some
     specially designated software packages--typically libraries--of the
     Free Software Foundation and other authors who decide to use it.  You
     can use it too, but we suggest you first think carefully about whether
     this license or the ordinary General Public License is the better
     strategy to use in any particular case, based on the explanations below.

       When we speak of free software, we are referring to freedom of use,
     not price.  Our General Public Licenses are designed to make sure that
     you have the freedom to distribute copies of free software (and charge
     for this service if you wish); that you receive source code or can get
     it if you want it; that you can change the software and use pieces of
     it in new free programs; and that you are informed that you can do
     these things.

       To protect your rights, we need to make restrictions that forbid
     distributors to deny you these rights or to ask you to surrender these
     rights.  These restrictions translate to certain responsibilities for
     you if you distribute copies of the library or if you modify it.

       For example, if you distribute copies of the library, whether gratis
     or for a fee, you must give the recipients all the rights that we gave
     you.  You must make sure that they, too, receive or can get the source
     code.  If you link other code with the library, you must provide
     complete object files to the recipients, so that they can relink them
     with the library after making changes to the library and recompiling
     it.  And you must show them these terms so they know their rights.

       We protect your rights with a two-step method: (1) we copyright the
     library, and (2) we offer you this license, which gives you legal
     permission to copy, distribute and/or modify the library.

       To protect each distributor, we want to make it very clear that
     there is no warranty for the free library.  Also, if the library is
     modified by someone else and passed on, the recipients should know
     that what they have is not the original version, so that the original
     author's reputation will not be affected by problems that might be
     introduced by others.

       Finally, software patents pose a constant threat to the existence of
     any free program.  We wish to make sure that a company cannot
     effectively restrict the users of a free program by obtaining a
     restrictive license from a patent holder.  Therefore, we insist that
     any patent license obtained for a version of the library must be
     consistent with the full freedom of use specified in this license.

       Most GNU software, including some libraries, is covered by the
     ordinary GNU General Public License.  This license, the GNU Lesser
     General Public License, applies to certain designated libraries, and
     is quite different from the ordinary General Public License.  We use
     this license for certain libraries in order to permit linking those
     libraries into non-free programs.

       When a program is linked with a library, whether statically or using
     a shared library, the combination of the two is legally speaking a
     combined work, a derivative of the original library.  The ordinary
     General Public License therefore permits such linking only if the
     entire combination fits its criteria of freedom.  The Lesser General
     Public License permits more lax criteria for linking other code with
     the library.

       We call this license the "Lesser" General Public License because it
     does Less to protect the user's freedom than the ordinary General
     Public License.  It also provides other free software developers Less
     of an advantage over competing non-free programs.  These disadvantages
     are the reason we use the ordinary General Public License for many
     libraries.  However, the Lesser license provides advantages in certain
     special circumstances.

       For example, on rare occasions, there may be a special need to
     encourage the widest possible use of a certain library, so that it becomes
     a de-facto standard.  To achieve this, non-free programs must be
     allowed to use the library.  A more frequent case is that a free
     library does the same job as widely used non-free libraries.  In this
     case, there is little to gain by limiting the free library to free
     software only, so we use the Lesser General Public License.

       In other cases, permission to use a particular library in non-free
     programs enables a greater number of people to use a large body of
     free software.  For example, permission to use the GNU C Library in
     non-free programs enables many more people to use the whole GNU
     operating system, as well as its variant, the GNU/Linux operating
     system.

       Although the Lesser General Public License is Less protective of the
     users' freedom, it does ensure that the user of a program that is
     linked with the Library has the freedom and the wherewithal to run
     that program using a modified version of the Library.

       The precise terms and conditions for copying, distribution and
     modification follow.  Pay close attention to the difference between a
     "work based on the library" and a "work that uses the library".  The
     former contains code derived from the library, whereas the latter must
     be combined with the library in order to run.

                       GNU LESSER GENERAL PUBLIC LICENSE
        TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

       0. This License Agreement applies to any software library or other
     program which contains a notice placed by the copyright holder or
     other authorized party saying it may be distributed under the terms of
     this Lesser General Public License (also called "this License").
     Each licensee is addressed as "you".

       A "library" means a collection of software functions and/or data
     prepared so as to be conveniently linked with application programs
     (which use some of those functions and data) to form executables.

       The "Library", below, refers to any such software library or work
     which has been distributed under these terms.  A "work based on the
     Library" means either the Library or any derivative work under
     copyright law: that is to say, a work containing the Library or a
     portion of it, either verbatim or with modifications and/or translated
     straightforwardly into another language.  (Hereinafter, translation is
     included without limitation in the term "modification".)

       "Source code" for a work means the preferred form of the work for
     making modifications to it.  For a library, complete source code means
     all the source code for all modules it contains, plus any associated
     interface definition files, plus the scripts used to control compilation
     and installation of the library.

       Activities other than copying, distribution and modification are not
     covered by this License; they are outside its scope.  The act of
     running a program using the Library is not restricted, and output from
     such a program is covered only if its contents constitute a work based
     on the Library (independent of the use of the Library in a tool for
     writing it).  Whether that is true depends on what the Library does
     and what the program that uses the Library does.

       1. You may copy and distribute verbatim copies of the Library's
     complete source code as you receive it, in any medium, provided that
     you conspicuously and appropriately publish on each copy an
     appropriate copyright notice and disclaimer of warranty; keep intact
     all the notices that refer to this License and to the absence of any
     warranty; and distribute a copy of this License along with the
     Library.

       You may charge a fee for the physical act of transferring a copy,
     and you may at your option offer warranty protection in exchange for a
     fee.

       2. You may modify your copy or copies of the Library or any portion
     of it, thus forming a work based on the Library, and copy and
     distribute such modifications or work under the terms of Section 1
     above, provided that you also meet all of these conditions:

         a) The modified work must itself be a software library.

         b) You must cause the files modified to carry prominent notices
         stating that you changed the files and the date of any change.

         c) You must cause the whole of the work to be licensed at no
         charge to all third parties under the terms of this License.

         d) If a facility in the modified Library refers to a function or a
         table of data to be supplied by an application program that uses
         the facility, other than as an argument passed when the facility
         is invoked, then you must make a good faith effort to ensure that,
         in the event an application does not supply such function or
         table, the facility still operates, and performs whatever part of
         its purpose remains meaningful.

         (For example, a function in a library to compute square roots has
         a purpose that is entirely well-defined independent of the
         application.  Therefore, Subsection 2d requires that any
         application-supplied function or table used by this function must
         be optional: if the application does not supply it, the square
         root function must still compute square roots.)

     These requirements apply to the modified work as a whole.  If
     identifiable sections of that work are not derived from the Library,
     and can be reasonably considered independent and separate works in
     themselves, then this License, and its terms, do not apply to those
     sections when you distribute them as separate works.  But when you
     distribute the same sections as part of a whole which is a work based
     on the Library, the distribution of the whole must be on the terms of
     this License, whose permissions for other licensees extend to the
     entire whole, and thus to each and every part regardless of who wrote
     it.

     Thus, it is not the intent of this section to claim rights or contest
     your rights to work written entirely by you; rather, the intent is to
     exercise the right to control the distribution of derivative or
     collective works based on the Library.

     In addition, mere aggregation of another work not based on the Library
     with the Library (or with a work based on the Library) on a volume of
     a storage or distribution medium does not bring the other work under
     the scope of this License.

       3. You may opt to apply the terms of the ordinary GNU General Public
     License instead of this License to a given copy of the Library.  To do
     this, you must alter all the notices that refer to this License, so
     that they refer to the ordinary GNU General Public License, version 2,
     instead of to this License.  (If a newer version than version 2 of the
     ordinary GNU General Public License has appeared, then you can specify
     that version instead if you wish.)  Do not make any other change in
     these notices.

       Once this change is made in a given copy, it is irreversible for
     that copy, so the ordinary GNU General Public License applies to all
     subsequent copies and derivative works made from that copy.

       This option is useful when you wish to copy part of the code of
     the Library into a program that is not a library.

       4. You may copy and distribute the Library (or a portion or
     derivative of it, under Section 2) in object code or executable form
     under the terms of Sections 1 and 2 above provided that you accompany
     it with the complete corresponding machine-readable source code, which
     must be distributed under the terms of Sections 1 and 2 above on a
     medium customarily used for software interchange.

       If distribution of object code is made by offering access to copy
     from a designated place, then offering equivalent access to copy the
     source code from the same place satisfies the requirement to
     distribute the source code, even though third parties are not
     compelled to copy the source along with the object code.

       5. A program that contains no derivative of any portion of the
     Library, but is designed to work with the Library by being compiled or
     linked with it, is called a "work that uses the Library".  Such a
     work, in isolation, is not a derivative work of the Library, and
     therefore falls outside the scope of this License.

       However, linking a "work that uses the Library" with the Library
     creates an executable that is a derivative of the Library (because it
     contains portions of the Library), rather than a "work that uses the
     library".  The executable is therefore covered by this License.
     Section 6 states terms for distribution of such executables.

       When a "work that uses the Library" uses material from a header file
     that is part of the Library, the object code for the work may be a
     derivative work of the Library even though the source code is not.
     Whether this is true is especially significant if the work can be
     linked without the Library, or if the work is itself a library.  The
     threshold for this to be true is not precisely defined by law.

       If such an object file uses only numerical parameters, data
     structure layouts and accessors, and small macros and small inline
     functions (ten lines or less in length), then the use of the object
     file is unrestricted, regardless of whether it is legally a derivative
     work.  (Executables containing this object code plus portions of the
     Library will still fall under Section 6.)

       Otherwise, if the work is a derivative of the Library, you may
     distribute the object code for the work under the terms of Section 6.
     Any executables containing that work also fall under Section 6,
     whether or not they are linked directly with the Library itself.

       6. As an exception to the Sections above, you may also combine or
     link a "work that uses the Library" with the Library to produce a
     work containing portions of the Library, and distribute that work
     under terms of your choice, provided that the terms permit
     modification of the work for the customer's own use and reverse
     engineering for debugging such modifications.

       You must give prominent notice with each copy of the work that the
     Library is used in it and that the Library and its use are covered by
     this License.  You must supply a copy of this License.  If the work
     during execution displays copyright notices, you must include the
     copyright notice for the Library among them, as well as a reference
     directing the user to the copy of this License.  Also, you must do one
     of these things:

         a) Accompany the work with the complete corresponding
         machine-readable source code for the Library including whatever
         changes were used in the work (which must be distributed under
         Sections 1 and 2 above); and, if the work is an executable linked
         with the Library, with the complete machine-readable "work that
         uses the Library", as object code and/or source code, so that the
         user can modify the Library and then relink to produce a modified
         executable containing the modified Library.  (It is understood
         that the user who changes the contents of definitions files in the
         Library will not necessarily be able to recompile the application
         to use the modified definitions.)

         b) Use a suitable shared library mechanism for linking with the
         Library.  A suitable mechanism is one that (1) uses at run time a
         copy of the library already present on the user's computer system,
         rather than copying library functions into the executable, and (2)
         will operate properly with a modified version of the library, if
         the user installs one, as long as the modified version is
         interface-compatible with the version that the work was made with.

         c) Accompany the work with a written offer, valid for at
         least three years, to give the same user the materials
         specified in Subsection 6a, above, for a charge no more
         than the cost of performing this distribution.

         d) If distribution of the work is made by offering access to copy
         from a designated place, offer equivalent access to copy the above
         specified materials from the same place.

         e) Verify that the user has already received a copy of these
         materials or that you have already sent this user a copy.

       For an executable, the required form of the "work that uses the
     Library" must include any data and utility programs needed for
     reproducing the executable from it.  However, as a special exception,
     the materials to be distributed need not include anything that is
     normally distributed (in either source or binary form) with the major
     components (compiler, kernel, and so on) of the operating system on
     which the executable runs, unless that component itself accompanies
     the executable.

       It may happen that this requirement contradicts the license
     restrictions of other proprietary libraries that do not normally
     accompany the operating system.  Such a contradiction means you cannot
     use both them and the Library together in an executable that you
     distribute.

       7. You may place library facilities that are a work based on the
     Library side-by-side in a single library together with other library
     facilities not covered by this License, and distribute such a combined
     library, provided that the separate distribution of the work based on
     the Library and of the other library facilities is otherwise
     permitted, and provided that you do these two things:

         a) Accompany the combined library with a copy of the same work
         based on the Library, uncombined with any other library
         facilities.  This must be distributed under the terms of the
         Sections above.

         b) Give prominent notice with the combined library of the fact
         that part of it is a work based on the Library, and explaining
         where to find the accompanying uncombined form of the same work.

       8. You may not copy, modify, sublicense, link with, or distribute
     the Library except as expressly provided under this License.  Any
     attempt otherwise to copy, modify, sublicense, link with, or
     distribute the Library is void, and will automatically terminate your
     rights under this License.  However, parties who have received copies,
     or rights, from you under this License will not have their licenses
     terminated so long as such parties remain in full compliance.

       9. You are not required to accept this License, since you have not
     signed it.  However, nothing else grants you permission to modify or
     distribute the Library or its derivative works.  These actions are
     prohibited by law if you do not accept this License.  Therefore, by
     modifying or distributing the Library (or any work based on the
     Library), you indicate your acceptance of this License to do so, and
     all its terms and conditions for copying, distributing or modifying
     the Library or works based on it.

       10. Each time you redistribute the Library (or any work based on the
     Library), the recipient automatically receives a license from the
     original licensor to copy, distribute, link with or modify the Library
     subject to these terms and conditions.  You may not impose any further
     restrictions on the recipients' exercise of the rights granted herein.
     You are not responsible for enforcing compliance by third parties with
     this License.

       11. If, as a consequence of a court judgment or allegation of patent
     infringement or for any other reason (not limited to patent issues),
     conditions are imposed on you (whether by court order, agreement or
     otherwise) that contradict the conditions of this License, they do not
     excuse you from the conditions of this License.  If you cannot
     distribute so as to satisfy simultaneously your obligations under this
     License and any other pertinent obligations, then as a consequence you
     may not distribute the Library at all.  For example, if a patent
     license would not permit royalty-free redistribution of the Library by
     all those who receive copies directly or indirectly through you, then
     the only way you could satisfy both it and this License would be to
     refrain entirely from distribution of the Library.

     If any portion of this section is held invalid or unenforceable under any
     particular circumstance, the balance of the section is intended to apply,
     and the section as a whole is intended to apply in other circumstances.

     It is not the purpose of this section to induce you to infringe any
     patents or other property right claims or to contest validity of any
     such claims; this section has the sole purpose of protecting the
     integrity of the free software distribution system which is
     implemented by public license practices.  Many people have made
     generous contributions to the wide range of software distributed
     through that system in reliance on consistent application of that
     system; it is up to the author/donor to decide if he or she is willing
     to distribute software through any other system and a licensee cannot
     impose that choice.

     This section is intended to make thoroughly clear what is believed to
     be a consequence of the rest of this License.

       12. If the distribution and/or use of the Library is restricted in
     certain countries either by patents or by copyrighted interfaces, the
     original copyright holder who places the Library under this License may add
     an explicit geographical distribution limitation excluding those countries,
     so that distribution is permitted only in or among countries not thus
     excluded.  In such case, this License incorporates the limitation as if
     written in the body of this License.

       13. The Free Software Foundation may publish revised and/or new
     versions of the Lesser General Public License from time to time.
     Such new versions will be similar in spirit to the present version,
     but may differ in detail to address new problems or concerns.

     Each version is given a distinguishing version number.  If the Library
     specifies a version number of this License which applies to it and
     "any later version", you have the option of following the terms and
     conditions either of that version or of any later version published by
     the Free Software Foundation.  If the Library does not specify a
     license version number, you may choose any version ever published by
     the Free Software Foundation.

       14. If you wish to incorporate parts of the Library into other free
     programs whose distribution conditions are incompatible with these,
     write to the author to ask for permission.  For software which is
     copyrighted by the Free Software Foundation, write to the Free
     Software Foundation; we sometimes make exceptions for this.  Our
     decision will be guided by the two goals of preserving the free status
     of all derivatives of our free software and of promoting the sharing
     and reuse of software generally.

                                 NO WARRANTY

       15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
     WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
     EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
     OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
     KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
     LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
     THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

       16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
     WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
     AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
     FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
     CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
     LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
     RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
     FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
     SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
     DAMAGES.

                          END OF TERMS AND CONDITIONS

                How to Apply These Terms to Your New Libraries

       If you develop a new library, and you want it to be of the greatest
     possible use to the public, we recommend making it free software that
     everyone can redistribute and change.  You can do so by permitting
     redistribution under these terms (or, alternatively, under the terms of the
     ordinary General Public License).

       To apply these terms, attach the following notices to the library.  It is
     safest to attach them to the start of each source file to most effectively
     convey the exclusion of warranty; and each file should have at least the
     "copyright" line and a pointer to where the full notice is found.

         <one line to give the library's name and a brief idea of what it does.>
         Copyright (C) <year>  <name of author>

         This library is free software; you can redistribute it and/or
         modify it under the terms of the GNU Lesser General Public
         License as published by the Free Software Foundation; either
         version 2.1 of the License, or (at your option) any later version.

         This library is distributed in the hope that it will be useful,
         but WITHOUT ANY WARRANTY; without even the implied warranty of
         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
         Lesser General Public License for more details.

         You should have received a copy of the GNU Lesser General Public
         License along with this library; if not, write to the Free Software
         Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

     Also add information on how to contact you by electronic and paper mail.

     You should also get your employer (if you work as a programmer) or your
     school, if any, to sign a "copyright disclaimer" for the library, if
     necessary.  Here is a sample; alter the names:

       Yoyodyne, Inc., hereby disclaims all copyright interest in the
       library `Frob' (a library for tweaking knobs) written by James Random Hacker.

       <signature of Ty Coon>, 1 April 1990
       Ty Coon, President of Vice

     That's all there is to it!

