This is guile.info, produced by makeinfo version 4.7 from guile.texi.

INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* Guile Reference: (guile).     The Guile reference manual.
END-INFO-DIR-ENTRY

   Guile Reference Manual Copyright (C) 1996 Free Software Foundation
Copyright (C) 1997 Free Software Foundation
Copyright (C) 2000 Free Software Foundation
Copyright (C) 2001 Free Software Foundation
Copyright (C) 2002 Free Software Foundation Copyright (C) 2004 Free
Software Foundation

   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 Free Software Foundation.


File: guile.info,  Node: Reading,  Next: Writing,  Prev: Ports,  Up: Input and Output

27.2 Reading
============

[Generic procedures for reading from ports.]

 -- Scheme Procedure: eof-object? x
 -- C Function: scm_eof_object_p (x)
     Return `#t' if X is an end-of-file object; otherwise return `#f'.

 -- Scheme Procedure: char-ready? [port]
 -- C Function: scm_char_ready_p (port)
     Return `#t' if a character is ready on input PORT and return `#f'
     otherwise.  If `char-ready?' returns `#t' then the next
     `read-char' operation on PORT is guaranteed not to hang.  If PORT
     is a file port at end of file then `char-ready?' returns `#t'.  (1)

 -- Scheme Procedure: read-char [port]
 -- C Function: scm_read_char (port)
     Return the next character available from PORT, updating PORT to
     point to the following character.  If no more characters are
     available, the end-of-file object is returned.

 -- Scheme Procedure: peek-char [port]
 -- C Function: scm_peek_char (port)
     Return the next character available from PORT, _without_ updating
     PORT to point to the following character.  If no more characters
     are available, the end-of-file object is returned.(2)

 -- Scheme Procedure: unread-char cobj [port]
 -- C Function: scm_unread_char (cobj, port)
     Place CHAR in PORT so that it will be read by the next read
     operation.  If called multiple times, the unread characters will
     be read again in last-in first-out order.  If PORT is not
     supplied, the current input port is used.

 -- Scheme Procedure: unread-string str port
 -- C Function: scm_unread_string (str, port)
     Place the string STR in PORT so that its characters will be read
     in subsequent read operations.  If called multiple times, the
     unread characters will be read again in last-in first-out order.
     If PORT is not supplied, the current-input-port is used.

 -- Scheme Procedure: drain-input port
 -- C Function: scm_drain_input (port)
     This procedure clears a port's input buffers, similar to the way
     that force-output clears the output buffer.  The contents of the
     buffers are returned as a single string, e.g.,

          (define p (open-input-file ...))
          (drain-input p) => empty string, nothing buffered yet.
          (unread-char (read-char p) p)
          (drain-input p) => initial chars from p, up to the buffer size.

     Draining the buffers may be useful for cleanly finishing buffered
     I/O so that the file descriptor can be used directly for further
     input.

 -- Scheme Procedure: port-column port
 -- Scheme Procedure: port-line port
 -- C Function: scm_port_column (port)
 -- C Function: scm_port_line (port)
     Return the current column number or line number of PORT, using the
     current input port if none is specified.  If the number is
     unknown, the result is #f.  Otherwise, the result is a 0-origin
     integer - i.e. the first character of the first line is line 0,
     column 0.  (However, when you display a file position, for example
     in an error message, we recommend you add 1 to get 1-origin
     integers.  This is because lines and column numbers traditionally
     start with 1, and that is what non-programmers will find most
     natural.)

 -- Scheme Procedure: set-port-column! port column
 -- Scheme Procedure: set-port-line! port line
 -- C Function: scm_set_port_column_x (port, column)
 -- C Function: scm_set_port_line_x (port, line)
     Set the current column or line number of PORT, using the current
     input port if none is specified.

   ---------- Footnotes ----------

   (1) `char-ready?' exists to make it possible for a program to accept
characters from interactive ports without getting stuck waiting for
input.  Any input editors associated with such ports must make sure
that characters whose existence has been asserted by `char-ready?'
cannot be rubbed out.  If `char-ready?' were to return `#f' at end of
file, a port at end of file would be indistinguishable from an
interactive port that has no ready characters.

   (2) The value returned by a call to `peek-char' is the same as the
value that would have been returned by a call to `read-char' on the same
port.  The only difference is that the very next call to `read-char' or
`peek-char' on that PORT will return the value returned by the
preceding call to `peek-char'.  In particular, a call to `peek-char' on
an interactive port will hang waiting for input whenever a call to
`read-char' would have hung.


File: guile.info,  Node: Writing,  Next: Closing,  Prev: Reading,  Up: Input and Output

27.3 Writing
============

[Generic procedures for writing to ports.]

 -- Scheme Procedure: get-print-state port
 -- C Function: scm_get_print_state (port)
     Return the print state of the port PORT. If PORT has no associated
     print state, `#f' is returned.

 -- Scheme Procedure: display obj [port]
     Send a representation of OBJ to CURRENT-OUTPUT-PORT.  Optional
     second arg PORT specifies an alternative output port.  The
     representation is similar to that produced by `write' (REFFIXME),
     the differences being strings are not quoted (and their characters
     are not escaped), and characters are rendered as if with
     `write-char'.

 -- Scheme Procedure: newline [port]
 -- C Function: scm_newline (port)
     Send a newline to PORT.  If PORT is omitted, send to the current
     output port.

 -- Scheme Procedure: port-with-print-state port pstate
 -- C Function: scm_port_with_print_state (port, pstate)
     Create a new port which behaves like PORT, but with an included
     print state PSTATE.

 -- Scheme Procedure: print-options-interface [setting]
 -- C Function: scm_print_options (setting)
     Option interface for the print options. Instead of using this
     procedure directly, use the procedures `print-enable',
     `print-disable', `print-set!' and `print-options'.

 -- Scheme Procedure: simple-format destination message . args
 -- C Function: scm_simple_format (destination, message, args)
     Write MESSAGE to DESTINATION, defaulting to the current output
     port.  MESSAGE can contain `~A' (was `%s') and `~S' (was `%S')
     escapes.  When printed, the escapes are replaced with
     corresponding members of ARGS: `~A' formats using `display' and
     `~S' formats using `write'.  If DESTINATION is `#t', then use the
     current output port, if DESTINATION is `#f', then return a string
     containing the formatted text. Does not add a trailing newline.

 -- Scheme Procedure: write-char chr [port]
 -- C Function: scm_write_char (chr, port)
     Send character CHR to PORT.

 -- Scheme Procedure: force-output [port]
 -- C Function: scm_force_output (port)
     Flush the specified output port, or the current output port if PORT
     is omitted.  The current output buffer contents are passed to the
     underlying port implementation (e.g., in the case of fports, the
     data will be written to the file and the output buffer will be
     cleared.)  It has no effect on an unbuffered port.

     The return value is unspecified.

 -- Scheme Procedure: flush-all-ports
 -- C Function: scm_flush_all_ports ()
     Equivalent to calling `force-output' on all open output ports.
     The return value is unspecified.


File: guile.info,  Node: Closing,  Next: Random Access,  Prev: Writing,  Up: Input and Output

27.4 Closing
============

 -- Scheme Procedure: close-port port
 -- C Function: scm_close_port (port)
     Close the specified port object.  Return `#t' if it successfully
     closes a port or `#f' if it was already closed.  An exception may
     be raised if an error occurs, for example when flushing buffered
     output.  See also *Note close: Ports and File Descriptors, for a
     procedure which can close file descriptors.

 -- Scheme Procedure: close-input-port port
 -- C Function: scm_close_input_port (port)
     Close the specified input port object.  The routine has no effect
     if the file has already been closed.  An exception may be raised
     if an error occurs.  The value returned is unspecified.

     See also *Note close: Ports and File Descriptors, for a procedure
     which can close file descriptors.

 -- Scheme Procedure: close-output-port port
 -- C Function: scm_close_output_port (port)
     Close the specified output port object.  The routine has no effect
     if the file has already been closed.  An exception may be raised
     if an error occurs.  The value returned is unspecified.

     See also *Note close: Ports and File Descriptors, for a procedure
     which can close file descriptors.

 -- Scheme Procedure: port-closed? port
 -- C Function: scm_port_closed_p (port)
     Return `#t' if PORT is closed or `#f' if it is open.


File: guile.info,  Node: Random Access,  Next: Line/Delimited,  Prev: Closing,  Up: Input and Output

27.5 Random Access
==================

 -- Scheme Procedure: seek fd_port offset whence
 -- C Function: scm_seek (fd_port, offset, whence)
     Sets the current position of FD/PORT to the integer OFFSET, which
     is interpreted according to the value of WHENCE.

     One of the following variables should be supplied for WHENCE:

      -- Variabele: SEEK_SET
          Seek from the beginning of the file.

      -- Variabele: SEEK_CUR
          Seek from the current position.

      -- Variabele: SEEK_END
          Seek from the end of the file.
     If FD/PORT is a file descriptor, the underlying system call is
     `lseek'.  PORT may be a string port.

     The value returned is the new position in the file.  This means
     that the current position of a port can be obtained using:
          (seek port 0 SEEK_CUR)

 -- Scheme Procedure: ftell fd_port
 -- C Function: scm_ftell (fd_port)
     Return an integer representing the current position of FD/PORT,
     measured from the beginning.  Equivalent to:

          (seek port 0 SEEK_CUR)

 -- Scheme Procedure: truncate-file object [length]
 -- C Function: scm_truncate_file (object, length)
     Truncates the object referred to by OBJECT to at most LENGTH
     bytes.  OBJECT can be a string containing a file name or an
     integer file descriptor or a port.  LENGTH may be omitted if
     OBJECT is not a file name, in which case the truncation occurs at
     the current port.  position.  The return value is unspecified.


File: guile.info,  Node: Line/Delimited,  Next: Block Reading and Writing,  Prev: Random Access,  Up: Input and Output

27.6 Line Oriented and Delimited Text
=====================================

The delimited-I/O module can be accessed with:

     (use-modules (ice-9 rdelim))

   It can be used to read or write lines of text, or read text
delimited by a specified set of characters.  It's similar to the `(scsh
rdelim)' module from guile-scsh, but does not use multiple values or
character sets and has an extra procedure `write-line'.

 -- Scheme Procedure: read-line [port] [handle-delim]
     Return a line of text from PORT if specified, otherwise from the
     value returned by `(current-input-port)'.  Under Unix, a line of
     text is terminated by the first end-of-line character or by
     end-of-file.

     If HANDLE-DELIM is specified, it should be one of the following
     symbols:
    `trim'
          Discard the terminating delimiter.  This is the default, but
          it will be impossible to tell whether the read terminated
          with a delimiter or end-of-file.

    `concat'
          Append the terminating delimiter (if any) to the returned
          string.

    `peek'
          Push the terminating delimiter (if any) back on to the port.

    `split'
          Return a pair containing the string read from the port and the
          terminating delimiter or end-of-file object.

 -- Scheme Procedure: read-line! buf [port]
     Read a line of text into the supplied string BUF and return the
     number of characters added to BUF.  If BUF is filled, then `#f' is
     returned.  Read from PORT if specified, otherwise from the value
     returned by `(current-input-port)'.

 -- Scheme Procedure: read-delimited delims [port] [handle-delim]
     Read text until one of the characters in the string DELIMS is found
     or end-of-file is reached.  Read from PORT if supplied, otherwise
     from the value returned by `(current-input-port)'.  HANDLE-DELIM
     takes the same values as described for `read-line'.

 -- Scheme Procedure: read-delimited! delims buf [port] [handle-delim]
          [start] [end]
     Read text into the supplied string BUF and return the number of
     characters added to BUF (subject to HANDLE-DELIM, which takes the
     same values specified for `read-line'.  If BUF is filled, `#f' is
     returned for both the number of characters read and the delimiter.
     Also terminates if one of the characters in the string DELIMS is
     found or end-of-file is reached.  Read from PORT if supplied,
     otherwise from the value returned by `(current-input-port)'.

 -- Scheme Procedure: write-line obj [port]
 -- C Function: scm_write_line (obj, port)
     Display OBJ and a newline character to PORT.  If PORT is not
     specified, `(current-output-port)' is used.  This function is
     equivalent to:
          (display obj [port])
          (newline [port])

   Some of the abovementioned I/O functions rely on the following C
primitives.  These will mainly be of interest to people hacking Guile
internals.

 -- Scheme Procedure: %read-delimited! delims str gobble [port [start
          [end]]]
 -- C Function: scm_read_delimited_x (delims, str, gobble, port, start,
          end)
     Read characters from PORT into STR until one of the characters in
     the DELIMS string is encountered.  If GOBBLE is true, discard the
     delimiter character; otherwise, leave it in the input stream for
     the next read.  If PORT is not specified, use the value of
     `(current-input-port)'.  If START or END are specified, store data
     only into the substring of STR bounded by START and END (which
     default to the beginning and end of the string, respectively).

     Return a pair consisting of the delimiter that terminated the
     string and the number of characters read.  If reading stopped at
     the end of file, the delimiter returned is the EOF-OBJECT; if the
     string was filled without encountering a delimiter, this value is
     `#f'.

 -- Scheme Procedure: %read-line [port]
 -- C Function: scm_read_line (port)
     Read a newline-terminated line from PORT, allocating storage as
     necessary.  The newline terminator (if any) is removed from the
     string, and a pair consisting of the line and its delimiter is
     returned.  The delimiter may be either a newline or the
     EOF-OBJECT; if `%read-line' is called at the end of file, it
     returns the pair `(#<eof> . #<eof>)'.


File: guile.info,  Node: Block Reading and Writing,  Next: Default Ports,  Prev: Line/Delimited,  Up: Input and Output

27.7 Block reading and writing
==============================

The Block-string-I/O module can be accessed with:

     (use-modules (ice-9 rw))

   It currently contains procedures that help to implement the `(scsh
rw)' module in guile-scsh.

 -- Scheme Procedure: read-string!/partial str [port_or_fdes [start
          [end]]]
 -- C Function: scm_read_string_x_partial (str, port_or_fdes, start,
          end)
     Read characters from a port or file descriptor into a string STR.
     A port must have an underlying file descriptor -- a so-called
     fport.  This procedure is scsh-compatible and can efficiently read
     large strings.  It will:

        * attempt to fill the entire string, unless the START and/or
          END arguments are supplied.  i.e., START defaults to 0 and
          END defaults to `(string-length str)'

        * use the current input port if PORT_OR_FDES is not supplied.

        * return fewer than the requested number of characters in some
          cases, e.g., on end of file, if interrupted by a signal, or if
          not all the characters are immediately available.

        * wait indefinitely for some input if no characters are
          currently available, unless the port is in non-blocking mode.

        * read characters from the port's input buffers if available,
          instead from the underlying file descriptor.

        * return `#f' if end-of-file is encountered before reading any
          characters, otherwise return the number of characters read.

        * return 0 if the port is in non-blocking mode and no characters
          are immediately available.

        * return 0 if the request is for 0 bytes, with no end-of-file
          check.

 -- Scheme Procedure: write-string/partial str [port_or_fdes [start
          [end]]]
 -- C Function: scm_write_string_partial (str, port_or_fdes, start, end)
     Write characters from a string STR to a port or file descriptor.
     A port must have an underlying file descriptor -- a so-called
     fport.  This procedure is scsh-compatible and can efficiently
     write large strings.  It will:

        * attempt to write the entire string, unless the START and/or
          END arguments are supplied.  i.e., START defaults to 0 and
          END defaults to `(string-length str)'

        * use the current output port if PORT_OF_FDES is not supplied.

        * in the case of a buffered port, store the characters in the
          port's output buffer, if all will fit.  If they will not fit
          then any existing buffered characters will be flushed before
          attempting to write the new characters directly to the
          underlying file descriptor.  If the port is in non-blocking
          mode and buffered characters can not be flushed immediately,
          then an `EAGAIN' system-error exception will be raised (Note:
          scsh does not support the use of non-blocking buffered ports.)

        * write fewer than the requested number of characters in some
          cases, e.g., if interrupted by a signal or if not all of the
          output can be accepted immediately.

        * wait indefinitely for at least one character from STR to be
          accepted by the port, unless the port is in non-blocking mode.

        * return the number of characters accepted by the port.

        * return 0 if the port is in non-blocking mode and can not
          accept at least one character from STR immediately

        * return 0 immediately if the request size is 0 bytes.


File: guile.info,  Node: Default Ports,  Next: Port Types,  Prev: Block Reading and Writing,  Up: Input and Output

27.8 Default Ports for Input, Output and Errors
===============================================

 -- Scheme Procedure: current-input-port
 -- C Function: scm_current_input_port ()
     Return the current input port.  This is the default port used by
     many input procedures.  Initially, `current-input-port' returns
     the "standard input" in Unix and C terminology.

 -- Scheme Procedure: current-output-port
 -- C Function: scm_current_output_port ()
     Return the current output port.  This is the default port used by
     many output procedures.  Initially, `current-output-port' returns
     the "standard output" in Unix and C terminology.

 -- Scheme Procedure: current-error-port
 -- C Function: scm_current_error_port ()
     Return the port to which errors and warnings should be sent (the
     "standard error" in Unix and C terminology).

 -- Scheme Procedure: set-current-input-port port
 -- Scheme Procedure: set-current-output-port port
 -- Scheme Procedure: set-current-error-port port
 -- C Function: scm_set_current_input_port (port)
 -- C Function: scm_set_current_output_port (port)
 -- C Function: scm_set_current_error_port (port)
     Change the ports returned by `current-input-port',
     `current-output-port' and `current-error-port', respectively, so
     that they use the supplied PORT for input or output.

 -- Scheme Procedure: set-current-output-port port
     Set the current default output port to PORT.

 -- Scheme Procedure: set-current-error-port port
     Set the current default error port to PORT.


File: guile.info,  Node: Port Types,  Next: I/O Extensions,  Prev: Default Ports,  Up: Input and Output

27.9 Types of Port
==================

[Types of port; how to make them.]

* Menu:

* File Ports:: Ports on an operating system file.
* String Ports:: Ports on a Scheme string.
* Soft Ports:: Ports on arbitrary Scheme procedures.
* Void Ports:: Ports on nothing at all.


File: guile.info,  Node: File Ports,  Next: String Ports,  Up: Port Types

27.9.1 File Ports
-----------------

The following procedures are used to open file ports.  See also *Note
open: Ports and File Descriptors, for an interface to the Unix `open'
system call.

 -- Scheme Procedure: open-file filename mode
 -- C Function: scm_open_file (filename, mode)
     Open the file whose name is FILENAME, and return a port
     representing that file.  The attributes of the port are determined
     by the MODE string.  The way in which this is interpreted is
     similar to C stdio.  The first character must be one of the
     following:
    `r'
          Open an existing file for input.

    `w'
          Open a file for output, creating it if it doesn't already
          exist or removing its contents if it does.

    `a'
          Open a file for output, creating it if it doesn't already
          exist.  All writes to the port will go to the end of the file.
          The "append mode" can be turned off while the port is in use
          *note fcntl: Ports and File Descriptors.
     The following additional characters can be appended:
    `+'
          Open the port for both input and output.  E.g., `r+': open an
          existing file for both input and output.

    `0'
          Create an "unbuffered" port.  In this case input and output
          operations are passed directly to the underlying port
          implementation without additional buffering.  This is likely
          to slow down I/O operations.  The buffering mode can be
          changed while a port is in use *note setvbuf: Ports and File
          Descriptors.

    `l'
          Add line-buffering to the port.  The port output buffer will
          be automatically flushed whenever a newline character is
          written.
     In theory we could create read/write ports which were buffered in
     one direction only.  However this isn't included in the current
     interfaces.  If a file cannot be opened with the access requested,
     `open-file' throws an exception.

 -- Scheme Procedure: open-input-file filename
     Open FILENAME for input.  Equivalent to
          (open-file FILENAME "r")

 -- Scheme Procedure: open-output-file filename
     Open FILENAME for output.  Equivalent to
          (open-file FILENAME "w")

 -- Scheme Procedure: call-with-input-file file proc
     PROC should be a procedure of one argument, and FILE should be a
     string naming a file.  The file must already exist. These
     procedures call PROC with one argument: the port obtained by
     opening the named file for input or output.  If the file cannot be
     opened, an error is signalled.  If the procedure returns, then the
     port is closed automatically and the value yielded by the
     procedure is returned.  If the procedure does not return, then the
     port will not be closed automatically unless it is possible to
     prove that the port will never again be used for a read or write
     operation.

 -- Scheme Procedure: call-with-output-file file proc
     PROC should be a procedure of one argument, and FILE should be a
     string naming a file.  The behaviour is unspecified if the file
     already exists. These procedures call PROC with one argument: the
     port obtained by opening the named file for input or output.  If
     the file cannot be opened, an error is signalled.  If the
     procedure returns, then the port is closed automatically and the
     value yielded by the procedure is returned.  If the procedure does
     not return, then the port will not be closed automatically unless
     it is possible to prove that the port will never again be used for
     a read or write operation.

 -- Scheme Procedure: with-input-from-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The file must already exist. The file is
     opened for input, an input port connected to it is made the
     default value returned by `current-input-port', and the THUNK is
     called with no arguments.  When the THUNK returns, the port is
     closed and the previous default is restored.  Returns the value
     yielded by THUNK.  If an escape procedure is used to escape from
     the continuation of these procedures, their behavior is
     implementation dependent.

 -- Scheme Procedure: with-output-to-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The effect is unspecified if the file
     already exists.  The file is opened for output, an output port
     connected to it is made the default value returned by
     `current-output-port', and the THUNK is called with no arguments.
     When the THUNK returns, the port is closed and the previous
     default is restored.  Returns the value yielded by THUNK.  If an
     escape procedure is used to escape from the continuation of these
     procedures, their behavior is implementation dependent.

 -- Scheme Procedure: with-error-to-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a
     string naming a file.  The effect is unspecified if the file
     already exists.  The file is opened for output, an output port
     connected to it is made the default value returned by
     `current-error-port', and the THUNK is called with no arguments.
     When the THUNK returns, the port is closed and the previous
     default is restored.  Returns the value yielded by THUNK.  If an
     escape procedure is used to escape from the continuation of these
     procedures, their behavior is implementation dependent.

 -- Scheme Procedure: port-mode port
 -- C Function: scm_port_mode (port)
     Return the port modes associated with the open port PORT.  These
     will not necessarily be identical to the modes used when the port
     was opened, since modes such as "append" which are used only
     during port creation are not retained.

 -- Scheme Procedure: port-filename port
 -- C Function: scm_port_filename (port)
     Return the filename associated with PORT.  This function returns
     the strings "standard input", "standard output" and "standard
     error" when called on the current input, output and error ports
     respectively.

 -- Scheme Procedure: set-port-filename! port filename
 -- C Function: scm_set_port_filename_x (port, filename)
     Change the filename associated with PORT, using the current input
     port if none is specified.  Note that this does not change the
     port's source of data, but only the value that is returned by
     `port-filename' and reported in diagnostic output.

 -- Scheme Procedure: file-port? obj
 -- C Function: scm_file_port_p (obj)
     Determine whether OBJ is a port that is related to a file.


File: guile.info,  Node: String Ports,  Next: Soft Ports,  Prev: File Ports,  Up: Port Types

27.9.2 String Ports
-------------------

The following allow string ports to be opened by analogy to R4R* file
port facilities:

 -- Scheme Procedure: call-with-output-string proc
 -- C Function: scm_call_with_output_string (proc)
     Calls the one-argument procedure PROC with a newly created output
     port.  When the function returns, the string composed of the
     characters written into the port is returned.  PROC should not
     close the port.

 -- Scheme Procedure: call-with-input-string string proc
 -- C Function: scm_call_with_input_string (string, proc)
     Calls the one-argument procedure PROC with a newly created input
     port from which STRING's contents may be read.  The value yielded
     by the PROC is returned.

 -- Scheme Procedure: with-output-to-string thunk
     Calls the zero-argument procedure THUNK with the current output
     port set temporarily to a new string port.  It returns a string
     composed of the characters written to the current output.

 -- Scheme Procedure: with-input-from-string string thunk
     Calls the zero-argument procedure THUNK with the current input
     port set temporarily to a string port opened on the specified
     STRING.  The value yielded by THUNK is returned.

 -- Scheme Procedure: open-input-string str
 -- C Function: scm_open_input_string (str)
     Take a string and return an input port that delivers characters
     from the string. The port can be closed by `close-input-port',
     though its storage will be reclaimed by the garbage collector if
     it becomes inaccessible.

 -- Scheme Procedure: open-output-string
 -- C Function: scm_open_output_string ()
     Return an output port that will accumulate characters for
     retrieval by `get-output-string'. The port can be closed by the
     procedure `close-output-port', though its storage will be
     reclaimed by the garbage collector if it becomes inaccessible.

 -- Scheme Procedure: get-output-string port
 -- C Function: scm_get_output_string (port)
     Given an output port created by `open-output-string', return a
     string consisting of the characters that have been output to the
     port so far.

     `get-output-string' must be used before closing PORT, once closed
     the string cannot be obtained.

   A string port can be used in many procedures which accept a port but
which are not dependent on implementation details of fports.  E.g.,
seeking and truncating will work on a string port, but trying to
extract the file descriptor number will fail.


File: guile.info,  Node: Soft Ports,  Next: Void Ports,  Prev: String Ports,  Up: Port Types

27.9.3 Soft Ports
-----------------

A "soft-port" is a port based on a vector of procedures capable of
accepting or delivering characters.  It allows emulation of I/O ports.

 -- Scheme Procedure: make-soft-port pv modes
 -- C Function: scm_make_soft_port (pv, modes)
     Return a port capable of receiving or delivering characters as
     specified by the MODES string (*note open-file: File Ports.).  PV
     must be a vector of length 5.  Its components are as follows:

       0. procedure accepting one character for output

       1. procedure accepting a string for output

       2. thunk for flushing output

       3. thunk for getting one character

       4. thunk for closing port (not by garbage collection)

     For an output-only port only elements 0, 1, 2, and 4 need be
     procedures.  For an input-only port only elements 3 and 4 need be
     procedures.  Thunks 2 and 4 can instead be `#f' if there is no
     useful operation for them to perform.

     If thunk 3 returns `#f' or an `eof-object' (*note eof-object?:
     (r5rs)Input.) it indicates that the port has reached end-of-file.
     For example:

          (define stdout (current-output-port))
          (define p (make-soft-port
                     (vector
                      (lambda (c) (write c stdout))
                      (lambda (s) (display s stdout))
                      (lambda () (display "." stdout))
                      (lambda () (char-upcase (read-char)))
                      (lambda () (display "@" stdout)))
                     "rw"))

          (write p p) => #<input-output: soft 8081e20>


File: guile.info,  Node: Void Ports,  Prev: Soft Ports,  Up: Port Types

27.9.4 Void Ports
-----------------

This kind of port causes any data to be discarded when written to, and
always returns the end-of-file object when read from.

 -- Scheme Procedure: %make-void-port mode
 -- C Function: scm_sys_make_void_port (mode)
     Create and return a new void port.  A void port acts like
     `/dev/null'.  The MODE argument specifies the input/output modes
     for this port: see the documentation for `open-file' in *Note File
     Ports::.


File: guile.info,  Node: I/O Extensions,  Prev: Port Types,  Up: Input and Output

27.10 Using and Extending Ports in C
====================================

* Menu:

* C Port Interface:: Using ports from C.
* Port Implementation:: How to implement a new port type in C.


File: guile.info,  Node: C Port Interface,  Next: Port Implementation,  Up: I/O Extensions

27.10.1 C Port Interface
------------------------

This section describes how to use Scheme ports from C.

27.10.1.1 Port basics
.....................

There are two main data structures.  A port type object (ptob) is of
type `scm_ptob_descriptor'.  A port instance is of type `scm_port'.
Given an `SCM' variable which points to a port, the corresponding C
port object can be obtained using the `SCM_PTAB_ENTRY' macro.  The ptob
can be obtained by using `SCM_PTOBNUM' to give an index into the
`scm_ptobs' global array.

27.10.1.2 Port buffers
......................

An input port always has a read buffer and an output port always has a
write buffer.  However the size of these buffers is not guaranteed to be
more than one byte (e.g., the `shortbuf' field in `scm_port' which is
used when no other buffer is allocated).  The way in which the buffers
are allocated depends on the implementation of the ptob.  For example
in the case of an fport, buffers may be allocated with malloc when the
port is created, but in the case of an strport the underlying string is
used as the buffer.

27.10.1.3 The `rw_random' flag
..............................

Special treatment is required for ports which can be seeked at random.
Before various operations, such as seeking the port or changing from
input to output on a bidirectional port or vice versa, the port
implementation must be given a chance to update its state.  The write
buffer is updated by calling the `flush' ptob procedure and the input
buffer is updated by calling the `end_input' ptob procedure.  In the
case of an fport, `flush' causes buffered output to be written to the
file descriptor, while `end_input' causes the descriptor position to be
adjusted to account for buffered input which was never read.

   The special treatment must be performed if the `rw_random' flag in
the port is non-zero.

27.10.1.4 The `rw_active' variable
..................................

The `rw_active' variable in the port is only used if `rw_random' is
set.  It's defined as an enum with the following values:

`SCM_PORT_READ'
     the read buffer may have unread data.

`SCM_PORT_WRITE'
     the write buffer may have unwritten data.

`SCM_PORT_NEITHER'
     neither the write nor the read buffer has data.

27.10.1.5 Reading from a port.
..............................

To read from a port, it's possible to either call existing libguile
procedures such as `scm_getc' and `scm_read_line' or to read data from
the read buffer directly.  Reading from the buffer involves the
following steps:

  1. Flush output on the port, if `rw_active' is `SCM_PORT_WRITE'.

  2. Fill the read buffer, if it's empty, using `scm_fill_input'.

  3. Read the data from the buffer and update the read position in the
     buffer.  Steps 2) and 3) may be repeated as many times as required.

  4. Set rw_active to `SCM_PORT_READ' if `rw_random' is set.

  5. update the port's line and column counts.

27.10.1.6 Writing to a port.
............................

To write data to a port, calling `scm_lfwrite' should be sufficient for
most purposes.  This takes care of the following steps:

  1. End input on the port, if `rw_active' is `SCM_PORT_READ'.

  2. Pass the data to the ptob implementation using the `write' ptob
     procedure.  The advantage of using the ptob `write' instead of
     manipulating the write buffer directly is that it allows the data
     to be written in one operation even if the port is using the
     single-byte `shortbuf'.

  3. Set `rw_active' to `SCM_PORT_WRITE' if `rw_random' is set.


File: guile.info,  Node: Port Implementation,  Prev: C Port Interface,  Up: I/O Extensions

27.10.2 Port Implementation
---------------------------

This section describes how to implement a new port type in C.

   As described in the previous section, a port type object (ptob) is a
structure of type `scm_ptob_descriptor'.  A ptob is created by calling
`scm_make_port_type'.

   All of the elements of the ptob, apart from `name', are procedures
which collectively implement the port behaviour.  Creating a new port
type mostly involves writing these procedures.

   `scm_make_port_type' initializes three elements of the structure
(`name', `fill_input' and `write') from its arguments.  The remaining
elements are initialized with default values and can be set later if
required.

`name'
     A pointer to a NUL terminated string: the name of the port type.
     This is the only element of `scm_ptob_descriptor' which is not a
     procedure.  Set via the first argument to `scm_make_port_type'.

`mark'
     Called during garbage collection to mark any SCM objects that a
     port object may contain.  It doesn't need to be set unless the
     port has `SCM' components.  Set using `scm_set_port_mark'.

`free'
     Called when the port is collected during gc.  It should free any
     resources used by the port.  Set using `scm_set_port_free'.

`print'
     Called when `write' is called on the port object, to print a port
     description.  e.g., for an fport it may produce something like:
     `#<input: /etc/passwd 3>'.   Set using `scm_set_port_print'.

`equalp'
     Not used at present.  Set using `scm_set_port_equalp'.

`close'
     Called when the port is closed, unless it was collected during gc.
     It should free any resources used by the port.  Set using
     `scm_set_port_close'.

`write'
     Accept data which is to be written using the port.  The port
     implementation may choose to buffer the data instead of processing
     it directly.  Set via the third argument to `scm_make_port_type'.

`flush'
     Complete the processing of buffered output data.  Reset the value
     of `rw_active' to `SCM_PORT_NEITHER'.  Set using
     `scm_set_port_flush'.

`end_input'
     Perform any synchronization required when switching from input to
     output on the port.  Reset the value of `rw_active' to
     `SCM_PORT_NEITHER'.  Set using `scm_set_port_end_input'.

`fill_input'
     Read new data into the read buffer and return the first character.
     It can be assumed that the read buffer is empty when this
     procedure is called.  Set via the second argument to
     `scm_make_port_type'.

`input_waiting'
     Return a lower bound on the number of bytes that could be read
     from the port without blocking.  It can be assumed that the
     current state of `rw_active' is `SCM_PORT_NEITHER'.  Set using
     `scm_set_port_input_waiting'.

`seek'
     Set the current position of the port.  The procedure can not make
     any assumptions about the value of `rw_active' when it's called.
     It can reset the buffers first if desired by using something like:

                if (pt->rw_active == SCM_PORT_READ)
          	scm_end_input (object);
                else if (pt->rw_active == SCM_PORT_WRITE)
          	ptob->flush (object);

     However note that this will have the side effect of discarding any
     data in the unread-char buffer, in addition to any side effects
     from the `end_input' and `flush' ptob procedures.  This is
     undesirable when seek is called to measure the current position of
     the port, i.e., `(seek p 0 SEEK_CUR)'.  The libguile fport and
     string port implementations take care to avoid this problem.

     The procedure is set using `scm_set_port_seek'.

`truncate'
     Truncate the port data to be specified length.  It can be assumed
     that the current state of `rw_active' is `SCM_PORT_NEITHER'.  Set
     using `scm_set_port_truncate'.



File: guile.info,  Node: Read/Load/Eval,  Next: Memory Management,  Prev: Input and Output,  Up: Top

28 Reading and Evaluating Scheme Code
*************************************

This chapter describes Guile functions that are concerned with reading,
loading and evaluating Scheme code at run time.

* Menu:

* Scheme Syntax::               Standard and extended Scheme syntax.
* Scheme Read::                 Reading Scheme code.
* Fly Evaluation::              Procedures for on the fly evaluation.
* Loading::                     Loading Scheme code from file.
* Delayed Evaluation::          Postponing evaluation until it is needed.
* Local Evaluation::            Evaluation in a local environment.
* Evaluator Behaviour::         Modifying Guile's evaluator.


File: guile.info,  Node: Scheme Syntax,  Next: Scheme Read,  Up: Read/Load/Eval

28.1 Scheme Syntax: Standard and Guile Extensions
=================================================

* Menu:

* Expression Syntax::
* Comments::
* Block Comments::
* Case Sensitivity::
* Keyword Syntax::
* Reader Extensions::


File: guile.info,  Node: Expression Syntax,  Next: Comments,  Up: Scheme Syntax

28.1.1 Expression Syntax
------------------------


File: guile.info,  Node: Comments,  Next: Block Comments,  Prev: Expression Syntax,  Up: Scheme Syntax

28.1.2 Comments
---------------

Comments in Scheme source files are written by starting them with a
semicolon character (`;').  The comment then reaches up to the end of
the line.  Comments can begin at any column, and the may be inserted on
the same line as Scheme code.

     ; Comment
     ;; Comment too
     (define x 1)        ; Comment after expression
     (let ((y 1))
       ;; Display something.
       (display y)
     ;;; Comment at left margin.
       (display (+ y 1)))

   It is common to use a single semicolon for comments following
expressions on a line, to use two semicolons for comments which are
indented like code, and three semicolons for comments which start at
column 0, even if they are inside an indented code block.  This
convention is used when indenting code in Emacs' Scheme mode.


File: guile.info,  Node: Block Comments,  Next: Case Sensitivity,  Prev: Comments,  Up: Scheme Syntax

28.1.3 Block Comments
---------------------

In addition to the standard line comments defined by R5RS, Guile has
another comment type for multiline comments, called "block comments".
This type of comment begins with the character sequence `#!' and ends
with the characters `!#', which must appear on a line of their own.
These comments are compatible with the block comments in the Scheme
Shell `scsh' (*note The Scheme shell (scsh)::).  The characters `#!'
were chosen because they are the magic characters used in shell scripts
for indicating that the name of the program for executing the script
follows on the same line.

   Thus a Guile script often starts like this.

     #! /usr/local/bin/guile -s
     !#

   More details on Guile scripting can be found in the scripting section
(*note Guile Scripting::).


File: guile.info,  Node: Case Sensitivity,  Next: Keyword Syntax,  Prev: Block Comments,  Up: Scheme Syntax

28.1.4 Case Sensitivity
-----------------------

Scheme as defined in R5RS is not case sensitive when reading symbols.
Guile, on the contrary is case sensitive by default, so the identifiers

     guile-whuzzy
     Guile-Whuzzy

   are the same in R5RS Scheme, but are different in Guile.

   It is possible to turn off case sensitivity in Guile by setting the
reader option `case-insensitive'.  More on reader options can be found
at (*note Reader options::).

     (read-enable 'case-insensitive)

   Note that this is seldom a problem, because Scheme programmers tend
not to use uppercase letters in their identifiers anyway.


File: guile.info,  Node: Keyword Syntax,  Next: Reader Extensions,  Prev: Case Sensitivity,  Up: Scheme Syntax

28.1.5 Keyword Syntax
---------------------


File: guile.info,  Node: Reader Extensions,  Prev: Keyword Syntax,  Up: Scheme Syntax

28.1.6 Reader Extensions
------------------------

 -- Scheme Procedure: read-hash-extend chr proc
 -- C Function: scm_read_hash_extend (chr, proc)
     Install the procedure PROC for reading expressions starting with
     the character sequence `#' and CHR.  PROC will be called with two
     arguments:  the character CHR and the port to read further data
     from. The object returned will be the return value of `read'.


File: guile.info,  Node: Scheme Read,  Next: Fly Evaluation,  Prev: Scheme Syntax,  Up: Read/Load/Eval

28.2 Reading Scheme Code
========================

 -- Scheme Procedure: read [port]
 -- C Function: scm_read (port)
     Read an s-expression from the input port PORT, or from the current
     input port if PORT is not specified.  Any whitespace before the
     next token is discarded.

   The behaviour of Guile's Scheme reader can be modified by
manipulating its read options.  For more information about options,
*Note User level options interfaces::.  If you want to know which
reader options are available, *Note Reader options::.

 -- Scheme Procedure: read-options [setting]
     Display the current settings of the read options.  If SETTING is
     omitted, only a short form of the current read options is printed.
     Otherwise, SETTING should be one of the following symbols:
    `help'
          Display the complete option settings.

    `full'
          Like `help', but also print programmer options.

 -- Scheme Procedure: read-enable option-name
 -- Scheme Procedure: read-disable option-name
 -- Scheme Procedure: read-set! option-name value
     Modify the read options.  `read-enable' should be used with boolean
     options and switches them on, `read-disable' switches them off.
     `read-set!' can be used to set an option to a specific value.

 -- Scheme Procedure: read-options-interface [setting]
 -- C Function: scm_read_options (setting)
     Option interface for the read options. Instead of using this
     procedure directly, use the procedures `read-enable',
     `read-disable', `read-set!' and `read-options'.


File: guile.info,  Node: Fly Evaluation,  Next: Loading,  Prev: Scheme Read,  Up: Read/Load/Eval

28.3 Procedures for On the Fly Evaluation
=========================================

*Note Environments::.

 -- Scheme Procedure: eval exp module
 -- C Function: scm_eval (exp, module)
     Evaluate EXP, a list representing a Scheme expression, in the
     top-level environment specified by MODULE.  While EXP is evaluated
     (using `primitive-eval'), MODULE is made the current module.  The
     current module is reset to its previous value when EVAL returns.

 -- Scheme Procedure: interaction-environment
 -- C Function: scm_interaction_environment ()
     Return a specifier for the environment that contains
     implementation-defined bindings, typically a superset of those
     listed in the report.  The intent is that this procedure will
     return the environment in which the implementation would evaluate
     expressions dynamically typed by the user.

 -- Scheme Procedure: eval-string string
 -- C Function: scm_eval_string (string)
     Evaluate STRING as the text representation of a Scheme form or
     forms, and return whatever value they produce.  Evaluation takes
     place in the environment returned by the procedure
     `interaction-environment'.

 -- Scheme Procedure: apply:nconc2last lst
 -- C Function: scm_nconc2last (lst)
     Given a list (ARG1 ... ARGS), this function conses the ARG1 ...
     arguments onto the front of ARGS, and returns the resulting list.
     Note that ARGS is a list; thus, the argument to this function is a
     list whose last element is a list.  Note: Rather than do new
     consing, `apply:nconc2last' destroys its argument, so use with
     care.

 -- Scheme Procedure: apply proc arg1 ... args
     PROC must be a procedure and ARGS must be a list.  Call PROC with
     the elements of the list `(append (list ARG1 ...) ARGS)' as the
     actual arguments.

 -- Scheme Procedure: primitive-eval exp
 -- C Function: scm_primitive_eval (exp)
     Evaluate EXP in the top-level environment specified by the current
     module.


File: guile.info,  Node: Loading,  Next: Delayed Evaluation,  Prev: Fly Evaluation,  Up: Read/Load/Eval

28.4 Loading Scheme Code from File
==================================

 -- Scheme Procedure: load filename
     Load FILENAME and evaluate its contents in the top-level
     environment.  The load paths are not searched.  If the variable
     `%load-hook' is defined, it should be bound to a procedure that
     will be called before any code is loaded.  See documentation for
     `%load-hook' later in this section.

 -- Scheme Procedure: load-from-path filename
     Similar to `load', but searches for FILENAME in the load paths.

 -- Scheme Procedure: primitive-load filename
 -- C Function: scm_primitive_load (filename)
     Load the file named FILENAME and evaluate its contents in the
     top-level environment. The load paths are not searched; FILENAME
     must either be a full pathname or be a pathname relative to the
     current directory.  If the  variable `%load-hook' is defined, it
     should be bound to a procedure that will be called before any code
     is loaded.  See the documentation for `%load-hook' later in this
     section.

 -- Scheme Procedure: primitive-load-path filename
 -- C Function: scm_primitive_load_path (filename)
     Search %LOAD-PATH for the file named FILENAME and load it into the
     top-level environment.  If FILENAME is a relative pathname and is
     not found in the list of search paths, an error is signalled.

 -- Scheme Procedure: %search-load-path filename
 -- C Function: scm_sys_search_load_path (filename)
     Search %LOAD-PATH for the file named FILENAME, which must be
     readable by the current user.  If FILENAME is found in the list of
     paths to search or is an absolute pathname, return its full
     pathname.  Otherwise, return `#f'.  Filenames may have any of the
     optional extensions in the `%load-extensions' list;
     `%search-load-path' will try each extension automatically.

 -- Variabele: %load-hook
     A procedure to be run whenever `primitive-load' is called.  If this
     procedure is defined, it will be called with the filename argument
     that was passed to `primitive-load'.

          (define %load-hook (lambda (file)
                               (display "Loading ")
                               (display file)
                               (write-line "...."))) => undefined
          (load-from-path "foo.scm")
          -| Loading /usr/local/share/guile/site/foo.scm....


 -- Scheme Procedure: current-load-port
 -- C Function: scm_current_load_port ()
     Return the current-load-port.  The load port is used internally by
     `primitive-load'.

 -- Variabele: %load-extensions
     A list of default file extensions for files containing Scheme code.
     `%search-load-path' tries each of these extensions when looking for
     a file to load.  By default, `%load-extensions' is bound to the
     list `("" ".scm")'.


File: guile.info,  Node: Delayed Evaluation,  Next: Local Evaluation,  Prev: Loading,  Up: Read/Load/Eval

28.5 Delayed Evaluation
=======================

[delay]

 -- Scheme Procedure: promise? obj
 -- C Function: scm_promise_p (obj)
     Return true if OBJ is a promise, i.e. a delayed computation (*note
     Delayed evaluation: (r5rs.info)Delayed evaluation.).

 -- Scheme Procedure: force x
 -- C Function: scm_force (x)
     If the promise X has not been computed yet, compute and return X,
     otherwise just return the previously computed value.


File: guile.info,  Node: Local Evaluation,  Next: Evaluator Behaviour,  Prev: Delayed Evaluation,  Up: Read/Load/Eval

28.6 Local Evaluation
=====================

[the-environment]

 -- Scheme Procedure: local-eval exp [env]
 -- C Function: scm_local_eval (exp, env)
     Evaluate EXP in its environment.  If ENV is supplied, it is the
     environment in which to evaluate EXP.  Otherwise, EXP must be a
     memoized code object (in which case, its environment is implicit).


File: guile.info,  Node: Evaluator Behaviour,  Prev: Local Evaluation,  Up: Read/Load/Eval

28.7 Evaluator Behaviour
========================

The behaviour of Guile's evaluator can be modified by manipulating the
evaluator options.  For more information about options, *Note User
level options interfaces::.  If you want to know which evaluator
options are available, *Note Evaluator options::.

 -- Scheme Procedure: eval-options [setting]
     Display the current settings of the evaluator options.  If SETTING
     is omitted, only a short form of the current evaluator options is
     printed.  Otherwise, SETTING should be one of the following
     symbols:
    `help'
          Display the complete option settings.

    `full'
          Like `help', but also print programmer options.

 -- Scheme Procedure: eval-enable option-name
 -- Scheme Procedure: eval-disable option-name
 -- Scheme Procedure: eval-set! option-name value
     Modify the evaluator options.  `eval-enable' should be used with
     boolean options and switches them on, `eval-disable' switches them
     off.  `eval-set!' can be used to set an option to a specific value.

 -- Scheme Procedure: eval-options-interface [setting]
 -- C Function: scm_eval_options_interface (setting)
     Option interface for the evaluation options. Instead of using this
     procedure directly, use the procedures `eval-enable',
     `eval-disable', `eval-set!' and `eval-options'.

 -- Scheme Procedure: traps [setting]
     Display the current settings of the evaluator traps options.  If
     SETTING is omitted, only a short form of the current evaluator
     traps options is printed.  Otherwise, SETTING should be one of the
     following symbols:
    `help'
          Display the complete option settings.

    `full'
          Like `help', but also print programmer options.

 -- Scheme Procedure: trap-enable option-name
 -- Scheme Procedure: trap-disable option-name
 -- Scheme Procedure: trap-set! option-name value
     Modify the evaluator options.  `trap-enable' should be used with
     boolean options and switches them on, `trap-disable' switches them
     off.  `trap-set!' can be used to set an option to a specific value.

 -- Scheme Procedure: evaluator-traps-interface [setting]
 -- C Function: scm_evaluator_traps (setting)
     Option interface for the evaluator trap options.


File: guile.info,  Node: Memory Management,  Next: Objects,  Prev: Read/Load/Eval,  Up: Top

29 Memory Management and Garbage Collection
*******************************************

Guile uses a _garbage collector_ to manage most of its objects.  This
means that the memory used to store a Scheme string, say, is
automatically reclaimed when no one is using this string any longer.
This can work because Guile knows enough about its objects at run-time
to be able to trace all references between them.  Thus, it can find all
'live' objects (objects that are still in use) by starting from a known
set of 'root' objects and following the links that these objects have
to other objects, and so on.  The objects that are not reached by this
recursive process can be considered 'dead' and their memory can be
reused for new objects.

   When you are programming in Scheme, you don't need to worry about the
garbage collector.  When programming in C, there are a few rules that
you must follow so that the garbage collector can do its job.

* Menu:

* Garbage Collection::
* Weak References::
* Guardians::


File: guile.info,  Node: Garbage Collection,  Next: Weak References,  Up: Memory Management

29.1 Garbage Collection
=======================

 -- Scheme Procedure: gc
 -- C Function: scm_gc ()
     Scans all of SCM objects and reclaims for further use those that
     are no longer accessible.  You normally don't need to call this
     function explicitly.  It is called automatically when appropriate.

 -- Scheme Procedure: gc-stats
 -- C Function: scm_gc_stats ()
     Return an association list of statistics about Guile's current use
     of storage.

 -- Scheme Procedure: object-address obj
 -- C Function: scm_object_address (obj)
     Return an integer that for the lifetime of OBJ is uniquely
     returned by this function for OBJ

 -- Scheme Procedure: unhash-name name
     Flushes the glocs for NAME, or all glocs if NAME is `#t'.

 -- Scheme Procedure: malloc-stats
     Return an alist ((WHAT . N) ...) describing number of malloced
     objects.  WHAT is the second argument to `scm_must_malloc', N is
     the number of objects of that type currently allocated.


File: guile.info,  Node: Weak References,  Next: Guardians,  Prev: Garbage Collection,  Up: Memory Management

29.2 Weak References
====================

[FIXME: This chapter is based on Mikael Djurfeldt's answer to a
question by Michael Livshin. Any mistakes are not theirs, of course. ]

   Weak references let you attach bookkeeping information to data so
that the additional information automatically disappears when the
original data is no longer in use and gets garbage collected. In a weak
key hash, the hash entry for that key disappears as soon as the key is
no longer referenced from anywhere else. For weak value hashes, the
same happens as soon as the value is no longer in use. Entries in a
doubly weak hash disappear when either the key or the value are not
used anywhere else anymore.

   Object properties offer the same kind of functionality as weak key
hashes in many situations. (*note Object Properties::)

   Here's an example (a little bit strained perhaps, but one of the
examples is actually used in Guile):

   Assume that you're implementing a debugging system where you want to
associate information about filename and position of source code
expressions with the expressions themselves.

   Hashtables can be used for that, but if you use ordinary hash tables
it will be impossible for the scheme interpreter to "forget" old source
when, for example, a file is reloaded.

   To implement the mapping from source code expressions to positional
information it is necessary to use weak-key tables since we don't want
the expressions to be remembered just because they are in our table.

   To implement a mapping from source file line numbers to source code
expressions you would use a weak-value table.

   To implement a mapping from source code expressions to the procedures
they constitute a doubly-weak table has to be used.

* Menu:

* Weak key hashes::
* Weak vectors::


File: guile.info,  Node: Weak key hashes,  Next: Weak vectors,  Up: Weak References

29.2.1 Weak key hashes
----------------------

 -- Scheme Procedure: make-weak-key-hash-table size
 -- Scheme Procedure: make-weak-value-hash-table size
 -- Scheme Procedure: make-doubly-weak-hash-table size
 -- C Function: scm_make_weak_key_hash_table (size)
 -- C Function: scm_make_weak_value_hash_table (size)
 -- C Function: scm_make_doubly_weak_hash_table (size)
     Return a weak hash table with SIZE buckets. As with any hash
     table, choosing a good size for the table requires some caution.

     You can modify weak hash tables in exactly the same way you would
     modify regular hash tables. (*note Hash Tables::)

 -- Scheme Procedure: weak-key-hash-table? obj
 -- Scheme Procedure: weak-value-hash-table? obj
 -- Scheme Procedure: doubly-weak-hash-table? obj
 -- C Function: scm_weak_key_hash_table_p (obj)
 -- C Function: scm_weak_value_hash_table_p (obj)
 -- C Function: scm_doubly_weak_hash_table_p (obj)
     Return `#t' if OBJ is the specified weak hash table. Note that a
     doubly weak hash table is neither a weak key nor a weak value hash
     table.

 -- Scheme Procedure: make-weak-value-hash-table k

 -- Scheme Procedure: weak-value-hash-table? x

 -- Scheme Procedure: make-doubly-weak-hash-table k

 -- Scheme Procedure: doubly-weak-hash-table? x


File: guile.info,  Node: Weak vectors,  Prev: Weak key hashes,  Up: Weak References

29.2.2 Weak vectors
-------------------

Weak vectors are mainly useful in Guile's implementation of weak hash
tables.

 -- Scheme Procedure: make-weak-vector size [fill]
 -- C Function: scm_make_weak_vector (size, fill)
     Return a weak vector with SIZE elements. If the optional argument
     FILL is given, all entries in the vector will be set to FILL. The
     default value for FILL is the empty list.

 -- Scheme Procedure: weak-vector . l
 -- Scheme Procedure: list->weak-vector l
 -- C Function: scm_weak_vector (l)
     Construct a weak vector from a list: `weak-vector' uses the list
     of its arguments while `list->weak-vector' uses its only argument
     L (a list) to construct a weak vector the same way `list->vector'
     would.

 -- Scheme Procedure: weak-vector? obj
 -- C Function: scm_weak_vector_p (obj)
     Return `#t' if OBJ is a weak vector. Note that all weak hashes are
     also weak vectors.


File: guile.info,  Node: Guardians,  Prev: Weak References,  Up: Memory Management

29.3 Guardians
==============

 -- Scheme Procedure: make-guardian [greedy?]
 -- C Function: scm_make_guardian (greedy_p)
     Create a new guardian.  A guardian protects a set of objects from
     garbage collection, allowing a program to apply cleanup or other
     actions.

     `make-guardian' returns a procedure representing the guardian.
     Calling the guardian procedure with an argument adds the argument
     to the guardian's set of protected objects.  Calling the guardian
     procedure without an argument returns one of the protected objects
     which are ready for garbage collection, or `#f' if no such object
     is available.  Objects which are returned in this way are removed
     from the guardian.

     `make-guardian' takes one optional argument that says whether the
     new guardian should be greedy or sharing.  If there is any chance
     that any object protected by the guardian may be resurrected, then
     you should make the guardian greedy (this is the default).

     See R. Kent Dybvig, Carl Bruggeman, and David Eby (1993)
     "Guardians in a Generation-Based Garbage Collector".  ACM SIGPLAN
     Conference on Programming Language Design and Implementation, June
     1993.

     (the semantics are slightly different at this point, but the paper
     still (mostly) accurately describes the interface).

 -- Scheme Procedure: destroy-guardian! guardian
 -- C Function: scm_destroy_guardian_x (guardian)
     Destroys GUARDIAN, by making it impossible to put any more objects
     in it or get any objects from it.  It also unguards any objects
     guarded by GUARDIAN.

 -- Scheme Procedure: guardian-greedy? guardian
 -- C Function: scm_guardian_greedy_p (guardian)
     Return `#t' if GUARDIAN is a greedy guardian, otherwise `#f'.

 -- Scheme Procedure: guardian-destroyed? guardian
 -- C Function: scm_guardian_destroyed_p (guardian)
     Return `#t' if GUARDIAN has been destroyed, otherwise `#f'.


File: guile.info,  Node: Objects,  Next: Modules,  Prev: Memory Management,  Up: Top

30 Objects
**********

 -- Scheme Procedure: entity? obj
 -- C Function: scm_entity_p (obj)
     Return `#t' if OBJ is an entity.

 -- Scheme Procedure: operator? obj
 -- C Function: scm_operator_p (obj)
     Return `#t' if OBJ is an operator.

 -- Scheme Procedure: set-object-procedure! obj proc
 -- C Function: scm_set_object_procedure_x (obj, proc)
     Set the object procedure of OBJ to PROC.  OBJ must be either an
     entity or an operator.

 -- Scheme Procedure: make-class-object metaclass layout
 -- C Function: scm_make_class_object (metaclass, layout)
     Create a new class object of class METACLASS, with the slot layout
     specified by LAYOUT.

 -- Scheme Procedure: make-subclass-object class layout
 -- C Function: scm_make_subclass_object (class, layout)
     Create a subclass object of CLASS, with the slot layout specified
     by LAYOUT.


File: guile.info,  Node: Modules,  Next: Scheduling,  Prev: Objects,  Up: Top

31 Modules
**********

When programs become large, naming conflicts can occur when a function
or global variable defined in one file has the same name as a function
or global variable in another file.  Even just a _similarity_ between
function names can cause hard-to-find bugs, since a programmer might
type the wrong function name.

   The approach used to tackle this problem is called _information
encapsulation_, which consists of packaging functional units into a
given name space that is clearly separated from other name spaces.  

   The language features that allow this are usually called _the module
system_ because programs are broken up into modules that are compiled
separately (or loaded separately in an interpreter).

   Older languages, like C, have limited support for name space
manipulation and protection.  In C a variable or function is public by
default, and can be made local to a module with the `static' keyword.
But you cannot reference public variables and functions from another
module with different names.

   More advanced module systems have become a common feature in recently
designed languages: ML, Python, Perl, and Modula 3 all allow the
_renaming_ of objects from a foreign module, so they will not clutter
the global name space.  

   In addition, Guile offers variables as first-class objects.  They can
be used for interacting with the module system.

* Menu:

* provide and require::         The SLIB feature mechanism.
* Environments::                R5RS top-level environments.
* The Guile module system::     How Guile does it.
* Dynamic Libraries::           Loading libraries of compiled code at run time.
* Variables::                   First-class variables.


File: guile.info,  Node: provide and require,  Next: Environments,  Up: Modules

31.1 provide and require
========================

Aubrey Jaffer, mostly to support his portable Scheme library SLIB,
implemented a provide/require mechanism for many Scheme implementations.
Library files in SLIB _provide_ a feature, and when user programs
_require_ that feature, the library file is loaded in.

   For example, the file `random.scm' in the SLIB package contains the
line

     (provide 'random)

   so to use its procedures, a user would type

     (require 'random)

   and they would magically become available, _but still have the same
names!_  So this method is nice, but not as good as a full-featured
module system.

   When SLIB is used with Guile, provide and require can be used to
access its facilities.


File: guile.info,  Node: Environments,  Next: The Guile module system,  Prev: provide and require,  Up: Modules

31.2 Environments
=================

Scheme, as defined in R5RS, does _not_ have a full module system.
However it does define the concept of a top-level "environment".  Such
an environment maps identifiers (symbols) to Scheme objects such as
procedures and lists: *Note About Closure::.  In other words, it
implements a set of "bindings".

   Environments in R5RS can be passed as the second argument to `eval'
(*note Fly Evaluation::).  Three procedures are defined to return
environments: `scheme-report-environment', `null-environment' and
`interaction-environment' (*note Fly Evaluation::).

   In addition, in Guile any module can be used as an R5RS environment,
i.e., passed as the second argument to `eval'.

 -- Scheme Procedure: scheme-report-environment version
 -- Scheme Procedure: null-environment version
     VERSION must be the exact integer `5', corresponding to revision 5
     of the Scheme report (the Revised^5 Report on Scheme).
     `scheme-report-environment' returns a specifier for an environment
     that is empty except for all bindings defined in the report that
     are either required or both optional and supported by the
     implementation. `null-environment' returns a specifier for an
     environment that is empty except for the (syntactic) bindings for
     all syntactic keywords defined in the report that are either
     required or both optional and supported by the implementation.

     Currently Guile does not support values of VERSION for other
     revisions of the report.

     The effect of assigning (through the use of `eval') a variable
     bound in a `scheme-report-environment' (for example `car') is
     unspecified.  Currently the environments specified by
     `scheme-report-environment' are not immutable in Guile.


File: guile.info,  Node: The Guile module system,  Next: Dynamic Libraries,  Prev: Environments,  Up: Modules

31.3 The Guile module system
============================

The Guile module system extends the concept of environments, discussed
in the previous section, with mechanisms to define, use and customise
sets of bindings.

   In 1996 Tom Lord implemented a full-featured module system for Guile
which allows loading Scheme source files into a private name space.
This system has been in available since at least Guile version 1.1.

   For Guile version 1.5.0 and later, the system has been improved to
have better integration from C code, more fine-grained user control
over interfaces, and documentation.

   Although it is anticipated that the module system implementation will
change in the future, the Scheme programming interface described in this
manual should be considered stable.  The C programming interface is
considered relatively stable, although at the time of this writing,
there is still some flux.

* Menu:

* General Information about Modules::  Guile module basics.
* Using Guile Modules::         How to use existing modules.
* Creating Guile Modules::      How to package your code into modules.
* Module System Quirks::        Strange things to be aware of.
* Included Guile Modules::      Which modules come with Guile?
* Accessing Modules from C::    How to work with modules with C code.


File: guile.info,  Node: General Information about Modules,  Next: Using Guile Modules,  Up: The Guile module system

31.3.1 General Information about Modules
----------------------------------------

A Guile module can be thought of as a collection of named procedures,
variables and macros.  More precisely, it is a set of "bindings" of
symbols (names) to Scheme objects.

   An environment is a mapping from identifiers (or symbols) to
locations, i.e., a set of bindings.  There are top-level environments
and lexical environments.  The environment in which a lambda is
executed is remembered as part of its definition.

   Within a module, all bindings are visible.  Certain bindings can be
declared "public", in which case they are added to the module's
so-called "export list"; this set of public bindings is called the
module's "public interface" (*note Creating Guile Modules::).

   A client module "uses" a providing module's bindings by either
accessing the providing module's public interface, or by building a
custom interface (and then accessing that).  In a custom interface, the
client module can "select" which bindings to access and can also
algorithmically "rename" bindings.  In contrast, when using the
providing module's public interface, the entire export list is available
without renaming (*note Using Guile Modules::).

   To use a module, it must be found and loaded.  All Guile modules
have a unique "module name", which is a list of one or more symbols.
Examples are `(ice-9 popen)' or `(srfi srfi-11)'.  When Guile searches
for the code of a module, it constructs the name of the file to load by
concatenating the name elements with slashes between the elements and
appending a number of file name extensions from the list
`%load-extensions' (*note Loading::).  The resulting file name is then
searched in all directories in the variable `%load-path' (*note Build
Config::).  For example, the `(ice-9 popen)' module would result in the
filename `ice-9/popen.scm' and searched in the installation directories
of Guile and in all other directories in the load path.

   Every module has a so-called syntax transformer associated with it.
This is a procedure which performs all syntax transformation for the
time the module is read in and evaluated.  When working with modules,
you can manipulate the current syntax transformer using the
`use-syntax' syntactic form or the `#:use-syntax' module definition
option (*note Creating Guile Modules::).

   Please note that there are some problems with the current module
system you should keep in mind (*note Module System Quirks::).  We hope
to address these eventually.


File: guile.info,  Node: Using Guile Modules,  Next: Creating Guile Modules,  Prev: General Information about Modules,  Up: The Guile module system

31.3.2 Using Guile Modules
--------------------------

To use a Guile module is to access either its public interface or a
custom interface (*note General Information about Modules::).  Both
types of access are handled by the syntactic form `use-modules', which
accepts one or more interface specifications and, upon evaluation,
arranges for those interfaces to be available to the current module.
This process may include locating and loading code for a given module if
that code has not yet been loaded, following %load-path (*note Build
Config::).

   An "interface specification" has one of two forms.  The first
variation is simply to name the module, in which case its public
interface is the one accessed.  For example:

     (use-modules (ice-9 popen))

   Here, the interface specification is `(ice-9 popen)', and the result
is that the current module now has access to `open-pipe', `close-pipe',
`open-input-pipe', and so on (*note Included Guile Modules::).

   Note in the previous example that if the current module had already
defined `open-pipe', that definition would be overwritten by the
definition in `(ice-9 popen)'.  For this reason (and others), there is
a second variation of interface specification that not only names a
module to be accessed, but also selects bindings from it and renames
them to suit the current module's needs.  For example:

     (use-modules ((ice-9 popen)
                   :select ((open-pipe . pipe-open) close-pipe)
                   :renamer (symbol-prefix-proc 'unixy:)))

   Here, the interface specification is more complex than before, and
the result is that a custom interface with only two bindings is created
and subsequently accessed by the current module.  The mapping of old to
new names is as follows:

     (ice-9 popen) sees:             current module sees:
     open-pipe                       unixy:pipe-open
     close-pipe                      unixy:close-pipe

   This example also shows how to use the convenience procedure
`symbol-prefix-proc'.

 -- Scheme Procedure: symbol-prefix-proc prefix-sym
     Return a procedure that prefixes its arg (a symbol) with
     PREFIX-SYM.

 -- syntax: use-modules spec ...
     Resolve each interface specification SPEC into an interface and
     arrange for these to be accessible by the current module.  The
     return value is unspecified.

     SPEC can be a list of symbols, in which case it names a module
     whose public interface is found and used.

     SPEC can also be of the form:

           (MODULE-NAME [:select SELECTION] [:renamer RENAMER])

     in which case a custom interface is newly created and used.
     MODULE-NAME is a list of symbols, as above; SELECTION is a list of
     selection-specs; and RENAMER is a procedure that takes a symbol
     and returns its new name.  A selection-spec is either a symbol or
     a pair of symbols `(ORIG . SEEN)', where ORIG is the name in the
     used module and SEEN is the name in the using module.  Note that
     SEEN is also passed through RENAMER.

     The `:select' and `:renamer' clauses are optional.  If both are
     omitted, the returned interface has no bindings.  If the `:select'
     clause is omitted, RENAMER operates on the used module's public
     interface.

     Signal error if module name is not resolvable.

 -- syntax: use-syntax module-name
     Load the module `module-name' and use its system transformer as
     the system transformer for the currently defined module, as well
     as installing it as the current system transformer.


File: guile.info,  Node: Creating Guile Modules,  Next: Module System Quirks,  Prev: Using Guile Modules,  Up: The Guile module system

31.3.3 Creating Guile Modules
-----------------------------

When you want to create your own modules, you have to take the following
steps:

   * Create a Scheme source file and add all variables and procedures
     you wish to export, or which are required by the exported
     procedures.

   * Add a `define-module' form at the beginning.

   * Export all bindings which should be in the public interface, either
     by using `define-public' or `export' (both documented below).

 -- syntax: define-module module-name [options ...]
     MODULE-NAME is of the form `(hierarchy file)'.  One example of
     this is

          (define-module (ice-9 popen))

     `define-module' makes this module available to Guile programs under
     the given MODULE-NAME.

     The OPTIONS are keyword/value pairs which specify more about the
     defined module.  The recognized options and their meaning is shown
     in the following table.

    `#:use-module INTERFACE-SPECIFICATION'
          Equivalent to a `(use-modules INTERFACE-SPECIFICATION)'
          (*note Using Guile Modules::).

    `#:use-syntax MODULE'
          Use MODULE when loading the currently defined module, and
          install it as the syntax transformer.

    `#:autoload MODULE SYMBOL'
          Load MODULE whenever SYMBOL is accessed.

    `#:export LIST'
          Export all identifiers in LIST, which must be a list of
          symbols.  This is equivalent to `(export LIST)' in the module
          body.

    `#:no-backtrace'
          Tell Guile not to record information for procedure backtraces
          when executing the procedures in this module.

    `#:pure'
          Create a "pure" module, that is a module which does not
          contain any of the standard procedure bindings except for the
          syntax forms.  This is useful if you want to create "safe"
          modules, that is modules which do not know anything about
          dangerous procedures.


 -- syntax: export variable ...
     Add all VARIABLEs (which must be symbols) to the list of exported
     bindings of the current module.

 -- syntax: define-public ...
     Equivalent to `(begin (define foo ...) (export foo))'.


File: guile.info,  Node: Module System Quirks,  Next: Included Guile Modules,  Prev: Creating Guile Modules,  Up: The Guile module system

31.3.4 Module System Quirks
---------------------------

Although the programming interfaces are relatively stable, the Guile
module system itself is still evolving.  Here are some situations where
usage surpasses design.

   * When using a module which exports a macro definition, the other
     module must export all bindings the macro expansion uses, too,
     because the expanded code would otherwise not be able to see these
     definitions and issue a "variable unbound" error, or worse, would
     use another binding which might be present in the scope of the
     expansion.

   * When two or more used modules export bindings with the same names,
     the last accessed module wins, and the exported binding of that
     last module will silently be used.  This might lead to
     hard-to-find errors because wrong procedures or variables are
     used.  To avoid this kind of "name-clash" situation, use a custom
     interface specification (*note Using Guile Modules::).  (We
     include this entry for the possible benefit of users of Guile
     versions previous to 1.5.0, when custom interfaces were added to
     the module system.)

   * [Add other quirks here.]



File: guile.info,  Node: Included Guile Modules,  Next: Accessing Modules from C,  Prev: Module System Quirks,  Up: The Guile module system

31.3.5 Included Guile Modules
-----------------------------

Some modules are included in the Guile distribution; here are references
to the entries in this manual which describe them in more detail:

*boot-9*
     boot-9 is Guile's initialization module, and it is always loaded
     when Guile starts up.

*(ice-9 debug)*
     Mikael Djurfeldt's source-level debugging support for Guile (*note
     Debugging Features::).

*(ice-9 threads)*
     Guile's support for multi threaded execution (*note Scheduling::).

*(ice-9 rdelim)*
     Line- and character-delimited input (*note Line/Delimited::).

*(ice-9 rw)*
     Block string input/output (*note Block Reading and Writing::).

*(ice-9 documentation)*
     Online documentation (REFFIXME).

*(srfi srfi-1)*
     A library providing a lot of useful list and pair processing
     procedures (*note SRFI-1::).

*(srfi srfi-2)*
     Support for `and-let*' (*note SRFI-2::).

*(srfi srfi-4)*
     Support for homogeneous numeric vectors (*note SRFI-4::).

*(srfi srfi-6)*
     Support for some additional string port procedures (*note
     SRFI-6::).

*(srfi srfi-8)*
     Multiple-value handling with `receive' (*note SRFI-8::).

*(srfi srfi-9)*
     Record definition with `define-record-type' (*note SRFI-9::).

*(srfi srfi-10)*
     Read hash extension `#,()' (*note SRFI-10::).

*(srfi srfi-11)*
     Multiple-value handling with `let-values' and `let-values*' (*note
     SRFI-11::).

*(srfi srfi-13)*
     String library (*note SRFI-13::).

*(srfi srfi-14)*
     Character-set library (*note SRFI-14::).

*(srfi srfi-17)*
     Getter-with-setter support (*note SRFI-17::).

*(ice-9 slib)*
     This module contains hooks for using Aubrey Jaffer's portable
     Scheme library SLIB from Guile (*note SLIB::).

*(ice-9 jacal)*
     This module contains hooks for using Aubrey Jaffer's symbolic math
     package Jacal from Guile (*note JACAL::).


File: guile.info,  Node: Accessing Modules from C,  Prev: Included Guile Modules,  Up: The Guile module system

31.3.6 Accessing Modules from C
-------------------------------

The last sections have described how modules are used in Scheme code,
which is the recommended way of creating and accessing modules.  You
can also work with modules from C, but it is more cumbersome.

   The following procedures are available.

 -- C Procedure: SCM scm_current_module ()
     Return the module that is the _current module_.

 -- C Procedure: SCM scm_set_current_module (SCM MODULE)
     Set the current module to MODULE and return the previous current
     module.

 -- C Procedure: SCM scm_c_call_with_current_module (SCM MODULE, SCM
          (*FUNC)(void *), void *DATA)
     Call FUNC and make MODULE the current module during the call.  The
     argument DATA is passed to FUNC.  The return value of
     `scm_c_call_with_current_module' is the return value of FUNC.

 -- C Procedure: SCM scm_c_lookup (const char *NAME)
     Return the variable bound to the symbol indicated by NAME in the
     current module.  If there is no such binding or the symbol is not
     bound to a variable, signal an error.

 -- C Procedure: SCM scm_lookup (SCM NAME)
     Like `scm_c_lookup', but the symbol is specified directly.

 -- C Procedure: SCM scm_c_module_lookup (SCM MODULE, const char *NAME)
 -- C Procedure: SCM scm_module_lookup (SCM MODULE, SCM NAME)
     Like `scm_c_lookup' and `scm_lookup', but the specified module is
     used instead of the current one.

 -- C Procedure: SCM scm_c_define (const char *NAME, SCM VAL)
     Bind the symbol indicated by NAME to a variable in the current
     module and set that variable to VAL.  When NAME is already bound
     to a variable, use that.  Else create a new variable.

 -- C Procedure: SCM scm_define (SCM NAME, SCM VAL)
     Like `scm_c_define', but the symbol is specified directly.

 -- C Procedure: SCM scm_c_module_define (SCM MODULE, const char *NAME,
          SCM VAL)
 -- C Procedure: SCM scm_module_define (SCM MODULE, SCM NAME, SCM VAL)
     Like `scm_c_define' and `scm_define', but the specified module is
     used instead of the current one.

 -- C Procedure: SCM scm_module_reverse_lookup (SCM MODULE, SCM
          VARIABLE)
     Find the symbol that is bound to VARIABLE in MODULE.  When no such
     binding is found, return #F.

 -- C Procedure: SCM scm_c_define_module (const char *NAME, void
          (*INIT)(void *), void *DATA)
     Define a new module named NAME and make it current while INIT is
     called, passing it DATA.  Return the module.

     The parameter NAME is a string with the symbols that make up the
     module name, separated by spaces.  For example, `"foo bar"' names
     the module `(foo bar)'.

     When there already exists a module named NAME, it is used
     unchanged, otherwise, an empty module is created.

 -- C Procedure: SCM scm_c_resolve_module (const char *NAME)
     Find the module name NAME and return it.  When it has not already
     been defined, try to auto-load it.  When it can't be found that
     way either, create an empty module.  The name is interpreted as
     for `scm_c_define_module'.

 -- C Procedure: SCM scm_resolve_module (SCM NAME)
     Like `scm_c_resolve_module', but the name is given as a real list
     of symbols.

 -- C Procedure: SCM scm_c_use_module (const char *NAME)
     Add the module named NAME to the uses list of the current module,
     as with `(use-modules NAME)'.  The name is interpreted as for
     `scm_c_define_module'.

 -- C Procedure: SCM scm_c_export (const char *NAME, ...)
     Add the bindings designated by NAME, ... to the public interface
     of the current module.  The list of names is terminated by `NULL'.


File: guile.info,  Node: Dynamic Libraries,  Next: Variables,  Prev: The Guile module system,  Up: Modules

31.4 Dynamic Libraries
======================

Most modern Unices have something called "shared libraries".  This
ordinarily means that they have the capability to share the executable
image of a library between several running programs to save memory and
disk space.  But generally, shared libraries give a lot of additional
flexibility compared to the traditional static libraries.  In fact,
calling them `dynamic' libraries is as correct as calling them `shared'.

   Shared libraries really give you a lot of flexibility in addition to
the memory and disk space savings.  When you link a program against a
shared library, that library is not closely incorporated into the final
executable.  Instead, the executable of your program only contains
enough information to find the needed shared libraries when the program
is actually run.  Only then, when the program is starting, is the final
step of the linking process performed.  This means that you need not
recompile all programs when you install a new, only slightly modified
version of a shared library.  The programs will pick up the changes
automatically the next time they are run.

   Now, when all the necessary machinery is there to perform part of the
linking at run-time, why not take the next step and allow the programmer
to explicitly take advantage of it from within his program?  Of course,
many operating systems that support shared libraries do just that, and
chances are that Guile will allow you to access this feature from within
your Scheme programs.  As you might have guessed already, this feature
is called "dynamic linking".(1)

   As with many aspects of Guile, there is a low-level way to access the
dynamic linking apparatus, and a more high-level interface that
integrates dynamically linked libraries into the module system.

* Menu:

* Low level dynamic linking::
* Extensions::

   ---------- Footnotes ----------

   (1) Some people also refer to the final linking stage at program
startup as `dynamic linking', so if you want to make yourself perfectly
clear, it is probably best to use the more technical term "dlopening",
as suggested by Gordon Matzigkeit in his libtool documentation.


File: guile.info,  Node: Low level dynamic linking,  Next: Extensions,  Up: Dynamic Libraries

31.4.1 Low level dynamic linking
--------------------------------

When using the low level procedures to do your dynamic linking, you have
complete control over which library is loaded when and what gets done
with it.

 -- Scheme Procedure: dynamic-link library
 -- C Function: scm_dynamic_link (library)
     Find the shared library denoted by LIBRARY (a string) and link it
     into the running Guile application.  When everything works out,
     return a Scheme object suitable for representing the linked object
     file.  Otherwise an error is thrown.  How object files are
     searched is system dependent.

     Normally, LIBRARY is just the name of some shared library file
     that will be searched for in the places where shared libraries
     usually reside, such as in `/usr/lib' and `/usr/local/lib'.

 -- Scheme Procedure: dynamic-object? obj
 -- C Function: scm_dynamic_object_p (obj)
     Return `#t' if OBJ is a dynamic library handle, or `#f' otherwise.

 -- Scheme Procedure: dynamic-unlink dobj
 -- C Function: scm_dynamic_unlink (dobj)
     Unlink the indicated object file from the application.  The
     argument DOBJ must have been obtained by a call to `dynamic-link'.
     After `dynamic-unlink' has been called on DOBJ, its content is no
     longer accessible.

 -- Scheme Procedure: dynamic-func name dobj
 -- C Function: scm_dynamic_func (name, dobj)
     Search the dynamic object DOBJ for the C function indicated by the
     string NAME and return some Scheme handle that can later be used
     with `dynamic-call' to actually call the function.

     Regardless whether your C compiler prepends an underscore `_' to
     the global names in a program, you should *not* include this
     underscore in FUNCTION.  Guile knows whether the underscore is
     needed or not and will add it when necessary.

 -- Scheme Procedure: dynamic-call func dobj
 -- C Function: scm_dynamic_call (func, dobj)
     Call the C function indicated by FUNC and DOBJ.  The function is
     passed no arguments and its return value is ignored.  When
     FUNCTION is something returned by `dynamic-func', call that
     function and ignore DOBJ.  When FUNC is a string , look it up in
     DYNOBJ; this is equivalent to
          (dynamic-call (dynamic-func FUNC DOBJ) #f)

     Interrupts are deferred while the C function is executing (with
     `SCM_DEFER_INTS'/`SCM_ALLOW_INTS').

 -- Scheme Procedure: dynamic-args-call func dobj args
 -- C Function: scm_dynamic_args_call (func, dobj, args)
     Call the C function indicated by FUNC and DOBJ, just like
     `dynamic-call', but pass it some arguments and return its return
     value.  The C function is expected to take two arguments and
     return an `int', just like `main':
          int c_func (int argc, char **argv);

     The parameter ARGS must be a list of strings and is converted into
     an array of `char *'.  The array is passed in ARGV and its size in
     ARGC.  The return value is converted to a Scheme number and
     returned from the call to `dynamic-args-call'.

   When dynamic linking is disabled or not supported on your system,
the above functions throw errors, but they are still available.

   Here is a small example that works on GNU/Linux:

     (define libc-obj (dynamic-link "libc.so"))
     libc-obj
     => #<dynamic-object "libc.so">
     (dynamic-args-call 'rand libc-obj '())
     => 269167349
     (dynamic-unlink libc-obj)
     libc-obj
     => #<dynamic-object "libc.so" (unlinked)>

   As you can see, after calling `dynamic-unlink' on a dynamically
linked library, it is marked as `(unlinked)' and you are no longer able
to use it with `dynamic-call', etc.  Whether the library is really
removed from you program is system-dependent and will generally not
happen when some other parts of your program still use it.  In the
example above, `libc' is almost certainly not removed from your program
because it is badly needed by almost everything.

   The functions to call a function from a dynamically linked library,
`dynamic-call' and `dynamic-args-call', are not very powerful.  They
are mostly intended to be used for calling specially written
initialization functions that will then add new primitives to Guile.
For example, we do not expect that you will dynamically link `libX11'
with `dynamic-link' and then construct a beautiful graphical user
interface just by using `dynamic-call' and `dynamic-args-call'.
Instead, the usual way would be to write a special Guile<->X11 glue
library that has intimate knowledge about both Guile and X11 and does
whatever is necessary to make them inter-operate smoothly.  This glue
library could then be dynamically linked into a vanilla Guile
interpreter and activated by calling its initialization function.  That
function would add all the new types and primitives to the Guile
interpreter that it has to offer.

   From this setup the next logical step is to integrate these glue
libraries into the module system of Guile so that you can load new
primitives into a running system just as you can load new Scheme code.

   There is, however, another possibility to get a more thorough access
to the functions contained in a dynamically linked library.  Anthony
Green has written `libffi', a library that implements a "foreign
function interface" for a number of different platforms.  With it, you
can extend the Spartan functionality of `dynamic-call' and
`dynamic-args-call' considerably.  There is glue code available in the
Guile contrib archive to make `libffi' accessible from Guile.


File: guile.info,  Node: Extensions,  Prev: Low level dynamic linking,  Up: Dynamic Libraries

31.4.2 Writing Dynamically Loadable Extensions
----------------------------------------------

Higher level linking routines allow you to manage loadable modules when
multiple scheme modules require the same dynamically linked library.  As
we described in section *Note A Sample Guile Extension::, we write a C
module which contains an init function, and then use the
`load-extension' to link the library and run the init function.
However, let's assume that we had two scheme modules (for example, (math
general) and (science electrons)) which both required the
`libguile-bessel' routines.  We would not want to link the shared file
twice because it wastes memory, and even if we were not concerned with
that, it would create symbol conflicts.  We cannot designate one to do
the loading, since we may only want one or the other (or both) at any
given time.  These routines solve this problem.

 -- Scheme Procedure: load-extension lib init
 -- C Function: scm_load_extension (SCM lib, SCM init)
 -- C Function: scm_c_load_extension (const char *lib, const char *init)

   Most of the time, when this function is called, it is equivalent to
calling `(dynamic-call init (dynamic-link lib))'.  It simply uses the
low-level dynamic linking routines to link the shared file, and call
its init function.  However, if the library and init function has been
pre-registered, it skips the linking of the shared file, and calls the
replacement init function which was designated by the registration.
That way both of our modules can contain the line

     (load-extension "libguile-bessel" "init_bessel")

   If, for example, (math general) gets loaded first, then it will do
the standard thing and links the shared file, and calls init_bessel.
When (science electrons) gets loaded, the load-extension line does not
cause the shared file to be linked.  Instead it simply causes the
replacement init function to be run.

 -- C Function: scm_c_register_extension (const char *lib, const char
          *init, void (*func) (void *), void *data)

   We utilize `scm_c_register_extension' from the init function of our
module to register our replacement function.  The bessel function
example would then look like

     #include <math.h>
     #include <libguile.h>

     static double pi; /* Random Global Variable */

     SCM
     j0_wrapper (SCM x)
     {
       return scm_make_real (j0 (scm_num2dbl (x, "j0")));
     }

     void
     define_functions (void *data)
     {
       scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
     }

     void
     init_bessel ()
     {
       pi = 3.14159265; /* Initialize our global var */
       define_functions (NULL);
       scm_c_register_extension ("libguile-bessel", "init_bessel",
                                 define_functions, NULL);
     }

   This way the first time `load-extension' is called, the shared
library is linked, the global variable is initialized, the proper scheme
functions (`j0') are defined, and the replacement init function is
registered.  The second time `load-extension' is called, it finds the
replacement function and calls `define_functions', without redundantly
attempting to link the shared file, or reinitializing our global
variables.

   The fourth argument to `scm_c_register_extension' is a pointer which
gets passed to the replacement init function which you can use for
anything your init function might need.

   The first (`lib') argument is allowed to be NULL. In which case only
the `init' argument is used when searching through the registered
extensions.  This is useful when you don't know the library name (which
isn't really relevant anyway in a completely linked program) and you
are sure that INIT is unique (which it must be for static linking).


File: guile.info,  Node: Variables,  Prev: Dynamic Libraries,  Up: Modules

31.5 Variables
==============

Each module has its own hash table, sometimes known as an "obarray",
that maps the names defined in that module to their corresponding
variable objects.

   A variable is a box-like object that can hold any Scheme value.  It
is said to be "undefined" if its box holds a special Scheme value that
denotes undefined-ness (which is different from all other Scheme values,
including for example `#f'); otherwise the variable is "defined".

   On its own, a variable object is anonymous.  A variable is said to be
"bound" when it is associated with a name in some way, usually a symbol
in a module obarray.  When this happens, the relationship is mutual:
the variable is bound to the name (in that module), and the name (in
that module) is bound to the variable.

   (That's the theory, anyway.  In practice, defined-ness and bound-ness
sometimes get confused, because Lisp and Scheme implementations have
often conflated -- or deliberately drawn no distinction between -- a
name that is unbound and a name that is bound to a variable whose value
is undefined.  We will try to be clear about the difference and explain
any confusion where it is unavoidable.)

   Variables do not have a read syntax.  Most commonly they are created
and bound implicitly by `define' expressions: a top-level `define'
expression of the form

     (define NAME VALUE)

creates a variable with initial value VALUE and binds it to the name
NAME in the current module.  But they can also be created dynamically
by calling one of the constructor procedures `make-variable' and
`make-undefined-variable'.

   First-class variables are especially useful for interacting with the
current module system (*note The Guile module system::).

 -- Scheme Procedure: make-undefined-variable
 -- C Function: scm_make_undefined_variable ()
     Return a variable that is initially unbound.

 -- Scheme Procedure: make-variable init
 -- C Function: scm_make_variable (init)
     Return a variable initialized to value INIT.

 -- Scheme Procedure: variable-bound? var
 -- C Function: scm_variable_bound_p (var)
     Return `#t' iff VAR is bound to a value.  Throws an error if VAR
     is not a variable object.

 -- Scheme Procedure: variable-ref var
 -- C Function: scm_variable_ref (var)
     Dereference VAR and return its value.  VAR must be a variable
     object; see `make-variable' and `make-undefined-variable'.

 -- Scheme Procedure: variable-set! var val
 -- C Function: scm_variable_set_x (var, val)
     Set the value of the variable VAR to VAL.  VAR must be a variable
     object, VAL can be any value. Return an unspecified value.

 -- Scheme Procedure: variable? obj
 -- C Function: scm_variable_p (obj)
     Return `#t' iff OBJ is a variable object, else return `#f'.


File: guile.info,  Node: Scheduling,  Next: Options and Config,  Prev: Modules,  Up: Top

32 Threads, Mutexes, Asyncs and Dynamic Roots
*********************************************

[FIXME: This is pasted in from Tom Lord's original guile.texi chapter
plus the Cygnus programmer's manual; it should be *very* carefully
reviewed and largely reorganized.]

* Menu:

* Arbiters::            Synchronization primitives.
* Asyncs::              Asynchronous procedure invocation.
* Dynamic Roots::       Root frames of execution.
* Threads::             Multiple threads of execution.
* Fluids::              Dynamically scoped variables.


File: guile.info,  Node: Arbiters,  Next: Asyncs,  Up: Scheduling

32.1 Arbiters
=============

Arbiters are synchronization objects.  They are created with
`make-arbiter'.  Two or more threads can synchronize on an arbiter by
trying to lock it using `try-arbiter'.  This call will succeed if no
other thread has called `try-arbiter' on the arbiter yet, otherwise it
will fail and return `#f'.  Once an arbiter is successfully locked, it
cannot be locked by another thread until the thread holding the arbiter
calls `release-arbiter' to unlock it.

 -- Scheme Procedure: make-arbiter name
 -- C Function: scm_make_arbiter (name)
     Return an object of type arbiter and name NAME. Its state is
     initially unlocked.  Arbiters are a way to achieve process
     synchronization.

 -- Scheme Procedure: try-arbiter arb
 -- C Function: scm_try_arbiter (arb)
     Return `#t' and lock the arbiter ARB if the arbiter was unlocked.
     Otherwise, return `#f'.

 -- Scheme Procedure: release-arbiter arb
 -- C Function: scm_release_arbiter (arb)
     Return `#t' and unlock the arbiter ARB if the arbiter was locked.
     Otherwise, return `#f'.


File: guile.info,  Node: Asyncs,  Next: Dynamic Roots,  Prev: Arbiters,  Up: Scheduling

32.2 Asyncs
===========

An async is a pair of one thunk (a parameterless procedure) and a mark.
Setting the mark on an async guarantees that the thunk will be executed
somewhen in the future ("asynchronously").  Setting the mark more than
once is satisfied by one execution of the thunk.

   Guile supports two types of asyncs: Normal asyncs and system asyncs.
They differ in that marked system asyncs are executed implicitly as soon
as possible, whereas normal asyncs have to be invoked explicitly.
System asyncs are held in an internal data structure and are maintained
by Guile.

   Normal asyncs are created with `async', system asyncs with
`system-async'.  They are marked with `async-mark' or
`system-async-mark', respectively.

 -- Scheme Procedure: async thunk
 -- C Function: scm_async (thunk)
     Create a new async for the procedure THUNK.

 -- Scheme Procedure: system-async thunk
 -- C Function: scm_system_async (thunk)
     Create a new async for the procedure THUNK.  Also add it to the
     system's list of active async objects.

 -- Scheme Procedure: async-mark a
 -- C Function: scm_async_mark (a)
     Mark the async A for future execution.

 -- Scheme Procedure: system-async-mark a
 -- C Function: scm_system_async_mark (a)
     Mark the async A for future execution.

   As already mentioned above, system asyncs are executed automatically.
Normal asyncs have to be explicitly invoked by storing one or more of
them into a list and passing them to `run-asyncs'.

 -- Scheme Procedure: run-asyncs list_of_a
 -- C Function: scm_run_asyncs (list_of_a)
     Execute all thunks from the asyncs of the list LIST_OF_A.

   Automatic invocation of system asyncs can be temporarily disabled by
calling `mask-signals' and `unmask-signals'.  Setting the mark while
async execution is disabled will nevertheless cause the async to run
once execution is enabled again.  Please note that calls to these
procedures should always be paired, and they must not be nested, e.g. no
`mask-signals' is allowed if another one is still active.

 -- Scheme Procedure: mask-signals
 -- C Function: scm_mask_signals ()
     Mask signals. The returned value is not specified.

 -- Scheme Procedure: unmask-signals
 -- C Function: scm_unmask_signals ()
     Unmask signals. The returned value is not specified.

 -- Scheme Procedure: noop . args
 -- C Function: scm_noop (args)
     Do nothing.  When called without arguments, return `#f', otherwise
     return the first argument.


File: guile.info,  Node: Dynamic Roots,  Next: Threads,  Prev: Asyncs,  Up: Scheduling

32.3 Dynamic Roots
==================

A "dynamic root" is a root frame of Scheme evaluation.  The top-level
repl, for example, is an instance of a dynamic root.

   Each dynamic root has its own chain of dynamic-wind information.
Each has its own set of continuations, jump-buffers, and pending CATCH
statements which are inaccessible from the dynamic scope of any other
dynamic root.

   In a thread-based system, each thread has its own dynamic root.
Therefore, continuations created by one thread may not be invoked by
another.

   Even in a single-threaded system, it is sometimes useful to create a
new dynamic root.  For example, if you want to apply a procedure, but to
not allow that procedure to capture the current continuation, calling
the procedure under a new dynamic root will do the job.

 -- Scheme Procedure: call-with-dynamic-root thunk handler
 -- C Function: scm_call_with_dynamic_root (thunk, handler)
     Evaluate `(thunk)' in a new dynamic context, returning its value.

     If an error occurs during evaluation, apply HANDLER to the
     arguments to the throw, just as `throw' would.  If this happens,
     HANDLER is called outside the scope of the new root - it is called
     in the same dynamic context in which `call-with-dynamic-root' was
     evaluated.

     If THUNK captures a continuation, the continuation is rooted at
     the call to THUNK.  In particular, the call to
     `call-with-dynamic-root' is not captured.  Therefore,
     `call-with-dynamic-root' always returns at most one time.

     Before calling THUNK, the dynamic-wind chain is un-wound back to
     the root and a new chain started for THUNK.  Therefore, this call
     may not do what you expect:

          ;; Almost certainly a bug:
          (with-output-to-port
           some-port

           (lambda ()
             (call-with-dynamic-root
              (lambda ()
                (display 'fnord)
                (newline))
              (lambda (errcode) errcode))))

     The problem is, on what port will `fnord' be displayed?  You might
     expect that because of the `with-output-to-port' that it will be
     displayed on the port bound to `some-port'.  But it probably won't
     - before evaluating the thunk, dynamic winds are unwound,
     including those created by `with-output-to-port'.  So, the
     standard output port will have been re-set to its default value
     before `display' is evaluated.

     (This function was added to Guile mostly to help calls to
     functions in C libraries that can not tolerate non-local exits or
     calls that return multiple times.  If such functions call back to
     the interpreter, it should be under a new dynamic root.)

 -- Scheme Procedure: dynamic-root
 -- C Function: scm_dynamic_root ()
     Return an object representing the current dynamic root.

     These objects are only useful for comparison using `eq?'.  They
     are currently represented as numbers, but your code should in no
     way depend on this.

 -- Scheme Procedure: quit [exit_val]
     Throw back to the error handler of the current dynamic root.

     If integer EXIT_VAL is specified and if Guile is being used
     stand-alone and if quit is called from the initial dynamic-root,
     EXIT_VAL becomes the exit status of the Guile process and the
     process exits.

   When Guile is run interactively, errors are caught from within the
read-eval-print loop.  An error message will be printed and `abort'
called.  A default set of signal handlers is installed, e.g., to allow
user interrupt of the interpreter.

   It is possible to switch to a "batch mode", in which the interpreter
will terminate after an error and in which all signals cause their
default actions.  Switching to batch mode causes any handlers installed
from Scheme code to be removed.  An example of where this is useful is
after forking a new process intended to run non-interactively.

 -- Scheme Procedure: batch-mode?
     Returns a boolean indicating whether the interpreter is in batch
     mode.

 -- Scheme Procedure: set-batch-mode?! arg
     If ARG is true, switches the interpreter to batch mode.  The `#f'
     case has not been implemented.


File: guile.info,  Node: Threads,  Next: Fluids,  Prev: Dynamic Roots,  Up: Scheduling

32.4 Threads
============

*[NOTE: this chapter was written for Cygnus Guile and has not yet been
updated for the Guile 1.x release.]*

   Here is a the reference for Guile's threads.  In this chapter I
simply quote verbatim Tom Lord's description of the low-level primitives
written in C (basically an interface to the POSIX threads library) and
Anthony Green's description of the higher-level thread procedures
written in scheme.  

   When using Guile threads, keep in mind that each guile thread is
executed in a new dynamic root.

* Menu:

* Low level thread primitives::
* Higher level thread procedures::


File: guile.info,  Node: Low level thread primitives,  Next: Higher level thread procedures,  Up: Threads

32.4.1 Low level thread primitives
----------------------------------

 -- Scheme Procedure: call-with-new-thread thunk error-handler
     Evaluate `(thunk)' in a new thread, and new dynamic context,
     returning a new thread object representing the thread.

     If an error occurs during evaluation, call error-handler, passing
     it an error code describing the condition.  [Error codes are
     currently meaningless integers.  In the future, real values will
     be specified.]  If this happens, the error-handler is called
     outside the scope of the new root - it is called in the same
     dynamic context in which with-new-thread was evaluated, but not in
     the caller's thread.

     All the evaluation rules for dynamic roots apply to threads.

 -- Scheme Procedure: join-thread thread
     Suspend execution of the calling thread until the target THREAD
     terminates, unless the target THREAD has already terminated.

 -- Scheme Procedure: yield
     If one or more threads are waiting to execute, calling yield
     forces an immediate context switch to one of them. Otherwise,
     yield has no effect.

 -- Scheme Procedure: make-mutex
     Create a new mutex object.

 -- Scheme Procedure: lock-mutex mutex
     Lock MUTEX. If the mutex is already locked, the calling thread
     blocks until the mutex becomes available. The function returns when
     the calling thread owns the lock on MUTEX.

 -- Scheme Procedure: unlock-mutex mutex
     Unlocks MUTEX if the calling thread owns the lock on MUTEX.
     Calling unlock-mutex on a mutex not owned by the current thread
     results in undefined behaviour. Once a mutex has been unlocked,
     one thread blocked on MUTEX is awakened and grabs the mutex lock.

 -- Scheme Procedure: make-condition-variable

 -- Scheme Procedure: wait-condition-variable cond-var mutex

 -- Scheme Procedure: signal-condition-variable cond-var


File: guile.info,  Node: Higher level thread procedures,  Prev: Low level thread primitives,  Up: Threads

32.4.2 Higher level thread procedures
-------------------------------------

Higher level thread procedures are available by loading the `(ice-9
threads)' module.  These provide standardized thread creation and mutex
interaction.

 -- Scheme Procedure: %thread-handler tag args...
     This procedure is specified as the standard error-handler for
     `make-thread' and `begin-thread'.  If the number of ARGS is three
     or more, use `display-error', otherwise display a message
     "uncaught throw to TAG".  All output is sent to the port specified
     by `current-error-port'.

     Before display, global var `the-last-stack' is set to `#f' and
     signals are unmasked with `unmask-signals'.

     [FIXME: Why distinguish based on number of args?!  Cue voodoo
     music here.]

 -- macro: make-thread proc [args...]
     Apply PROC to ARGS in a new thread formed by
     `call-with-new-thread' using `%thread-handler' as the error
     handler.

 -- macro: begin-thread first [rest...]
     Evaluate forms FIRST and REST in a new thread formed by
     `call-with-new-thread' using `%thread-handler' as the error
     handler.

 -- macro: with-mutex m [body...]
     Lock mutex M, evaluate BODY, and then unlock M.  These
     sub-operations form the branches of a `dynamic-wind'.

 -- macro: monitor first [rest...]
     Evaluate forms FIRST and REST under a newly created anonymous
     mutex, using `with-mutex'.

     [FIXME: Is there any way to access the mutex?]


File: guile.info,  Node: Fluids,  Prev: Threads,  Up: Scheduling

32.5 Fluids
===========

Fluids are objects to store values in.  They have a few properties which
make them useful in certain situations: Fluids can have one value per
dynamic root (*note Dynamic Roots::), so that changes to the value in a
fluid are only visible in the same dynamic root.  Since threads are
executed in separate dynamic roots, fluids can be used for thread local
storage (*note Threads::).

   Fluids can be used to simulate dynamically scoped variables.  These
are used in several (especially in older) dialects of lisp, such as in
Emacs Lisp, and they work a bit like global variables in that they can
be modified by the caller of a procedure, and the called procedure will
see the changes.  With lexically scoped variables--which are normally
used in Scheme--this cannot happen.  See the description of
`with-fluids*' below for details.

   New fluids are created with `make-fluid' and `fluid?' is used for
testing whether an object is actually a fluid.

 -- Scheme Procedure: make-fluid
 -- C Function: scm_make_fluid ()
     Return a newly created fluid.  Fluids are objects of a certain
     type (a smob) that can hold one SCM value per dynamic root.  That
     is, modifications to this value are only visible to code that
     executes within the same dynamic root as the modifying code.  When
     a new dynamic root is constructed, it inherits the values from its
     parent.  Because each thread executes in its own dynamic root, you
     can use fluids for thread local storage.

 -- Scheme Procedure: fluid? obj
 -- C Function: scm_fluid_p (obj)
     Return `#t' iff OBJ is a fluid; otherwise, return `#f'.

   The values stored in a fluid can be accessed with `fluid-ref' and
`fluid-set!'.

 -- Scheme Procedure: fluid-ref fluid
 -- C Function: scm_fluid_ref (fluid)
     Return the value associated with FLUID in the current dynamic
     root.  If FLUID has not been set, then return `#f'.

 -- Scheme Procedure: fluid-set! fluid value
 -- C Function: scm_fluid_set_x (fluid, value)
     Set the value associated with FLUID in the current dynamic root.

   `with-fluids*' temporarily changes the values of one or more fluids,
so that the given procedure and each procedure called by it access the
given values.  After the procedure returns, the old values are restored.

 -- Scheme Procedure: with-fluids* fluids values thunk
 -- C Function: scm_with_fluids (fluids, values, thunk)
     Set FLUIDS to VALUES temporary, and call THUNK.  FLUIDS must be a
     list of fluids and VALUES must be the same number of their values
     to be applied.  Each substitution is done one after another.
     THUNK must be a procedure with no argument.


File: guile.info,  Node: Options and Config,  Next: Translation,  Prev: Scheduling,  Up: Top

33 Configuration, Features and Runtime Options
**********************************************

Why is my Guile different from your Guile?  There are three kinds of
possible variation:

   * build differences -- different versions of the Guile source code,
     installation directories, configuration flags that control pieces
     of functionality being included or left out, etc.

   * differences in dynamically loaded code -- behaviour and features
     provided by modules that can be dynamically loaded into a running
     Guile

   * different runtime options -- some of the options that are provided
     for controlling Guile's behaviour may be set differently.

   Guile provides "introspective" variables and procedures to query all
of these possible variations at runtime.  For runtime options, it also
provides procedures to change the settings of options and to obtain
documentation on what the options mean.

* Menu:

* Build Config::                Build and installation configuration.
* Feature Tracking::            Available features in the Guile process.
* Runtime Options::             Controlling Guile's runtime behaviour.


File: guile.info,  Node: Build Config,  Next: Feature Tracking,  Up: Options and Config

33.1 Configuration, Build and Installation
==========================================

The following procedures and variables provide information about how
Guile was configured, built and installed on your system.

 -- Scheme Procedure: version
 -- Scheme Procedure: effective-version
 -- Scheme Procedure: major-version
 -- Scheme Procedure: minor-version
 -- Scheme Procedure: micro-version
 -- C Function: scm_version ()
 -- C Function: scm_effective_version ()
 -- C Function: scm_major_version ()
 -- C Function: scm_minor_version ()
 -- C Function: scm_micro_version ()
     Return a string describing Guile's full version number, effective
     version number, major, minor or micro version number, respectively.
     The `effective-version' function returns the version name that
     should remain unchanged during a stable series.  Currently that
     means that it omits the micro version.  The effective version
     should be used for items like the versioned share directory name
     i.e. `/usr/share/guile/1.6/'

          (version) => "1.6.0"
          (effective-version) => "1.6"
          (major-version) => "1"
          (minor-version) => "6"
          (micro-version) => "0"

 -- Scheme Procedure: %package-data-dir
 -- C Function: scm_sys_package_data_dir ()
     Return the name of the directory under which Guile Scheme files in
     general are stored.  On Unix-like systems, this is usually
     `/usr/local/share/guile' or `/usr/share/guile'.

 -- Scheme Procedure: %library-dir
 -- C Function: scm_sys_library_dir ()
     Return the name of the directory where the Guile Scheme files that
     belong to the core Guile installation (as opposed to files from a
     3rd party package) are installed.  On Unix-like systems, this is
     usually `/usr/local/share/guile/<GUILE_EFFECTIVE_VERSION>' or
     `/usr/share/guile/<GUILE_EFFECTIVE_VERSION>', for example:
     `/usr/local/share/guile/1.6'.

 -- Scheme Procedure: %site-dir
 -- C Function: scm_sys_site_dir ()
     Return the name of the directory where Guile Scheme files specific
     to your site should be installed.  On Unix-like systems, this is
     usually `/usr/local/share/guile/site' or `/usr/share/guile/site'.

 -- Variabele: %load-path
     List of directories which should be searched for Scheme modules and
     libraries.  `%load-path' is initialized when Guile starts up to
     `(list (%site-dir) (%library-dir) (%package-data-dir) ".")',
     prepended with the contents of the GUILE_LOAD_PATH environment
     variable, if it is set.

 -- Scheme Procedure: parse-path path [tail]
 -- C Function: scm_parse_path (path, tail)
     Parse PATH, which is expected to be a colon-separated string, into
     a list and return the resulting list with TAIL appended. If PATH
     is `#f', TAIL is returned.

 -- Scheme Procedure: search-path path filename [extensions]
 -- C Function: scm_search_path (path, filename, extensions)
     Search PATH for a directory containing a file named FILENAME. The
     file must be readable, and not a directory.  If we find one,
     return its full filename; otherwise, return `#f'.  If FILENAME is
     absolute, return it unchanged.  If given, EXTENSIONS is a list of
     strings; for each directory in PATH, we search for FILENAME
     concatenated with each EXTENSION.

 -- Variabele: %guile-build-info
     Alist of information collected during the building of a particular
     Guile.  Entries can be grouped into one of several categories:
     directories, env vars, and versioning info.

     Briefly, here are the keys in `%guile-build-info', by group:

    directories
          srcdir, top_srcdir, prefix, exec_prefix, bindir, sbindir,
          libexecdir, datadir, sysconfdir, sharedstatedir,
          localstatedir, libdir, infodir, mandir, includedir,
          pkgdatadir, pkglibdir, pkgincludedir

    env vars
          LIBS

    versioning info
          guileversion, libguileinterface, buildstamp

     Values are all strings.  The value for `LIBS' is typically found
     also as a part of "guile-config link" output.  The value for
     `guileversion' has form X.Y.Z, and should be the same as returned
     by `(version)'.  The value for `libguileinterface' is libtool
     compatible and has form CURRENT:REVISION:AGE.  The value for
     `buildstamp' is the output of the date(1) command.

     In the source, `%guile-build-info' is initialized from
     libguile/libpath.h, which is completely generated, so deleting
     this file before a build guarantees up-to-date values for that
     build.


File: guile.info,  Node: Feature Tracking,  Next: Runtime Options,  Prev: Build Config,  Up: Options and Config

33.2 Feature Tracking
=====================

Guile has a Scheme level variable `*features*' that keeps track to some
extent of the features that are available in a running Guile.
`*features*' is a list of symbols, for example `threads', each of which
describes a feature of the running Guile process.

 -- Variabele: *features*
     A list of symbols describing available features of the Guile
     process.

   You shouldn't modify the `*features*' variable directly using
`set!'.  Instead, see the procedures that are provided for this purpose
in the following subsection.

* Menu:

* Feature Manipulation::        Checking for and advertising features.
* Common Feature Symbols::      Commonly available features.


File: guile.info,  Node: Feature Manipulation,  Next: Common Feature Symbols,  Up: Feature Tracking

33.2.1 Feature Manipulation
---------------------------

To check whether a particular feature is available, use the `provided?'
procedure:

 -- Scheme Procedure: provided? feature
 -- Deprecated Scheme Procedure: feature? feature
     Return `#t' if the specified FEATURE is available, otherwise `#f'.

   To advertise a feature from your own Scheme code, you can use the
`provide' procedure:

 -- Scheme Procedure: provide feature
     Add FEATURE to the list of available features in this Guile
     process.

   For C code, the equivalent function takes its feature name as a
`char *' argument for convenience:

 -- C Function: void scm_add_feature (const char *str)
     Add a symbol with name STR to the list of available features in
     this Guile process.


File: guile.info,  Node: Common Feature Symbols,  Prev: Feature Manipulation,  Up: Feature Tracking

33.2.2 Common Feature Symbols
-----------------------------

In general, a particular feature may be available for one of two
reasons.  Either because the Guile library was configured and compiled
with that feature enabled -- i.e. the feature is built into the library
on your system.  Or because some C or Scheme code that was dynamically
loaded by Guile has added that feature to the list.

   In the first category, here are the features that the current
version of Guile may define (depending on how it is built), and what
they mean.

`array'
     Indicates support for arrays (*note Arrays::).

`array-for-each'
     Indicates availability of `array-for-each' and other array mapping
     procedures (*note Array Mapping::).

`char-ready?'
     Indicates that the `char-ready?' function is available (*note
     Reading::).

`complex'
     Indicates support for complex numbers.

`current-time'
     Indicates availability of time-related functions: `times',
     `get-internal-run-time' and so on (*note Time::).

`debug-extensions'
     Indicates that the debugging evaluator is available, together with
     the options for controlling it.

`delay'
     Indicates support for promises (*note Delayed Evaluation::).

`EIDs'
     Indicates that the `geteuid' and `getegid' really return effective
     user and group IDs (*note Processes::).

`inexact'
     Indicates support for inexact numbers.

`i/o-extensions'
     Indicates availability of the following extended I/O procedures:
     `ftell', `redirect-port', `dup->fdes', `dup2', `fileno',
     `isatty?', `fdopen', `primitive-move->fdes' and `fdes->ports'
     (*note Ports and File Descriptors::).

`net-db'
     Indicates availability of network database functions:
     `scm_gethost', `scm_getnet', `scm_getproto', `scm_getserv',
     `scm_sethost', `scm_setnet', `scm_setproto', `scm_setserv', and
     their `byXXX' variants (*note Network Databases::).

`posix'
     Indicates support for POSIX functions: `pipe', `getgroups',
     `kill', `execl' and so on (*note POSIX::).

`random'
     Indicates availability of random number generation functions:
     `random', `copy-random-state', `random-uniform' and so on (*note
     Random::).

`reckless'
     Indicates that Guile was built with important checks omitted -- you
     should never see this!

`regex'
     Indicates support for POSIX regular expressions using
     `make-regexp', `regexp-exec' and friends (*note Regexp
     Functions::).

`socket'
     Indicates availability of socket-related functions: `socket',
     `bind', `connect' and so on (*note Network Sockets and
     Communication::).

`sort'
     Indicates availability of sorting and merging functions (*note
     Sorting::).

`system'
     Indicates that the `system' function is available (*note
     Processes::).

`threads'
     Indicates support for multithreading (*note Threads::).

`values'
     Indicates support for multiple return values using `values' and
     `call-with-values' (*note Multiple Values::).

   Available features in the second category depend, by definition, on
what additional code your Guile process has loaded in.  The following
table lists features that you might encounter for this reason.

`defmacro'
     Indicates that the `defmacro' macro is available (*note Macros::).

`describe'
     Indicates that the `(oop goops describe)' module has been loaded,
     which provides a procedure for describing the contents of GOOPS
     instances.

`readline'
     Indicates that Guile has loaded in Readline support, for command
     line editing (*note Readline Support::).

`record'
     Indicates support for record definition using `make-record-type'
     and friends (*note Records::).

   Although these tables may seem exhaustive, it is probably unwise in
practice to rely on them, as the correspondences between feature symbols
and available procedures/behaviour are not strictly defined.  If you are
writing code that needs to check for the existence of some procedure, it
is probably safer to do so directly using the `defined?' procedure than
to test for the corresponding feature using `feature?'.


File: guile.info,  Node: Runtime Options,  Prev: Feature Tracking,  Up: Options and Config

33.3 Runtime Options
====================

Guile's runtime behaviour can be modified by setting options.  For
example, is the language that Guile accepts case sensitive, or should
the debugger automatically show a backtrace on error?

   Guile has two levels of interface for managing options: a low-level
control interface, and a user-level interface which allows the enabling
or disabling of options.

   Moreover, the options are classified in groups according to whether
they configure _reading_, _printing_, _debugging_ or _evaluating_.

* Menu:

* Low level options interfaces::
* User level options interfaces::
* Reader options::
* Printing options::
* Debugger options::
* Evaluator options::
* Evaluator trap options::
* Examples of option use::


File: guile.info,  Node: Low level options interfaces,  Next: User level options interfaces,  Up: Runtime Options

33.3.1 Low Level Options Interfaces
-----------------------------------

 -- Scheme Procedure: read-options-interface [setting]
 -- Scheme Procedure: eval-options-interface [setting]
 -- Scheme Procedure: print-options-interface [setting]
 -- Scheme Procedure: debug-options-interface [setting]
 -- Scheme Procedure: evaluator-traps-interface [setting]
 -- C Function: scm_read_options (setting)
 -- C Function: scm_eval_options_interface (setting)
 -- C Function: scm_print_options (setting)
 -- C Function: scm_debug_options (setting)
 -- C Function: scm_evaluator_traps (setting)
     If one of these procedures is called with no arguments (or with
     `setting == SCM_UNDEFINED' in C code), it returns a list describing
     the current setting of the read, eval, print, debug or evaluator
     traps options respectively.  The setting of a boolean option is
     indicated simply by the presence or absence of the option symbol
     in the list.  The setting of a non-boolean option is indicated by
     the presence of the option symbol immediately followed by the
     option's current value.

     If called with a list argument, these procedures interpret the
     list as an option setting and modify the relevant options
     accordingly.  [FIXME -- this glosses over a lot of details!]

     If called with any other argument, such as `'help', these
     procedures return a list of entries like `(OPTION-SYMBOL
     DEFAULT-VALUE DOC-STRING)', with each entry giving the default
     value and documentation for each option symbol in the relevant set
     of options.


File: guile.info,  Node: User level options interfaces,  Next: Reader options,  Prev: Low level options interfaces,  Up: Runtime Options

33.3.2 User Level Options Interfaces
------------------------------------

 -- Scheme Procedure: <group>-options [arg]
 -- Scheme Procedure: read-options [arg]
 -- Scheme Procedure: print-options [arg]
 -- Scheme Procedure: debug-options [arg]
 -- Scheme Procedure: traps [arg]
     These functions list the options in their group.  The optional
     argument ARG is a symbol which modifies the form in which the
     options are presented.

     With no arguments, `<group>-options' returns the values of the
     options in that particular group.  If ARG is `'help', a
     description of each option is given.  If ARG is `'full',
     programmers' options are also shown.

     ARG can also be a list representing the state of all options.  In
     this case, the list contains single symbols (for enabled boolean
     options) and symbols followed by values.
[FIXME: I don't think 'full is ever any different from 'help.  What's
up?]

 -- Scheme Procedure: <group>-enable option-symbol
 -- Scheme Procedure: read-enable option-symbol
 -- Scheme Procedure: print-enable option-symbol
 -- Scheme Procedure: debug-enable option-symbol
 -- Scheme Procedure: trap-enable option-symbol
     These functions set the specified OPTION-SYMBOL in their options
     group.  They only work if the option is boolean, and throw an error
     otherwise.

 -- Scheme Procedure: <group>-disable option-symbol
 -- Scheme Procedure: read-disable option-symbol
 -- Scheme Procedure: print-disable option-symbol
 -- Scheme Procedure: debug-disable option-symbol
 -- Scheme Procedure: trap-disable option-symbol
     These functions turn off the specified OPTION-SYMBOL in their
     options group.  They only work if the option is boolean, and throw
     an error otherwise.

 -- syntax: <group>-set! option-symbol value
 -- syntax: read-set! option-symbol value
 -- syntax: print-set! option-symbol value
 -- syntax: debug-set! option-symbol value
 -- syntax: trap-set! option-symbol value
     These functions set a non-boolean OPTION-SYMBOL to the specified
     VALUE.


File: guile.info,  Node: Reader options,  Next: Printing options,  Prev: User level options interfaces,  Up: Runtime Options

33.3.3 Reader options
---------------------

Here is the list of reader options generated by typing `(read-options
'full)' in Guile.  You can also see the default values.

     keywords         #f      Style of keyword recognition: #f or 'prefix
     case-insensitive no      Convert symbols to lower case.
     positions        yes     Record positions of source code expressions.
     copy             no      Copy source code expressions.

   Notice that while Standard Scheme is case insensitive, to ease
translation of other Lisp dialects, notably Emacs Lisp, into Guile,
Guile is case-sensitive by default.

   To make Guile case insensitive, you can type

     (read-enable 'case-insensitive)


File: guile.info,  Node: Printing options,  Next: Debugger options,  Prev: Reader options,  Up: Runtime Options

33.3.4 Printing options
-----------------------

Here is the list of print options generated by typing `(print-options
'full)' in Guile.  You can also see the default values.

     source          no      Print closures with source.
     closure-hook    #f      Hook for printing closures.


File: guile.info,  Node: Evaluator options,  Next: Evaluator trap options,  Prev: Debugger options,  Up: Runtime Options

33.3.5 Evaluator options
------------------------

These are the evaluator options with their default values, as they are
printed by typing `(eval-options 'full)' in Guile.

     stack           22000   Size of thread stacks (in machine words).


File: guile.info,  Node: Evaluator trap options,  Next: Examples of option use,  Prev: Evaluator options,  Up: Runtime Options

33.3.6 Evaluator trap options
-----------------------------

[FIXME: These flags, together with their corresponding handlers, are not
user level options.  Probably this entire section should be moved to the
documentation about the low-level programmer debugging interface.]

   Here is the list of evaluator trap options generated by typing
`(traps 'full)' in Guile.  You can also see the default values.

     exit-frame      no      Trap when exiting eval or apply.
     apply-frame     no      Trap when entering apply.
     enter-frame     no      Trap when eval enters new frame.
     traps		yes	Enable evaluator traps.

 -- apply-frame-handler: key cont tailp
     Called when a procedure is being applied.

     Called if:

        * evaluator traps are enabled [traps interface], and

        * either
             - `apply-frame' is enabled [traps interface], or

             - trace mode is on [debug-options interface], and the
               procedure being called has the trace property enabled.

     If cheap traps are enabled [debug-options interface], CONT is a
     debug object, otherwise it is a restartable continuation.

     TAILP is true if this is a tail call

 -- exit-frame-handler: key cont retval
     Called when a value is returned from a procedure.

     Called if:

        * evaluator traps are enabled [traps interface], and

        * either
             -  `exit-frame' is enabled [traps interface], or

             - trace mode is on [debug-options interface], and the
               procedure being called has the trace property enabled.

     If cheap traps are enabled [debug-options interface], CONT is a
     debug object, otherwise it is a restartable continuation.

     RETVAL is the return value.


File: guile.info,  Node: Debugger options,  Next: Evaluator options,  Prev: Printing options,  Up: Runtime Options

33.3.7 Debugger options
-----------------------

Here is the list of print options generated by typing `(debug-options
'full)' in Guile.  You can also see the default values.

     stack           20000   Stack size limit (0 = no check).
     debug           yes     Use the debugging evaluator.
     backtrace       no      Show backtrace on error.
     depth           20      Maximal length of printed backtrace.
     maxdepth        1000    Maximal number of stored backtrace frames.
     frames          3       Maximum number of tail-recursive frames in backtrace.
     indent          10      Maximal indentation in backtrace.
     backwards       no      Display backtrace in anti-chronological order.
     procnames       yes     Record procedure names at definition.
     trace           no      *Trace mode.
     breakpoints     no      *Check for breakpoints.
     cheap           yes     *Flyweight representation of the stack at traps.

33.3.7.1 Stack overflow
.......................

Stack overflow errors are caused by a computation trying to use more
stack space than has been enabled by the `stack' option.  They are
reported like this:

     (non-tail-recursive-factorial 500)
     -|
     ERROR: Stack overflow
     ABORT: (stack-overflow)

   If you get an error like this, you can either try rewriting your
code to use less stack space, or increase the maximum stack size.  To
increase the maximum stack size, use `debug-set!', for example:

     (debug-set! stack 200000)
     =>
     (show-file-name #t stack 200000 debug backtrace depth 20 maxdepth 1000 frames 3 indent 10 width 79 procnames cheap)

     (non-tail-recursive-factorial 500)
     =>
     122013682599111006870123878542304692625357434...

   If you prefer to try rewriting your code, you may be able to save
stack space by making some of your procedures "tail recursive".  For a
description of what this means, see *Note Proper tail recursion:
(r5rs)Proper tail recursion.


File: guile.info,  Node: Examples of option use,  Prev: Evaluator trap options,  Up: Runtime Options

33.3.8 Examples of option use
-----------------------------

Here is an example of a session in which some read and debug option
handling procedures are used.  In this example, the user

  1. Notices that the symbols `abc' and `aBc' are not the same

  2. Examines the `read-options', and sees that `case-insensitive' is
     set to "no".

  3. Enables `case-insensitive'

  4. Verifies that now `aBc' and `abc' are the same

  5. Disables `case-insensitive' and enables debugging `backtrace'

  6. Reproduces the error of displaying `aBc' with backtracing enabled
     [FIXME: this last example is lame because there is no depth in the
     backtrace.  Need to give a better example, possibly putting
     debugging option examples in a separate session.]

     guile> (define abc "hello")
     guile> abc
     "hello"
     guile> aBc
     ERROR: In expression aBc:
     ERROR: Unbound variable: aBc
     ABORT: (misc-error)

     Type "(backtrace)" to get more information.
     guile> (read-options 'help)
     keywords	#f	Style of keyword recognition: #f or 'prefix
     case-insensitive	no	Convert symbols to lower case.
     positions	yes	Record positions of source code expressions.
     copy		no	Copy source code expressions.
     guile> (debug-options 'help)
     stack		20000	Stack size limit (0 = no check).
     debug		yes	Use the debugging evaluator.
     backtrace	no	Show backtrace on error.
     depth		20	Maximal length of printed backtrace.
     maxdepth	1000	Maximal number of stored backtrace frames.
     frames		3	Maximum number of tail-recursive frames in backtrace.
     indent		10	Maximal indentation in backtrace.
     backwards	no	Display backtrace in anti-chronological order.
     procnames	yes	Record procedure names at definition.
     trace		no	*Trace mode.
     breakpoints	no	*Check for breakpoints.
     cheap		yes	*Flyweight representation of the stack at traps.
     guile> (read-enable 'case-insensitive)
     (keywords #f case-insensitive positions)
     guile> aBc
     "hello"
     guile> (read-disable 'case-insensitive)
     (keywords #f positions)
     guile> (debug-enable 'backtrace)
     (stack 20000 debug backtrace depth 20 maxdepth 1000 frames 3 indent 10 procnames cheap)
     guile> aBc

     Backtrace:
     0* aBc

     ERROR: In expression aBc:
     ERROR: Unbound variable: aBc
     ABORT: (misc-error)
     guile>


File: guile.info,  Node: Translation,  Next: Debugging,  Prev: Options and Config,  Up: Top

34 Support for Translating Other Languages
******************************************

[Describe translation framework.]

* Menu:

* Emacs Lisp Support::          Helper primitives for Emacs Lisp.


File: guile.info,  Node: Emacs Lisp Support,  Up: Translation

34.1 Emacs Lisp Support
=======================

 -- Scheme Procedure: nil-car x
 -- C Function: scm_nil_car (x)
     Return the car of X, but convert it to LISP nil if it is Scheme's
     end-of-list.

 -- Scheme Procedure: nil-cdr x
 -- C Function: scm_nil_cdr (x)
     Return the cdr of X, but convert it to LISP nil if it is Scheme's
     end-of-list.

 -- Scheme Procedure: nil-cons x y
 -- C Function: scm_nil_cons (x, y)
     Create a new cons cell with X as the car and Y as the cdr, but
     convert Y to Scheme's end-of-list if it is a Lisp nil.

 -- Scheme Procedure: nil-eq x y
     Compare X and Y and return Lisp's t if they are `eq?', return
     Lisp's nil otherwise.

 -- Scheme Procedure: null x
 -- C Function: scm_null (x)
     Return Lisp's `t' if X is nil in the LISP sense, return Lisp's nil
     otherwise.


File: guile.info,  Node: Debugging,  Next: Deprecated,  Prev: Translation,  Up: Top

35 Debugging Infrastructure
***************************

* Menu:

* Source Properties::           Remembering the source of an expression.
* Using Traps::
* Capturing the Stack or Innermost Stack Frame::
* Examining the Stack::
* Examining Stack Frames::
* Decoding Memoized Source Expressions::
* Starting a New Stack::


File: guile.info,  Node: Source Properties,  Next: Using Traps,  Up: Debugging

35.1 Source Properties
======================

As Guile reads in Scheme code from file or from standard input, it
remembers the file name, line number and column number where each
expression begins.  These pieces of information are known as the
"source properties" of the expression.  If an expression undergoes
transformation -- for example, if there is a syntax transformer in
effect, or the expression is a macro call -- the source properties are
copied from the untransformed to the transformed expression so that, if
an error occurs when evaluating the transformed expression, Guile's
debugger can point back to the file and location where the expression
originated.

   The way that source properties are stored means that Guile can only
associate source properties with parenthesized expressions, and not, for
example, with individual symbols, numbers or strings.  The difference
can be seen by typing `(xxx)' and `xxx' at the Guile prompt (where the
variable `xxx' has not been defined):

     guile> (xxx)
     standard input:2:1: In expression (xxx):
     standard input:2:1: Unbound variable: xxx
     ABORT: (unbound-variable)
     guile> xxx
     <unnamed port>: In expression xxx:
     <unnamed port>: Unbound variable: xxx
     ABORT: (unbound-variable)

In the latter case, no source properties were stored, so the best that
Guile could say regarding the location of the problem was "<unnamed
port>".

   The recording of source properties is controlled by the read option
named "positions" (*note Reader options::).  This option is switched
_on_ by default, together with the debug options "debug" and
"backtrace" (*note Debugger options::), when Guile is run
interactively; all these options are _off_ by default when Guile runs a
script non-interactively.


File: guile.info,  Node: Using Traps,  Next: Capturing the Stack or Innermost Stack Frame,  Prev: Source Properties,  Up: Debugging

35.2 Using Traps
================

 -- Scheme Procedure: with-traps thunk
 -- C Function: scm_with_traps (thunk)
     Call THUNK with traps enabled.

 -- Scheme Procedure: debug-object? obj
 -- C Function: scm_debug_object_p (obj)
     Return `#t' if OBJ is a debug object.


File: guile.info,  Node: Capturing the Stack or Innermost Stack Frame,  Next: Examining the Stack,  Prev: Using Traps,  Up: Debugging

35.3 Capturing the Stack or Innermost Stack Frame
=================================================

When an error occurs in a running program, or the program hits a
breakpoint, its state at that point can be represented by a "stack" of
all the evaluations and procedure applications that are logically in
progress at that time, each of which is known as a "frame".  The
programmer can learn more about the program's state at the point of
interruption or error by inspecting the stack and its frames.

 -- Scheme Procedure: make-stack obj . args
 -- C Function: scm_make_stack (obj, args)
     Create a new stack. If OBJ is `#t', the current evaluation stack
     is used for creating the stack frames, otherwise the frames are
     taken from OBJ (which must be either a debug object or a
     continuation).

     ARGS should be a list containing any combination of integer,
     procedure and `#t' values.

     These values specify various ways of cutting away uninteresting
     stack frames from the top and bottom of the stack that
     `make-stack' returns.  They come in pairs like this: `(INNER_CUT_1
     OUTER_CUT_1 INNER_CUT_2 OUTER_CUT_2 ...)'.

     Each INNER_CUT_N can be `#t', an integer, or a procedure.  `#t'
     means to cut away all frames up to but excluding the first user
     module frame.  An integer means to cut away exactly that number of
     frames.  A procedure means to cut away all frames up to but
     excluding the application frame whose procedure matches the
     specified one.

     Each OUTER_CUT_N can be an integer or a procedure.  An integer
     means to cut away that number of frames.  A procedure means to cut
     away frames down to but excluding the application frame whose
     procedure matches the specified one.

     If the OUTER_CUT_N of the last pair is missing, it is taken as 0.

 -- Scheme Procedure: last-stack-frame obj
 -- C Function: scm_last_stack_frame (obj)
     Return a stack which consists of a single frame, which is the last
     stack frame for OBJ. OBJ must be either a debug object or a
     continuation.


File: guile.info,  Node: Examining the Stack,  Next: Examining Stack Frames,  Prev: Capturing the Stack or Innermost Stack Frame,  Up: Debugging

35.4 Examining the Stack
========================

 -- Scheme Procedure: stack? obj
 -- C Function: scm_stack_p (obj)
     Return `#t' if OBJ is a calling stack.

 -- Scheme Procedure: stack-id stack
 -- C Function: scm_stack_id (stack)
     Return the identifier given to STACK by `start-stack'.

 -- Scheme Procedure: stack-length stack
 -- C Function: scm_stack_length (stack)
     Return the length of STACK.

 -- Scheme Procedure: stack-ref stack index
 -- C Function: scm_stack_ref (stack, index)
     Return the INDEX'th frame from STACK.

 -- Scheme Procedure: display-backtrace stack port [first [depth]]
 -- C Function: scm_display_backtrace (stack, port, first, depth)
     Display a backtrace to the output port PORT. STACK is the stack to
     take the backtrace from, FIRST specifies where in the stack to
     start and DEPTH how much frames to display. Both FIRST and DEPTH
     can be `#f', which means that default values will be used.


File: guile.info,  Node: Examining Stack Frames,  Next: Decoding Memoized Source Expressions,  Prev: Examining the Stack,  Up: Debugging

35.5 Examining Stack Frames
===========================

 -- Scheme Procedure: frame? obj
 -- C Function: scm_frame_p (obj)
     Return `#t' if OBJ is a stack frame.

 -- Scheme Procedure: frame-number frame
 -- C Function: scm_frame_number (frame)
     Return the frame number of FRAME.

 -- Scheme Procedure: frame-previous frame
 -- C Function: scm_frame_previous (frame)
     Return the previous frame of FRAME, or `#f' if FRAME is the first
     frame in its stack.

 -- Scheme Procedure: frame-next frame
 -- C Function: scm_frame_next (frame)
     Return the next frame of FRAME, or `#f' if FRAME is the last frame
     in its stack.

 -- Scheme Procedure: frame-source frame
 -- C Function: scm_frame_source (frame)
     Return the source of FRAME.

 -- Scheme Procedure: frame-procedure? frame
 -- C Function: scm_frame_procedure_p (frame)
     Return `#t' if a procedure is associated with FRAME.

 -- Scheme Procedure: frame-procedure frame
 -- C Function: scm_frame_procedure (frame)
     Return the procedure for FRAME, or `#f' if no procedure is
     associated with FRAME.

 -- Scheme Procedure: frame-arguments frame
 -- C Function: scm_frame_arguments (frame)
     Return the arguments of FRAME.

 -- Scheme Procedure: frame-evaluating-args? frame
 -- C Function: scm_frame_evaluating_args_p (frame)
     Return `#t' if FRAME contains evaluated arguments.

 -- Scheme Procedure: frame-overflow? frame
 -- C Function: scm_frame_overflow_p (frame)
     Return `#t' if FRAME is an overflow frame.

 -- Scheme Procedure: frame-real? frame
 -- C Function: scm_frame_real_p (frame)
     Return `#t' if FRAME is a real frame.

 -- Scheme Procedure: display-application frame [port [indent]]
 -- C Function: scm_display_application (frame, port, indent)
     Display a procedure application FRAME to the output port PORT.
     INDENT specifies the indentation of the output.


File: guile.info,  Node: Decoding Memoized Source Expressions,  Next: Starting a New Stack,  Prev: Examining Stack Frames,  Up: Debugging

35.6 Decoding Memoized Source Expressions
=========================================

 -- Scheme Procedure: memoized? obj
 -- C Function: scm_memoized_p (obj)
     Return `#t' if OBJ is memoized.

 -- Scheme Procedure: unmemoize m
 -- C Function: scm_unmemoize (m)
     Unmemoize the memoized expression M,

 -- Scheme Procedure: memoized-environment m
 -- C Function: scm_memoized_environment (m)
     Return the environment of the memoized expression M.


File: guile.info,  Node: Starting a New Stack,  Prev: Decoding Memoized Source Expressions,  Up: Debugging

35.7 Starting a New Stack
=========================

 -- Scheme Syntax: start-stack id exp
     Evaluate EXP on a new calling stack with identity ID.  If EXP is
     interrupted during evaluation, backtraces will not display frames
     farther back than EXP's top-level form.  This macro is a way of
     artificially limiting backtraces and stack procedures, largely as
     a convenience to the user.


File: guile.info,  Node: Deprecated,  Next: SLIB,  Prev: Debugging,  Up: Top

36 Deprecated
*************

* Menu:

* Shared And Read Only Strings::
* Sloppy Membership::           `Sloppy' list membership procedures.
* Strange Eval::                Strange variations on `eval'.
* Close All Ports::             Closing all ports except some ...
* C Module Reg::                Old method for registering C modules.
* Obarray Symbols::             Obarray symbol manipulation.
* Removed Items::               Previously deprecated, now removed.


File: guile.info,  Node: Shared And Read Only Strings,  Next: Sloppy Membership,  Up: Deprecated

36.1 Shared And Read Only Strings
=================================

The procedures described in this section are deprecated because explicit
shared substrings are planned to disappear from Guile.

   Instead, all strings will be implemented using sharing internally,
combined with a copy-on-write strategy.  Once internal string sharing
and copy-on-write have been implemented, it will be unnecessary to
preserve the concept of read only strings.

* Menu:

* Shared Substrings::           Strings which share memory with each other.
* Read Only Strings::           Treating certain non-strings as strings.


File: guile.info,  Node: Shared Substrings,  Next: Read Only Strings,  Up: Shared And Read Only Strings

36.1.1 Shared Substrings
------------------------

Whenever you extract a substring using `substring', the Scheme
interpreter allocates a new string and copies data from the old string.
This is expensive, but `substring' is so convenient for manipulating
text that programmers use it often.

   Guile Scheme provides the concept of the "shared substring" to
improve performance of many substring-related operations.  A shared
substring is an object that mostly behaves just like an ordinary
substring, except that it actually shares storage space with its parent
string.

 -- Deprecated Scheme Procedure: make-shared-substring str [start [end]]
 -- Deprecated C Function: scm_make_shared_substring (str, start, end)
     Return a shared substring of STR.  The arguments are the same as
     for the `substring' function: the shared substring returned
     includes all of the text from STR between indexes START
     (inclusive) and END (exclusive).  If END is omitted, it defaults
     to the end of STR.  The shared substring returned by
     `make-shared-substring' occupies the same storage space as STR.

   Example:

     (define foo "the quick brown fox")
     (define bar (make-shared-substring some-string 4 9))

     foo => "t h e   q u i c k   b r o w n   f o x"
     bar =========> |---------|

   The shared substring BAR is not given its own storage space.
Instead, the Guile interpreter notes internally that BAR points to a
portion of the memory allocated to FOO.  However, BAR behaves like an
ordinary string in most respects: it may be used with string primitives
like `string-length', `string-ref', `string=?'.  Guile makes the
necessary translation between indices of BAR and indices of FOO
automatically.

     (string-length? bar) => 5	; bar only extends from indices 4 to 9
     (string-ref bar 3)  => #\c	; same as (string-ref foo 7)
     (make-shared-substring bar 2)
       => "ick"			; can even make a shared substring!

   Because creating a shared substring does not require allocating new
storage from the heap, it is a very fast operation.  However, because it
shares memory with its parent string, a change to the contents of the
parent string will implicitly change the contents of its shared
substrings.

     (string-set! foo 7 #\r)
     bar => "quirk"

   Guile considers shared substrings to be immutable.  This is because
programmers might not always be aware that a given string is really a
shared substring, and might innocently try to mutate it without
realizing that the change would affect its parent string.  (We are
currently considering a "copy-on-write" strategy that would permit
modifying shared substrings without affecting the parent string.)

   In general, shared substrings are useful in circumstances where it is
important to divide a string into smaller portions, but you do not
expect to change the contents of any of the strings involved.


File: guile.info,  Node: Read Only Strings,  Prev: Shared Substrings,  Up: Shared And Read Only Strings

36.1.2 Read Only Strings
------------------------

In previous versions of Guile, there was the idea that some string-based
primitives such as `string-append' could equally accept symbols as
arguments.  For example, one could write

     (string-append '/home/ 'vigilia)

and get `"/home/vigilia"' as the result.  The term "read only string"
was adopted to describe the argument type expected by such primitives.

   This idea has now been removed.  The predicate `read-only-string?'
still exists, but deprecated, and is equivalent to

     (lambda (x) (or (string? x) (symbol? x)))

But no Guile primitives now use `read-only-string?' to validate their
arguments.

   String-based primitives such as `string-append' now require strings:

     (string-append '/home/ 'vigilia)
     =>
     ERROR: Wrong type argument (expecting STRINGP): /home/

 -- Deprecated Scheme Procedure: read-only-string? obj
 -- Deprecated C Function: scm_read_only_string_p (obj)
     Return `#t' if OBJ is either a string or a symbol, otherwise
     return `#f'.


File: guile.info,  Node: Sloppy Membership,  Next: Strange Eval,  Prev: Shared And Read Only Strings,  Up: Deprecated

36.2 `Sloppy' List Membership Procedures
========================================

The following are equivalent to `memq', `memv' and `member'
respectively, except that they do not fully type-check the arguments
that they are given.  They are deprecated because the lack of proper
type-checking makes them dangerous.

 -- Deprecated Scheme Procedure: sloppy-memq x lst
 -- Deprecated C Function: scm_sloppy_memq (x, lst)
     This procedure behaves like `memq', but does no type or error
     checking.  Its use is recommended only in writing Guile internals,
     not for high-level Scheme programs.

 -- Deprecated Scheme Procedure: sloppy-memv x lst
 -- Deprecated C Function: scm_sloppy_memv (x, lst)
     This procedure behaves like `memv', but does no type or error
     checking.  Its use is recommended only in writing Guile internals,
     not for high-level Scheme programs.

 -- Deprecated Scheme Procedure: sloppy-member x lst
 -- Deprecated C Function: scm_sloppy_member (x, lst)
     This procedure behaves like `member', but does no type or error
     checking.  Its use is recommended only in writing Guile internals,
     not for high-level Scheme programs.


File: guile.info,  Node: Strange Eval,  Next: Close All Ports,  Prev: Sloppy Membership,  Up: Deprecated

36.3 Strange Variations on `eval'
=================================

`eval2' was useful in previous Guile releases because the `eval' in
those releases was a single argument `eval' that did not conform to
R5RS.  Guile's standard `eval' now requires a second
environment-specifier argument (which Guile interprets as the module in
which to evaluate the specified code expression).  Hence `eval' is now
R5RS-compliant, and `eval2' is obsolete and therefore deprecated.

 -- Deprecated Scheme Procedure: eval2 obj env_thunk
 -- Deprecated C Function: scm_eval2 (obj, env_thunk)
     Evaluate EXP, a Scheme expression, in the environment designated
     by LOOKUP, a symbol-lookup function.  Do not use this version of
     eval, it does not play well with the module system.  Use `eval' or
     `primitive-eval' instead.

   In previous Guile releases, the implementation of expressions like
`(eval (read port))' was deficient in that source properties associated
with the expression returned by the `read' would be lost during the
`eval'.  To provide a way of performing a read and evaluation without
losing source properties, `read-and-eval!' was invented.

   In this Guile release, evaluation always preserves source property
information.  So `read-and-eval!' is now unnecessary.

 -- Deprecated Scheme Procedure: read-and-eval! [port]
 -- Deprecated C Function: scm_read_and_eval_x (port)
     Read a form from PORT (standard input by default), and evaluate it
     (memoizing it in the process) in the top-level environment.  If no
     data is left to be read from PORT, an `end-of-file' error is
     signalled.


File: guile.info,  Node: Close All Ports,  Next: C Module Reg,  Prev: Strange Eval,  Up: Deprecated

36.4 Closing All Ports Except Some ...
======================================

 -- Deprecated Scheme Procedure: close-all-ports-except . ports
 -- Deprecated C Function: scm_close_all_ports_except (ports)
     [DEPRECATED] Close all open file ports used by the interpreter
     except for those supplied as arguments.  This procedure was
     intended to be used before an exec call to close file descriptors
     which are not needed in the new process.  However it has the
     undesirable side effect of flushing buffers, so it's deprecated.
     Use port-for-each instead.


File: guile.info,  Node: C Module Reg,  Next: Obarray Symbols,  Prev: Close All Ports,  Up: Deprecated

36.5 Old Method for Registering C Modules.
==========================================

** Auto-loading of compiled-code modules is deprecated.

   Guile used to be able to automatically find and link a shared
library to satisfy requests for a module.  For example, the module
`(foo bar)' could be implemented by placing a shared library named
"foo/libbar.so" (or with a different extension) in a directory on the
load path of Guile.

   This has been found to be too tricky, and is no longer supported.
The shared libraries are now called "extensions".  You should now write
a small Scheme file that calls `load-extension' to load the shared
library and initialize it explicitely.

   The shared libraries themselves should be installed in the usual
places for shared libraries, with names like "libguile-foo-bar".

   For example, place this into a file "foo/bar.scm"

   (define-module (foo bar))

   (load-extension "libguile-foo-bar" "foobar_init")


File: guile.info,  Node: Obarray Symbols,  Next: Removed Items,  Prev: C Module Reg,  Up: Deprecated

36.6 Obarray Symbol Manipulation
================================

Guile's module mechanism uses "obarrays", which are hash tables that
map symbols to variables.  Guile 1.4 included a group of primitives that
could be used for the manipulation of the symbol-variable mappings in
such obarrays.

   However, considering the availability both of low-level procedures
for operating on hash tables in general (*note Hash Tables::), and of a
dedicated API for module-related operations (*note Modules::), the
intermediate set of obarray primitives is no longer useful, and --
which is worse -- makes it more difficult to evolve the implementation
of Guile's module system.  Hence this set of primitives has now been
deprecated.

   If you have code using these functions, please change it to use
either hash table or module-related operations.

 -- Deprecated Scheme Procedure: gentemp [prefix [obarray]]
 -- Deprecated C Function: scm_gentemp (prefix, obarray)
     Create a new symbol with a name unique in an obarray.  The name is
     constructed from an optional string PREFIX and a counter value.
     The default prefix is `t'.  The OBARRAY is specified as a second
     optional argument.  Default is the system obarray where all normal
     symbols are interned.  The counter is increased by 1 at each call.
     There is no provision for resetting the counter.

 -- Deprecated Scheme Procedure: intern-symbol obarray string
 -- Deprecated C Function: scm_intern_symbol (obarray, string)
     Add a new symbol to OBARRAY with name STRING, bound to an
     unspecified initial value.  The symbol table is not modified if a
     symbol with this name is already present.

 -- Deprecated Scheme Procedure: symbol-interned? obarray string
 -- Deprecated C Function: scm_symbol_interned_p (obarray, string)
     Return `#t' if OBARRAY contains a symbol with name STRING, and
     `#f' otherwise.

 -- Deprecated Scheme Procedure: unintern-symbol obarray string
 -- Deprecated C Function: scm_unintern_symbol (obarray, string)
     Remove the symbol with name STRING from OBARRAY.  This function
     returns `#t' if the symbol was present and `#f' otherwise.

 -- Deprecated Scheme Procedure: string->obarray-symbol obarray string
          [soft?]
 -- Deprecated C Function: scm_string_to_obarray_symbol (obarray,
          string, soft_p)
     Intern a new symbol in OBARRAY, a symbol table, with name STRING.

     If OBARRAY is `#f', use the default system symbol table.  If
     OBARRAY is `#t', the symbol should not be interned in any symbol
     table; merely return the pair (SYMBOL . #<UNDEFINED>).

     The SOFT? argument determines whether new symbol table entries
     should be created when the specified symbol is not already present
     in OBARRAY.  If SOFT? is specified and is a true value, then new
     entries should not be added for symbols not already present in the
     table; instead, simply return `#f'.

 -- Deprecated Scheme Procedure: symbol-binding obarray string
 -- Deprecated C Function: scm_symbol_binding (obarray, string)
     Look up in OBARRAY the symbol whose name is STRING, and return the
     value to which it is bound.  If OBARRAY is `#f', use the global
     symbol table.  If STRING is not interned in OBARRAY, an error is
     signalled.

 -- Deprecated Scheme Procedure: symbol-bound? obarray string
 -- Deprecated C Function: scm_symbol_bound_p (obarray, string)
     Return `#t' if OBARRAY contains a symbol with name STRING bound to
     a defined value.  This differs from SYMBOL-INTERNED? in that the
     mere mention of a symbol usually causes it to be interned;
     `symbol-bound?' determines whether a symbol has been given any
     meaningful value.

 -- Deprecated Scheme Procedure: symbol-set! obarray string value
 -- Deprecated C Function: scm_symbol_set_x (obarray, string, value)
     Find the symbol in OBARRAY whose name is STRING, and rebind it to
     VALUE.  An error is signalled if STRING is not present in OBARRAY.

 -- Deprecated Scheme Procedure: builtin-bindings
 -- Deprecated C Function: scm_builtin_bindings
     Create and return a copy of the global symbol table, removing all
     unbound symbols.


File: guile.info,  Node: Removed Items,  Prev: Obarray Symbols,  Up: Deprecated

36.7 Previously Deprecated Items Now Removed
============================================

tag fseek list*


File: guile.info,  Node: SLIB,  Next: POSIX,  Prev: Deprecated,  Up: Top

37 SLIB
*******

Before the SLIB facilities can be used, the following Scheme expression
must be executed:

     (use-modules (ice-9 slib))

   `require' can then be used as described in *Note SLIB: (slib)Top.

   For example:

     guile> (use-modules (ice-9 slib))
     guile> (require 'primes)
     guile> (probably-prime? 13)

* Menu:

* SLIB installation::
* JACAL::


File: guile.info,  Node: SLIB installation,  Next: JACAL,  Up: SLIB

37.1 SLIB installation
======================

The following seems to work (e.g., with slib versions 2c7 and 2d2):

  1. Unpack slib somewhere, e.g., /usr/local/share/slib.

  2. Create a symlink in the Guile site directory to slib, e.g.,:

          ln -s /usr/local/share/slib /usr/local/share/guile/site/slib

  3. Use Guile to create the catalog file, e.g.,:

          # guile
          guile> (use-modules (ice-9 slib))
          guile> (load "/usr/local/share/slib/mklibcat.scm")
          guile> (quit)

     The catalog data should now be in
     `/usr/local/share/guile/site/slibcat'.

     If instead you get an error such as:

          Unbound variable: scheme-implementation-type

     then a solution is to get a newer version of Guile, or to modify
     ice-9/slib.scm to use define-public for the offending variables.

  4. Install the documentation:

          cd /usr/local/share/slib
          rm /usr/local/info/slib.info*
          cp slib.info /usr/local/info
          install-info slib.info /usr/local/info/dir


File: guile.info,  Node: JACAL,  Prev: SLIB installation,  Up: SLIB

37.2 JACAL
==========

Jacal is a symbolic math package written in Scheme by Aubrey Jaffer.  It
is usually installed as an extra package in SLIB (*note Packages not
shipped with Guile::).

   You can use Guile's interface to SLIB to invoke Jacal:

     (use-modules (ice-9 slib))
     (slib:load "math")
     (math)

For complete documentation on Jacal, please read the Jacal manual.  If
it has been installed on line, you can look at *Note Jacal: (jacal)Top.
Otherwise you can find it on the web at
`http://www-swiss.ai.mit.edu/~jaffer/JACAL.html'


File: guile.info,  Node: POSIX,  Next: SRFI Support,  Prev: SLIB,  Up: Top

38 POSIX System Calls and Networking
************************************

* Menu:

* Conventions::                 Conventions employed by the POSIX interface.
* Ports and File Descriptors::  Scheme ``ports'' and Unix file descriptors
				  have different representations.
* File System::                 stat, chown, chmod, etc.
* User Information::            Retrieving a user's GECOS (/etc/passwd) entry.
* Time::                        gettimeofday, localtime, strftime, etc.
* Runtime Environment::         Accessing and modifying Guile's environment.
* Processes::                   getuid, getpid, etc.
* Signals::                     sigaction, kill, pause, alarm, setitimer, etc.
* Terminals and Ptys::          ttyname, tcsetpgrp, etc.
* Pipes::                       Communicating data between processes.
* Networking::                  gethostbyaddr, getnetent, socket, bind, listen.
* System Identification::       Obtaining information about the system.
* Locales::                     setlocale, etc.
* Encryption::


File: guile.info,  Node: Conventions,  Next: Ports and File Descriptors,  Up: POSIX

38.1 POSIX Interface Conventions
================================

These interfaces provide access to operating system facilities.  They
provide a simple wrapping around the underlying C interfaces to make
usage from Scheme more convenient.  They are also used to implement the
Guile port of *Note The Scheme shell (scsh)::.

   Generally there is a single procedure for each corresponding Unix
facility.  There are some exceptions, such as procedures implemented for
speed and convenience in Scheme with no primitive Unix equivalent,
e.g., `copy-file'.

   The interfaces are intended as far as possible to be portable across
different versions of Unix.  In some cases procedures which can't be
implemented on particular systems may become no-ops, or perform limited
actions.  In other cases they may throw errors.

   General naming conventions are as follows:

   * The Scheme name is often identical to the name of the underlying
     Unix facility.

   * Underscores in Unix procedure names are converted to hyphens.

   * Procedures which destructively modify Scheme data have exclamation
     marks appended, e.g., `recv!'.

   * Predicates (returning only `#t' or `#f') have question marks
     appended, e.g., `access?'.

   * Some names are changed to avoid conflict with dissimilar interfaces
     defined by scsh, e.g., `primitive-fork'.

   * Unix preprocessor names such as `EPERM' or `R_OK' are converted to
     Scheme variables of the same name (underscores are not replaced
     with hyphens).

   Unexpected conditions are generally handled by raising exceptions.
There are a few procedures which return a special value if they don't
succeed, e.g., `getenv' returns `#f' if it the requested string is not
found in the environment.  These cases are noted in the documentation.

   For ways to deal with exceptions, *Note Exceptions::.

   Errors which the C-library would report by returning a NULL pointer
or through some other means are reported by raising a `system-error'
exception.  The value of the Unix `errno' variable is available in the
data passed by the exception.

   It can be extracted with the function `system-error-errno':

     (catch
      'system-error
      (lambda ()
        (mkdir "/this-ought-to-fail-if-I'm-not-root"))
      (lambda stuff
        (let ((errno (system-error-errno stuff)))
          (cond
           ((= errno EACCES)
            (display "You're not allowed to do that."))
           ((= errno EEXIST)
            (display "Already exists."))
           (#t
            (display (strerror errno))))
          (newline))))


File: guile.info,  Node: Ports and File Descriptors,  Next: File System,  Prev: Conventions,  Up: POSIX

38.2 Ports and File Descriptors
===============================

Conventions generally follow those of scsh, *Note The Scheme shell
(scsh)::.

   File ports are implemented using low-level operating system I/O
facilities, with optional buffering to improve efficiency *note File
Ports::

   Note that some procedures (e.g., `recv!') will accept ports as
arguments, but will actually operate directly on the file descriptor
underlying the port.  Any port buffering is ignored, including the
buffer which implements `peek-char' and `unread-char'.

   The `force-output' and `drain-input' procedures can be used to clear
the buffers.

   Each open file port has an associated operating system file
descriptor.  File descriptors are generally not useful in Scheme
programs; however they may be needed when interfacing with foreign code
and the Unix environment.

   A file descriptor can be extracted from a port and a new port can be
created from a file descriptor.  However a file descriptor is just an
integer and the garbage collector doesn't recognize it as a reference
to the port.  If all other references to the port were dropped, then
it's likely that the garbage collector would free the port, with the
side-effect of closing the file descriptor prematurely.

   To assist the programmer in avoiding this problem, each port has an
associated "revealed count" which can be used to keep track of how many
times the underlying file descriptor has been stored in other places.
If a port's revealed count is greater than zero, the file descriptor
will not be closed when the port is garbage collected.  A programmer
can therefore ensure that the revealed count will be greater than zero
if the file descriptor is needed elsewhere.

   For the simple case where a file descriptor is "imported" once to
become a port, it does not matter if the file descriptor is closed when
the port is garbage collected.  There is no need to maintain a revealed
count.  Likewise when "exporting" a file descriptor to the external
environment, setting the revealed count is not required provided the
port is kept open (i.e., is pointed to by a live Scheme binding) while
the file descriptor is in use.

   To correspond with traditional Unix behaviour, the three file
descriptors (0, 1 and 2) are automatically imported when a program
starts up and assigned to the initial values of the current input,
output and error ports.  The revealed count for each is initially set to
one, so that dropping references to one of these ports will not result
in its garbage collection: it could be retrieved with fdopen or
fdes->ports.

 -- Scheme Procedure: port-revealed port
 -- C Function: scm_port_revealed (port)
     Return the revealed count for PORT.

 -- Scheme Procedure: set-port-revealed! port rcount
 -- C Function: scm_set_port_revealed_x (port, rcount)
     Sets the revealed count for a port to a given value.  The return
     value is unspecified.

 -- Scheme Procedure: fileno port
 -- C Function: scm_fileno (port)
     Return the integer file descriptor underlying PORT.  Does not
     change its revealed count.

 -- Scheme Procedure: port->fdes port
     Returns the integer file descriptor underlying PORT.  As a side
     effect the revealed count of PORT is incremented.

 -- Scheme Procedure: fdopen fdes modes
 -- C Function: scm_fdopen (fdes, modes)
     Return a new port based on the file descriptor FDES.  Modes are
     given by the string MODES.  The revealed count of the port is
     initialized to zero.  The modes string is the same as that
     accepted by *Note open-file: File Ports.

 -- Scheme Procedure: fdes->ports fd
 -- C Function: scm_fdes_to_ports (fd)
     Return a list of existing ports which have FDES as an underlying
     file descriptor, without changing their revealed counts.

 -- Scheme Procedure: fdes->inport fdes
     Returns an existing input port which has FDES as its underlying
     file descriptor, if one exists, and increments its revealed count.
     Otherwise, returns a new input port with a revealed count of 1.

 -- Scheme Procedure: fdes->outport fdes
     Returns an existing output port which has FDES as its underlying
     file descriptor, if one exists, and increments its revealed count.
     Otherwise, returns a new output port with a revealed count of 1.

 -- Scheme Procedure: primitive-move->fdes port fd
 -- C Function: scm_primitive_move_to_fdes (port, fd)
     Moves the underlying file descriptor for PORT to the integer value
     FDES without changing the revealed count of PORT.  Any other ports
     already using this descriptor will be automatically shifted to new
     descriptors and their revealed counts reset to zero.  The return
     value is `#f' if the file descriptor already had the required
     value or `#t' if it was moved.

 -- Scheme Procedure: move->fdes port fdes
     Moves the underlying file descriptor for PORT to the integer value
     FDES and sets its revealed count to one.  Any other ports already
     using this descriptor will be automatically shifted to new
     descriptors and their revealed counts reset to zero.  The return
     value is unspecified.

 -- Scheme Procedure: release-port-handle port
     Decrements the revealed count for a port.

 -- Scheme Procedure: fsync object
 -- C Function: scm_fsync (object)
     Copies any unwritten data for the specified output file descriptor
     to disk.  If PORT/FD is a port, its buffer is flushed before the
     underlying file descriptor is fsync'd.  The return value is
     unspecified.

 -- Scheme Procedure: open path flags [mode]
 -- C Function: scm_open (path, flags, mode)
     Open the file named by PATH for reading and/or writing.  FLAGS is
     an integer specifying how the file should be opened.  MODE is an
     integer specifying the permission bits of the file, if it needs to
     be created, before the umask is applied.  The default is 666 (Unix
     itself has no default).

     FLAGS can be constructed by combining variables using `logior'.
     Basic flags are:

      -- Variabele: O_RDONLY
          Open the file read-only.

      -- Variabele: O_WRONLY
          Open the file write-only.

      -- Variabele: O_RDWR
          Open the file read/write.

      -- Variabele: O_APPEND
          Append to the file instead of truncating.

      -- Variabele: O_CREAT
          Create the file if it does not already exist.

     See the Unix documentation of the `open' system call for
     additional flags.

 -- Scheme Procedure: open-fdes path flags [mode]
 -- C Function: scm_open_fdes (path, flags, mode)
     Similar to `open' but return a file descriptor instead of a port.

 -- Scheme Procedure: close fd_or_port
 -- C Function: scm_close (fd_or_port)
     Similar to close-port (*note close-port: Closing.), but also works
     on file descriptors.  A side effect of closing a file descriptor
     is that any ports using that file descriptor are moved to a
     different file descriptor and have their revealed counts set to
     zero.

 -- Scheme Procedure: close-fdes fd
 -- C Function: scm_close_fdes (fd)
     A simple wrapper for the `close' system call.  Close file
     descriptor FD, which must be an integer.  Unlike close (*note
     close: Ports and File Descriptors.), the file descriptor will be
     closed even if a port is using it.  The return value is
     unspecified.

 -- Scheme Procedure: unread-char char [port]
 -- C Function: scm_unread_char (char, port)
     Place CHAR in PORT so that it will be read by the next read
     operation.  If called multiple times, the unread characters will
     be read again in last-in first-out order.  If PORT is not
     supplied, the current input port is used.

 -- Scheme Procedure: unread-string str port
     Place the string STR in PORT so that its characters will be read
     in subsequent read operations.  If called multiple times, the
     unread characters will be read again in last-in first-out order.
     If PORT is not supplied, the current-input-port is used.

 -- Scheme Procedure: pipe
 -- C Function: scm_pipe ()
     Return a newly created pipe: a pair of ports which are linked
     together on the local machine.  The _car_ is the input port and
     the _cdr_ is the output port.  Data written (and flushed) to the
     output port can be read from the input port.  Pipes are commonly
     used for communication with a newly forked child process.  The
     need to flush the output port can be avoided by making it
     unbuffered using `setvbuf'.

     Writes occur atomically provided the size of the data in bytes is
     not greater than the value of `PIPE_BUF'.  Note that the output
     port is likely to block if too much data (typically equal to
     `PIPE_BUF') has been written but not yet read from the input port.

   The next group of procedures perform a `dup2' system call, if NEWFD
(an integer) is supplied, otherwise a `dup'.  The file descriptor to be
duplicated can be supplied as an integer or contained in a port.  The
type of value returned varies depending on which procedure is used.

   All procedures also have the side effect when performing `dup2' that
any ports using NEWFD are moved to a different file descriptor and have
their revealed counts set to zero.

 -- Scheme Procedure: dup->fdes fd_or_port [fd]
 -- C Function: scm_dup_to_fdes (fd_or_port, fd)
     Return a new integer file descriptor referring to the open file
     designated by FD_OR_PORT, which must be either an open file port
     or a file descriptor.

 -- Scheme Procedure: dup->inport port/fd [newfd]
     Returns a new input port using the new file descriptor.

 -- Scheme Procedure: dup->outport port/fd [newfd]
     Returns a new output port using the new file descriptor.

 -- Scheme Procedure: dup port/fd [newfd]
     Returns a new port if PORT/FD is a port, with the same mode as the
     supplied port, otherwise returns an integer file descriptor.

 -- Scheme Procedure: dup->port port/fd mode [newfd]
     Returns a new port using the new file descriptor.  MODE supplies a
     mode string for the port (*note open-file: File Ports.).

 -- Scheme Procedure: duplicate-port port modes
     Returns a new port which is opened on a duplicate of the file
     descriptor underlying PORT, with mode string MODES as for *Note
     open-file: File Ports.  The two ports will share a file position
     and file status flags.

     Unexpected behaviour can result if both ports are subsequently used
     and the original and/or duplicate ports are buffered.  The mode
     string can include `0' to obtain an unbuffered duplicate port.

     This procedure is equivalent to `(dup->port PORT MODES)'.

 -- Scheme Procedure: redirect-port old new
 -- C Function: scm_redirect_port (old, new)
     This procedure takes two ports and duplicates the underlying file
     descriptor from OLD-PORT into NEW-PORT.  The current file
     descriptor in NEW-PORT will be closed.  After the redirection the
     two ports will share a file position and file status flags.

     The return value is unspecified.

     Unexpected behaviour can result if both ports are subsequently used
     and the original and/or duplicate ports are buffered.

     This procedure does not have any side effects on other ports or
     revealed counts.

 -- Scheme Procedure: dup2 oldfd newfd
 -- C Function: scm_dup2 (oldfd, newfd)
     A simple wrapper for the `dup2' system call.  Copies the file
     descriptor OLDFD to descriptor number NEWFD, replacing the
     previous meaning of NEWFD.  Both OLDFD and NEWFD must be integers.
     Unlike for dup->fdes or primitive-move->fdes, no attempt is made
     to move away ports which are using NEWFD.  The return value is
     unspecified.

 -- Scheme Procedure: port-mode port
     Return the port modes associated with the open port PORT.  These
     will not necessarily be identical to the modes used when the port
     was opened, since modes such as "append" which are used only
     during port creation are not retained.

 -- Scheme Procedure: port-for-each proc
 -- C Function: scm_port_for_each (proc)
     Apply PROC to each port in the Guile port table in turn.  The
     return value is unspecified.  More specifically, PROC is applied
     exactly once to every port that exists in the system at the time
     PORT-FOR-EACH is invoked.  Changes to the port table while
     PORT-FOR-EACH is running have no effect as far as PORT-FOR-EACH is
     concerned.

 -- Scheme Procedure: setvbuf port mode [size]
 -- C Function: scm_setvbuf (port, mode, size)
     Set the buffering mode for PORT.  MODE can be:
    `_IONBF'
          non-buffered

    `_IOLBF'
          line buffered

    `_IOFBF'
          block buffered, using a newly allocated buffer of SIZE bytes.
          If SIZE is omitted, a default size will be used.

 -- Scheme Procedure: fcntl object cmd [value]
 -- C Function: scm_fcntl (object, cmd, value)
     Apply COMMAND to the specified file descriptor or the underlying
     file descriptor of the specified port.  VALUE is an optional
     integer argument.

     Values for COMMAND are:

    `F_DUPFD'
          Duplicate a file descriptor

    `F_GETFD'
          Get flags associated with the file descriptor.

    `F_SETFD'
          Set flags associated with the file descriptor to VALUE.

    `F_GETFL'
          Get flags associated with the open file.

    `F_SETFL'
          Set flags associated with the open file to VALUE

    `F_GETOWN'
          Get the process ID of a socket's owner, for `SIGIO' signals.

    `F_SETOWN'
          Set the process that owns a socket to VALUE, for `SIGIO'
          signals.

    `FD_CLOEXEC'
          The value used to indicate the "close on exec" flag with
          `F_GETFL' or `F_SETFL'.

 -- Scheme Procedure: flock file operation
 -- C Function: scm_flock (file, operation)
     Apply or remove an advisory lock on an open file.  OPERATION
     specifies the action to be done:
    `LOCK_SH'
          Shared lock.  More than one process may hold a shared lock
          for a given file at a given time.

    `LOCK_EX'
          Exclusive lock.  Only one process may hold an exclusive lock
          for a given file at a given time.

    `LOCK_UN'
          Unlock the file.

    `LOCK_NB'
          Don't block when locking.  May be specified by bitwise OR'ing
          it to one of the other operations.
     The return value is not specified. FILE may be an open file
     descriptor or an open file descriptor port.

 -- Scheme Procedure: select reads writes excepts [secs [usecs]]
 -- C Function: scm_select (reads, writes, excepts, secs, usecs)
     This procedure has a variety of uses: waiting for the ability to
     provide input, accept output, or the existence of exceptional
     conditions on a collection of ports or file descriptors, or
     waiting for a timeout to occur.  It also returns if interrupted by
     a signal.

     READS, WRITES and EXCEPTS can be lists or vectors, with each
     member a port or a file descriptor.  The value returned is a list
     of three corresponding lists or vectors containing only the
     members which meet the specified requirement.  The ability of port
     buffers to provide input or accept output is taken into account.
     Ordering of the input lists or vectors is not preserved.

     The optional arguments SECS and USECS specify the timeout.  Either
     SECS can be specified alone, as either an integer or a real
     number, or both SECS and USECS can be specified as integers, in
     which case USECS is an additional timeout expressed in
     microseconds.  If SECS is omitted or is `#f' then select will wait
     for as long as it takes for one of the other conditions to be
     satisfied.

     The scsh version of `select' differs as follows: Only vectors are
     accepted for the first three arguments.  The USECS argument is not
     supported.  Multiple values are returned instead of a list.
     Duplicates in the input vectors appear only once in output.  An
     additional `select!' interface is provided.


File: guile.info,  Node: File System,  Next: User Information,  Prev: Ports and File Descriptors,  Up: POSIX

38.3 File System
================

These procedures allow querying and setting file system attributes
(such as owner, permissions, sizes and types of files); deleting,
copying, renaming and linking files; creating and removing directories
and querying their contents; syncing the file system and creating
special files.

 -- Scheme Procedure: access? path how
 -- C Function: scm_access (path, how)
     Return `#t' if PATH corresponds to an existing file and the
     current process has the type of access specified by HOW, otherwise
     `#f'.  HOW should be specified using the values of the variables
     listed below.  Multiple values can be combined using a bitwise or,
     in which case `#t' will only be returned if all accesses are
     granted.

     Permissions are checked using the real id of the current process,
     not the effective id, although it's the effective id which
     determines whether the access would actually be granted.

      -- Variabele: R_OK
          test for read permission.

      -- Variabele: W_OK
          test for write permission.

      -- Variabele: X_OK
          test for execute permission.

      -- Variabele: F_OK
          test for existence of the file.

 -- Scheme Procedure: stat object
 -- C Function: scm_stat (object)
     Return an object containing various information about the file
     determined by OBJ.  OBJ can be a string containing a file name or
     a port or integer file descriptor which is open on a file (in
     which case `fstat' is used as the underlying system call).

     The object returned by `stat' can be passed as a single parameter
     to the following procedures, all of which return integers:

    `stat:dev'
          The device containing the file.

    `stat:ino'
          The file serial number, which distinguishes this file from all
          other files on the same device.

    `stat:mode'
          The mode of the file.  This includes file type information and
          the file permission bits.  See `stat:type' and `stat:perms'
          below.

    `stat:nlink'
          The number of hard links to the file.

    `stat:uid'
          The user ID of the file's owner.

    `stat:gid'
          The group ID of the file.

    `stat:rdev'
          Device ID; this entry is defined only for character or block
          special files.

    `stat:size'
          The size of a regular file in bytes.

    `stat:atime'
          The last access time for the file.

    `stat:mtime'
          The last modification time for the file.

    `stat:ctime'
          The last modification time for the attributes of the file.

    `stat:blksize'
          The optimal block size for reading or writing the file, in
          bytes.

    `stat:blocks'
          The amount of disk space that the file occupies measured in
          units of 512 byte blocks.

     In addition, the following procedures return the information from
     stat:mode in a more convenient form:

    `stat:type'
          A symbol representing the type of file.  Possible values are
          regular, directory, symlink, block-special, char-special,
          fifo, socket and unknown

    `stat:perms'
          An integer representing the access permission bits.

 -- Scheme Procedure: lstat str
 -- C Function: scm_lstat (str)
     Similar to `stat', but does not follow symbolic links, i.e., it
     will return information about a symbolic link itself, not the file
     it points to.  PATH must be a string.

 -- Scheme Procedure: readlink path
 -- C Function: scm_readlink (path)
     Return the value of the symbolic link named by PATH (a string),
     i.e., the file that the link points to.

 -- Scheme Procedure: chown object owner group
 -- C Function: scm_chown (object, owner, group)
     Change the ownership and group of the file referred to by OBJECT to
     the integer values OWNER and GROUP.  OBJECT can be a string
     containing a file name or, if the platform supports fchown, a port
     or integer file descriptor which is open on the file.  The return
     value is unspecified.

     If OBJECT is a symbolic link, either the ownership of the link or
     the ownership of the referenced file will be changed depending on
     the operating system (lchown is unsupported at present).  If OWNER
     or GROUP is specified as `-1', then that ID is not changed.

 -- Scheme Procedure: chmod object mode
 -- C Function: scm_chmod (object, mode)
     Changes the permissions of the file referred to by OBJ.  OBJ can
     be a string containing a file name or a port or integer file
     descriptor which is open on a file (in which case `fchmod' is used
     as the underlying system call).  MODE specifies the new
     permissions as a decimal number, e.g., `(chmod "foo" #o755)'.  The
     return value is unspecified.

 -- Scheme Procedure: utime pathname [actime [modtime]]
 -- C Function: scm_utime (pathname, actime, modtime)
     `utime' sets the access and modification times for the file named
     by PATH.  If ACTIME or MODTIME is not supplied, then the current
     time is used.  ACTIME and MODTIME must be integer time values as
     returned by the `current-time' procedure.
          (utime "foo" (- (current-time) 3600))
     will set the access time to one hour in the past and the
     modification time to the current time.

 -- Scheme Procedure: delete-file str
 -- C Function: scm_delete_file (str)
     Deletes (or "unlinks") the file specified by PATH.

 -- Scheme Procedure: copy-file oldfile newfile
 -- C Function: scm_copy_file (oldfile, newfile)
     Copy the file specified by PATH-FROM to PATH-TO.  The return value
     is unspecified.

 -- Scheme Procedure: rename-file oldname newname
 -- C Function: scm_rename (oldname, newname)
     Renames the file specified by OLDNAME to NEWNAME.  The return
     value is unspecified.

 -- Scheme Procedure: link oldpath newpath
 -- C Function: scm_link (oldpath, newpath)
     Creates a new name NEWPATH in the file system for the file named
     by OLDPATH.  If OLDPATH is a symbolic link, the link may or may
     not be followed depending on the system.

 -- Scheme Procedure: symlink oldpath newpath
 -- C Function: scm_symlink (oldpath, newpath)
     Create a symbolic link named PATH-TO with the value (i.e.,
     pointing to) PATH-FROM.  The return value is unspecified.

 -- Scheme Procedure: mkdir path [mode]
 -- C Function: scm_mkdir (path, mode)
     Create a new directory named by PATH.  If MODE is omitted then the
     permissions of the directory file are set using the current umask.
     Otherwise they are set to the decimal value specified with MODE.
     The return value is unspecified.

 -- Scheme Procedure: rmdir path
 -- C Function: scm_rmdir (path)
     Remove the existing directory named by PATH.  The directory must
     be empty for this to succeed.  The return value is unspecified.

 -- Scheme Procedure: opendir dirname
 -- C Function: scm_opendir (dirname)
     Open the directory specified by PATH and return a directory stream.

 -- Scheme Procedure: directory-stream? obj
 -- C Function: scm_directory_stream_p (obj)
     Return a boolean indicating whether OBJECT is a directory stream
     as returned by `opendir'.

 -- Scheme Procedure: readdir port
 -- C Function: scm_readdir (port)
     Return (as a string) the next directory entry from the directory
     stream STREAM.  If there is no remaining entry to be read then the
     end of file object is returned.

 -- Scheme Procedure: rewinddir port
 -- C Function: scm_rewinddir (port)
     Reset the directory port STREAM so that the next call to `readdir'
     will return the first directory entry.

 -- Scheme Procedure: closedir port
 -- C Function: scm_closedir (port)
     Close the directory stream STREAM.  The return value is
     unspecified.

   Here is an example showing how to display all the entries in a
directory:

     (define dir (opendir "/usr/lib"))
     (do ((entry (readdir dir) (readdir dir)))
         ((eof-object? entry))
       (display entry)(newline))
     (closedir dir)

 -- Scheme Procedure: sync
 -- C Function: scm_sync ()
     Flush the operating system disk buffers.  The return value is
     unspecified.

 -- Scheme Procedure: mknod path type perms dev
 -- C Function: scm_mknod (path, type, perms, dev)
     Creates a new special file, such as a file corresponding to a
     device.  PATH specifies the name of the file.  TYPE should be one
     of the following symbols: regular, directory, symlink,
     block-special, char-special, fifo, or socket.  PERMS (an integer)
     specifies the file permissions.  DEV (an integer) specifies which
     device the special file refers to.  Its exact interpretation
     depends on the kind of special file being created.

     E.g.,
          (mknod "/dev/fd0" 'block-special #o660 (+ (* 2 256) 2))

     The return value is unspecified.

 -- Scheme Procedure: tmpnam
 -- C Function: scm_tmpnam ()
     Return a name in the file system that does not match any existing
     file.  However there is no guarantee that another process will not
     create the file after `tmpnam' is called.  Care should be taken if
     opening the file, e.g., use the `O_EXCL' open flag or use
     `mkstemp!' instead.

 -- Scheme Procedure: mkstemp! tmpl
 -- C Function: scm_mkstemp (tmpl)
     Create a new unique file in the file system and returns a new
     buffered port open for reading and writing to the file.  TMPL is a
     string specifying where the file should be created: it must end
     with `XXXXXX' and will be changed in place to return the name of
     the temporary file.

 -- Scheme Procedure: dirname filename
 -- C Function: scm_dirname (filename)
     Return the directory name component of the file name FILENAME. If
     FILENAME does not contain a directory component, `.' is returned.

 -- Scheme Procedure: basename filename [suffix]
 -- C Function: scm_basename (filename, suffix)
     Return the base name of the file name FILENAME. The base name is
     the file name without any directory components.  If SUFFIX is
     provided, and is equal to the end of BASENAME, it is removed also.

          (basename "/tmp/test.xml" ".xml")
          => "test"


File: guile.info,  Node: User Information,  Next: Time,  Prev: File System,  Up: POSIX

38.4 User Information
=====================

The facilities in this section provide an interface to the user and
group database.  They should be used with care since they are not
reentrant.

   The following functions accept an object representing user
information and return a selected component:

`passwd:name'
     The name of the userid.

`passwd:passwd'
     The encrypted passwd.

`passwd:uid'
     The user id number.

`passwd:gid'
     The group id number.

`passwd:gecos'
     The full name.

`passwd:dir'
     The home directory.

`passwd:shell'
     The login shell.

 -- Scheme Procedure: getpwuid uid
     Look up an integer userid in the user database.

 -- Scheme Procedure: getpwnam name
     Look up a user name string in the user database.

 -- Scheme Procedure: setpwent
     Initializes a stream used by `getpwent' to read from the user
     database.  The next use of `getpwent' will return the first entry.
     The return value is unspecified.

 -- Scheme Procedure: getpwent
     Return the next entry in the user database, using the stream set by
     `setpwent'.

 -- Scheme Procedure: endpwent
     Closes the stream used by `getpwent'.  The return value is
     unspecified.

 -- Scheme Procedure: setpw [arg]
 -- C Function: scm_setpwent (arg)
     If called with a true argument, initialize or reset the password
     data stream.  Otherwise, close the stream.  The `setpwent' and
     `endpwent' procedures are implemented on top of this.

 -- Scheme Procedure: getpw [user]
 -- C Function: scm_getpwuid (user)
     Look up an entry in the user database.  OBJ can be an integer, a
     string, or omitted, giving the behaviour of getpwuid, getpwnam or
     getpwent respectively.

   The following functions accept an object representing group
information and return a selected component:

`group:name'
     The group name.

`group:passwd'
     The encrypted group password.

`group:gid'
     The group id number.

`group:mem'
     A list of userids which have this group as a supplementary group.

 -- Scheme Procedure: getgrgid gid
     Look up an integer group id in the group database.

 -- Scheme Procedure: getgrnam name
     Look up a group name in the group database.

 -- Scheme Procedure: setgrent
     Initializes a stream used by `getgrent' to read from the group
     database.  The next use of `getgrent' will return the first entry.
     The return value is unspecified.

 -- Scheme Procedure: getgrent
     Return the next entry in the group database, using the stream set
     by `setgrent'.

 -- Scheme Procedure: endgrent
     Closes the stream used by `getgrent'.  The return value is
     unspecified.

 -- Scheme Procedure: setgr [arg]
 -- C Function: scm_setgrent (arg)
     If called with a true argument, initialize or reset the group data
     stream.  Otherwise, close the stream.  The `setgrent' and
     `endgrent' procedures are implemented on top of this.

 -- Scheme Procedure: getgr [name]
 -- C Function: scm_getgrgid (name)
     Look up an entry in the group database.  OBJ can be an integer, a
     string, or omitted, giving the behaviour of getgrgid, getgrnam or
     getgrent respectively.

   In addition to the accessor procedures for the user database, the
following shortcut procedures are also available.

 -- Scheme Procedure: cuserid
 -- C Function: scm_cuserid ()
     Return a string containing a user name associated with the
     effective user id of the process.  Return `#f' if this information
     cannot be obtained.

 -- Scheme Procedure: getlogin
 -- C Function: scm_getlogin ()
     Return a string containing the name of the user logged in on the
     controlling terminal of the process, or `#f' if this information
     cannot be obtained.


File: guile.info,  Node: Time,  Next: Runtime Environment,  Prev: User Information,  Up: POSIX

38.5 Time
=========

 -- Scheme Procedure: current-time
 -- C Function: scm_current_time ()
     Return the number of seconds since 1970-01-01 00:00:00 UTC,
     excluding leap seconds.

 -- Scheme Procedure: gettimeofday
 -- C Function: scm_gettimeofday ()
     Return a pair containing the number of seconds and microseconds
     since 1970-01-01 00:00:00 UTC, excluding leap seconds.  Note:
     whether true microsecond resolution is available depends on the
     operating system.

   The following procedures either accept an object representing a
broken down time and return a selected component, or accept an object
representing a broken down time and a value and set the component to
the value.  The numbers in parentheses give the usual range.

`tm:sec, set-tm:sec'
     Seconds (0-59).

`tm:min, set-tm:min'
     Minutes (0-59).

`tm:hour, set-tm:hour'
     Hours (0-23).

`tm:mday, set-tm:mday'
     Day of the month (1-31).

`tm:mon, set-tm:mon'
     Month (0-11).

`tm:year, set-tm:year'
     Year (70-), the year minus 1900.

`tm:wday, set-tm:wday'
     Day of the week (0-6) with Sunday represented as 0.

`tm:yday, set-tm:yday'
     Day of the year (0-364, 365 in leap years).

`tm:isdst, set-tm:isdst'
     Daylight saving indicator (0 for "no", greater than 0 for "yes",
     less than 0 for "unknown").

`tm:gmtoff, set-tm:gmtoff'
     Time zone offset in seconds west of UTC (-46800 to 43200).

`tm:zone, set-tm:zone'
     Time zone label (a string), not necessarily unique.

 -- Scheme Procedure: localtime time [zone]
 -- C Function: scm_localtime (time, zone)
     Return an object representing the broken down components of TIME,
     an integer like the one returned by `current-time'.  The time zone
     for the calculation is optionally specified by ZONE (a string),
     otherwise the `TZ' environment variable or the system default is
     used.

 -- Scheme Procedure: gmtime time
 -- C Function: scm_gmtime (time)
     Return an object representing the broken down components of TIME,
     an integer like the one returned by `current-time'.  The values
     are calculated for UTC.

 -- Scheme Procedure: mktime sbd_time [zone]
 -- C Function: scm_mktime (sbd_time, zone)
     BD-TIME is an object representing broken down time and `zone' is
     an optional time zone specifier (otherwise the TZ environment
     variable or the system default is used).

     Returns a pair: the car is a corresponding integer time value like
     that returned by `current-time'; the cdr is a broken down time
     object, similar to as BD-TIME but with normalized values.

 -- Scheme Procedure: tzset
 -- C Function: scm_tzset ()
     Initialize the timezone from the TZ environment variable or the
     system default.  It's not usually necessary to call this procedure
     since it's done automatically by other procedures that depend on
     the timezone.

 -- Scheme Procedure: strftime format stime
 -- C Function: scm_strftime (format, stime)
     Formats a time specification TIME using TEMPLATE.  TIME is an
     object with time components in the form returned by `localtime' or
     `gmtime'.  TEMPLATE is a string which can include formatting
     specifications introduced by a `%' character.  The formatting of
     month and day names is dependent on the current locale.  The value
     returned is the formatted string.  *Note Formatting Date and Time:
     (libc)Formatting Date and Time.)

          (strftime "%c" (localtime (current-time)))
          => "Mon Mar 11 20:17:43 2002"

 -- Scheme Procedure: strptime format string
 -- C Function: scm_strptime (format, string)
     Performs the reverse action to `strftime', parsing STRING
     according to the specification supplied in TEMPLATE.  The
     interpretation of month and day names is dependent on the current
     locale.  The value returned is a pair.  The car has an object with
     time components in the form returned by `localtime' or `gmtime',
     but the time zone components are not usefully set.  The cdr
     reports the number of characters from STRING which were used for
     the conversion.

 -- Variabele: internal-time-units-per-second
     The value of this variable is the number of time units per second
     reported by the following procedures.

 -- Scheme Procedure: times
 -- C Function: scm_times ()
     Return an object with information about real and processor time.
     The following procedures accept such an object as an argument and
     return a selected component:

    `tms:clock'
          The current real time, expressed as time units relative to an
          arbitrary base.

    `tms:utime'
          The CPU time units used by the calling process.

    `tms:stime'
          The CPU time units used by the system on behalf of the calling
          process.

    `tms:cutime'
          The CPU time units used by terminated child processes of the
          calling process, whose status has been collected (e.g., using
          `waitpid').

    `tms:cstime'
          Similarly, the CPU times units used by the system on behalf of
          terminated child processes.

 -- Scheme Procedure: get-internal-real-time
 -- C Function: scm_get_internal_real_time ()
     Return the number of time units since the interpreter was started.

 -- Scheme Procedure: get-internal-run-time
 -- C Function: scm_get_internal_run_time ()
     Return the number of time units of processor time used by the
     interpreter.  Both _system_ and _user_ time are included but
     subprocesses are not.


File: guile.info,  Node: Runtime Environment,  Next: Processes,  Prev: Time,  Up: POSIX

38.6 Runtime Environment
========================

 -- Scheme Procedure: program-arguments
 -- Scheme Procedure: command-line
 -- C Function: scm_program_arguments ()
     Return the list of command line arguments passed to Guile, as a
     list of strings.  The list includes the invoked program name,
     which is usually `"guile"', but excludes switches and parameters
     for command line options like `-e' and `-l'.

 -- Scheme Procedure: getenv nam
 -- C Function: scm_getenv (nam)
     Looks up the string NAME in the current environment.  The return
     value is `#f' unless a string of the form `NAME=VALUE' is found,
     in which case the string `VALUE' is returned.

 -- Scheme Procedure: setenv name value
     Modifies the environment of the current process, which is also the
     default environment inherited by child processes.

     If VALUE is `#f', then NAME is removed from the environment.
     Otherwise, the string NAME=VALUE is added to the environment,
     replacing any existing string with name matching NAME.

     The return value is unspecified.

 -- Scheme Procedure: environ [env]
 -- C Function: scm_environ (env)
     If ENV is omitted, return the current environment (in the Unix
     sense) as a list of strings.  Otherwise set the current
     environment, which is also the default environment for child
     processes, to the supplied list of strings.  Each member of ENV
     should be of the form `NAME=VALUE' and values of `NAME' should not
     be duplicated.  If ENV is supplied then the return value is
     unspecified.

 -- Scheme Procedure: putenv str
 -- C Function: scm_putenv (str)
     Modifies the environment of the current process, which is also the
     default environment inherited by child processes.

     If STRING is of the form `NAME=VALUE' then it will be written
     directly into the environment, replacing any existing environment
     string with name matching `NAME'.  If STRING does not contain an
     equal sign, then any existing string with name matching STRING will
     be removed.

     The return value is unspecified.


File: guile.info,  Node: Processes,  Next: Signals,  Prev: Runtime Environment,  Up: POSIX

38.7 Processes
==============

 -- Scheme Procedure: chdir str
 -- C Function: scm_chdir (str)
     Change the current working directory to PATH.  The return value is
     unspecified.

 -- Scheme Procedure: getcwd
 -- C Function: scm_getcwd ()
     Return the name of the current working directory.

 -- Scheme Procedure: umask [mode]
 -- C Function: scm_umask (mode)
     If MODE is omitted, returns a decimal number representing the
     current file creation mask.  Otherwise the file creation mask is
     set to MODE and the previous value is returned.

     E.g., `(umask #o022)' sets the mask to octal 22, decimal 18.

 -- Scheme Procedure: chroot path
 -- C Function: scm_chroot (path)
     Change the root directory to that specified in PATH.  This
     directory will be used for path names beginning with `/'.  The
     root directory is inherited by all children of the current
     process.  Only the superuser may change the root directory.

 -- Scheme Procedure: getpid
 -- C Function: scm_getpid ()
     Return an integer representing the current process ID.

 -- Scheme Procedure: getgroups
 -- C Function: scm_getgroups ()
     Return a vector of integers representing the current supplementary
     group IDs.

 -- Scheme Procedure: getppid
 -- C Function: scm_getppid ()
     Return an integer representing the process ID of the parent
     process.

 -- Scheme Procedure: getuid
 -- C Function: scm_getuid ()
     Return an integer representing the current real user ID.

 -- Scheme Procedure: getgid
 -- C Function: scm_getgid ()
     Return an integer representing the current real group ID.

 -- Scheme Procedure: geteuid
 -- C Function: scm_geteuid ()
     Return an integer representing the current effective user ID.  If
     the system does not support effective IDs, then the real ID is
     returned.  `(feature? 'EIDs)' reports whether the system supports
     effective IDs.

 -- Scheme Procedure: getegid
 -- C Function: scm_getegid ()
     Return an integer representing the current effective group ID.  If
     the system does not support effective IDs, then the real ID is
     returned.  `(feature? 'EIDs)' reports whether the system supports
     effective IDs.

 -- Scheme Procedure: setuid id
 -- C Function: scm_setuid (id)
     Sets both the real and effective user IDs to the integer ID,
     provided the process has appropriate privileges.  The return value
     is unspecified.

 -- Scheme Procedure: setgid id
 -- C Function: scm_setgid (id)
     Sets both the real and effective group IDs to the integer ID,
     provided the process has appropriate privileges.  The return value
     is unspecified.

 -- Scheme Procedure: seteuid id
 -- C Function: scm_seteuid (id)
     Sets the effective user ID to the integer ID, provided the process
     has appropriate privileges.  If effective IDs are not supported,
     the real ID is set instead - `(feature? 'EIDs)' reports whether the
     system supports effective IDs.  The return value is unspecified.

 -- Scheme Procedure: setegid id
 -- C Function: scm_setegid (id)
     Sets the effective group ID to the integer ID, provided the process
     has appropriate privileges.  If effective IDs are not supported,
     the real ID is set instead - `(feature? 'EIDs)' reports whether the
     system supports effective IDs.  The return value is unspecified.

 -- Scheme Procedure: getpgrp
 -- C Function: scm_getpgrp ()
     Return an integer representing the current process group ID.  This
     is the POSIX definition, not BSD.

 -- Scheme Procedure: setpgid pid pgid
 -- C Function: scm_setpgid (pid, pgid)
     Move the process PID into the process group PGID.  PID or PGID
     must be integers: they can be zero to indicate the ID of the
     current process.  Fails on systems that do not support job control.
     The return value is unspecified.

 -- Scheme Procedure: setsid
 -- C Function: scm_setsid ()
     Creates a new session.  The current process becomes the session
     leader and is put in a new process group.  The process will be
     detached from its controlling terminal if it has one.  The return
     value is an integer representing the new process group ID.

 -- Scheme Procedure: waitpid pid [options]
 -- C Function: scm_waitpid (pid, options)
     This procedure collects status information from a child process
     which has terminated or (optionally) stopped.  Normally it will
     suspend the calling process until this can be done.  If more than
     one child process is eligible then one will be chosen by the
     operating system.

     The value of PID determines the behaviour:

    PID greater than 0
          Request status information from the specified child process.

    PID equal to -1 or WAIT_ANY
          Request status information for any child process.

    PID equal to 0 or WAIT_MYPGRP
          Request status information for any child process in the
          current process group.

    PID less than -1
          Request status information for any child process whose
          process group ID is -PID.

     The OPTIONS argument, if supplied, should be the bitwise OR of the
     values of zero or more of the following variables:

      -- Variabele: WNOHANG
          Return immediately even if there are no child processes to be
          collected.

      -- Variabele: WUNTRACED
          Report status information for stopped processes as well as
          terminated processes.

     The return value is a pair containing:

       1. The process ID of the child process, or 0 if `WNOHANG' was
          specified and no process was collected.

       2. The integer status value.

   The following three functions can be used to decode the process
status code returned by `waitpid'.

 -- Scheme Procedure: status:exit-val status
 -- C Function: scm_status_exit_val (status)
     Return the exit status value, as would be set if a process ended
     normally through a call to `exit' or `_exit', if any, otherwise
     `#f'.

 -- Scheme Procedure: status:term-sig status
 -- C Function: scm_status_term_sig (status)
     Return the signal number which terminated the process, if any,
     otherwise `#f'.

 -- Scheme Procedure: status:stop-sig status
 -- C Function: scm_status_stop_sig (status)
     Return the signal number which stopped the process, if any,
     otherwise `#f'.

 -- Scheme Procedure: system [cmd]
 -- C Function: scm_system (cmd)
     Execute CMD using the operating system's "command processor".
     Under Unix this is usually the default shell `sh'.  The value
     returned is CMD's exit status as returned by `waitpid', which can
     be interpreted using the functions above.

     If `system' is called without arguments, return a boolean
     indicating whether the command processor is available.

 -- Scheme Procedure: primitive-exit [status]
 -- C Function: scm_primitive_exit (status)
     Terminate the current process without unwinding the Scheme stack.
     This is would typically be useful after a fork.  The exit status
     is STATUS if supplied, otherwise zero.

 -- Scheme Procedure: execl filename . args
 -- C Function: scm_execl (filename, args)
     Executes the file named by PATH as a new process image.  The
     remaining arguments are supplied to the process; from a C program
     they are accessible as the `argv' argument to `main'.
     Conventionally the first ARG is the same as PATH.  All arguments
     must be strings.

     If ARG is missing, PATH is executed with a null argument list,
     which may have system-dependent side-effects.

     This procedure is currently implemented using the `execv' system
     call, but we call it `execl' because of its Scheme calling
     interface.

 -- Scheme Procedure: execlp filename . args
 -- C Function: scm_execlp (filename, args)
     Similar to `execl', however if FILENAME does not contain a slash
     then the file to execute will be located by searching the
     directories listed in the `PATH' environment variable.

     This procedure is currently implemented using the `execvp' system
     call, but we call it `execlp' because of its Scheme calling
     interface.

 -- Scheme Procedure: execle filename env . args
 -- C Function: scm_execle (filename, env, args)
     Similar to `execl', but the environment of the new process is
     specified by ENV, which must be a list of strings as returned by
     the `environ' procedure.

     This procedure is currently implemented using the `execve' system
     call, but we call it `execle' because of its Scheme calling
     interface.

 -- Scheme Procedure: primitive-fork
 -- C Function: scm_fork ()
     Creates a new "child" process by duplicating the current "parent"
     process.  In the child the return value is 0.  In the parent the
     return value is the integer process ID of the child.

     This procedure has been renamed from `fork' to avoid a naming
     conflict with the scsh fork.

 -- Scheme Procedure: nice incr
 -- C Function: scm_nice (incr)
     Increment the priority of the current process by INCR.  A higher
     priority value means that the process runs less often.  The return
     value is unspecified.

 -- Scheme Procedure: setpriority which who prio
 -- C Function: scm_setpriority (which, who, prio)
     Set the scheduling priority of the process, process group or user,
     as indicated by WHICH and WHO. WHICH is one of the variables
     `PRIO_PROCESS', `PRIO_PGRP' or `PRIO_USER', and WHO is interpreted
     relative to WHICH (a process identifier for `PRIO_PROCESS',
     process group identifier for `PRIO_PGRP', and a user identifier
     for `PRIO_USER'.  A zero value of WHO denotes the current process,
     process group, or user.  PRIO is a value in the range -20 and 20,
     the default priority is 0; lower priorities cause more favorable
     scheduling.  Sets the priority of all of the specified processes.
     Only the super-user may lower priorities.  The return value is not
     specified.

 -- Scheme Procedure: getpriority which who
 -- C Function: scm_getpriority (which, who)
     Return the scheduling priority of the process, process group or
     user, as indicated by WHICH and WHO. WHICH is one of the variables
     `PRIO_PROCESS', `PRIO_PGRP' or `PRIO_USER', and WHO is interpreted
     relative to WHICH (a process identifier for `PRIO_PROCESS',
     process group identifier for `PRIO_PGRP', and a user identifier
     for `PRIO_USER'.  A zero value of WHO denotes the current process,
     process group, or user.  Return the highest priority (lowest
     numerical value) of any of the specified processes.


File: guile.info,  Node: Signals,  Next: Terminals and Ptys,  Prev: Processes,  Up: POSIX

38.8 Signals
============

Procedures to raise, handle and wait for signals.

 -- Scheme Procedure: kill pid sig
 -- C Function: scm_kill (pid, sig)
     Sends a signal to the specified process or group of processes.

     PID specifies the processes to which the signal is sent:

    PID greater than 0
          The process whose identifier is PID.

    PID equal to 0
          All processes in the current process group.

    PID less than -1
          The process group whose identifier is -PID

    PID equal to -1
          If the process is privileged, all processes except for some
          special system processes.  Otherwise, all processes with the
          current effective user ID.

     SIG should be specified using a variable corresponding to the Unix
     symbolic name, e.g.,

      -- Variabele: SIGHUP
          Hang-up signal.

      -- Variabele: SIGINT
          Interrupt signal.

 -- Scheme Procedure: raise sig
 -- C Function: scm_raise (sig)
     Sends a specified signal SIG to the current process, where SIG is
     as described for the kill procedure.

 -- Scheme Procedure: sigaction signum [handler [flags]]
 -- C Function: scm_sigaction (signum, handler, flags)
     Install or report the signal handler for a specified signal.

     SIGNUM is the signal number, which can be specified using the value
     of variables such as `SIGINT'.

     If ACTION is omitted, `sigaction' returns a pair: the CAR is the
     current signal hander, which will be either an integer with the
     value `SIG_DFL' (default action) or `SIG_IGN' (ignore), or the
     Scheme procedure which handles the signal, or `#f' if a non-Scheme
     procedure handles the signal.  The CDR contains the current
     `sigaction' flags for the handler.

     If ACTION is provided, it is installed as the new handler for
     SIGNUM.  ACTION can be a Scheme procedure taking one argument, or
     the value of `SIG_DFL' (default action) or `SIG_IGN' (ignore), or
     `#f' to restore whatever signal handler was installed before
     `sigaction' was first used.  Flags can optionally be specified for
     the new handler (`SA_RESTART' will always be added if it's
     available and the system is using restartable system calls.)  The
     return value is a pair with information about the old handler as
     described above.

     This interface does not provide access to the "signal blocking"
     facility.  Maybe this is not needed, since the thread support may
     provide solutions to the problem of consistent access to data
     structures.

 -- Scheme Procedure: restore-signals
 -- C Function: scm_restore_signals ()
     Return all signal handlers to the values they had before any call
     to `sigaction' was made.  The return value is unspecified.

 -- Scheme Procedure: alarm i
 -- C Function: scm_alarm (i)
     Set a timer to raise a `SIGALRM' signal after the specified number
     of seconds (an integer).  It's advisable to install a signal
     handler for `SIGALRM' beforehand, since the default action is to
     terminate the process.

     The return value indicates the time remaining for the previous
     alarm, if any.  The new value replaces the previous alarm.  If
     there was no previous alarm, the return value is zero.

 -- Scheme Procedure: pause
 -- C Function: scm_pause ()
     Pause the current process (thread?) until a signal arrives whose
     action is to either terminate the current process or invoke a
     handler procedure.  The return value is unspecified.

 -- Scheme Procedure: sleep i
 -- C Function: scm_sleep (i)
     Wait for the given number of seconds (an integer) or until a signal
     arrives.  The return value is zero if the time elapses or the
     number of seconds remaining otherwise.

 -- Scheme Procedure: usleep i
 -- C Function: scm_usleep (i)
     Sleep for I microseconds.  `usleep' is not available on all
     platforms.

 -- Scheme Procedure: setitimer which_timer interval_seconds
          interval_microseconds value_seconds value_microseconds
 -- C Function: scm_setitimer (which_timer, interval_seconds,
          interval_microseconds, value_seconds, value_microseconds)
     Set the timer specified by WHICH_TIMER according to the given
     INTERVAL_SECONDS, INTERVAL_MICROSECONDS, VALUE_SECONDS, and
     VALUE_MICROSECONDS values.

     Return information about the timer's previous setting.  Errors are
     handled as described in the guile info pages under "POSIX
     Interface Conventions".

     The timers available are: `ITIMER_REAL', `ITIMER_VIRTUAL', and
     `ITIMER_PROF'.

     The return value will be a list of two cons pairs representing the
     current state of the given timer.  The first pair is the seconds
     and microseconds of the timer `it_interval', and the second pair is
     the seconds and microseconds of the timer `it_value'.

 -- Scheme Procedure: getitimer which_timer
 -- C Function: scm_getitimer (which_timer)
     Return information about the timer specified by WHICH_TIMER Errors
     are handled as described in the guile info pages under "POSIX
     Interface Conventions".

     The timers available are: `ITIMER_REAL', `ITIMER_VIRTUAL', and
     `ITIMER_PROF'.

     The return value will be a list of two cons pairs representing the
     current state of the given timer.  The first pair is the seconds
     and microseconds of the timer `it_interval', and the second pair is
     the seconds and microseconds of the timer `it_value'.


File: guile.info,  Node: Terminals and Ptys,  Next: Pipes,  Prev: Signals,  Up: POSIX

38.9 Terminals and Ptys
=======================

 -- Scheme Procedure: isatty? port
 -- C Function: scm_isatty_p (port)
     Return `#t' if PORT is using a serial non-file device, otherwise
     `#f'.

 -- Scheme Procedure: ttyname port
 -- C Function: scm_ttyname (port)
     Return a string with the name of the serial terminal device
     underlying PORT.

 -- Scheme Procedure: ctermid
 -- C Function: scm_ctermid ()
     Return a string containing the file name of the controlling
     terminal for the current process.

 -- Scheme Procedure: tcgetpgrp port
 -- C Function: scm_tcgetpgrp (port)
     Return the process group ID of the foreground process group
     associated with the terminal open on the file descriptor
     underlying PORT.

     If there is no foreground process group, the return value is a
     number greater than 1 that does not match the process group ID of
     any existing process group.  This can happen if all of the
     processes in the job that was formerly the foreground job have
     terminated, and no other job has yet been moved into the
     foreground.

 -- Scheme Procedure: tcsetpgrp port pgid
 -- C Function: scm_tcsetpgrp (port, pgid)
     Set the foreground process group ID for the terminal used by the
     file descriptor underlying PORT to the integer PGID.  The calling
     process must be a member of the same session as PGID and must have
     the same controlling terminal.  The return value is unspecified.


File: guile.info,  Node: Pipes,  Next: Networking,  Prev: Terminals and Ptys,  Up: POSIX

38.10 Pipes
===========

The following procedures provide an interface to the `popen' and
`pclose' system routines.  The code is in a separate "popen" module:

     (use-modules (ice-9 popen))

 -- Scheme Procedure: open-pipe command modes
     Executes the shell command COMMAND (a string) in a subprocess.  A
     pipe to the process is created and returned.  MODES specifies
     whether an input or output pipe to the process is created: it
     should be the value of `OPEN_READ' or `OPEN_WRITE'.

 -- Scheme Procedure: open-input-pipe command
     Equivalent to `open-pipe' with mode `OPEN_READ'.

          (read-line (open-input-pipe "date"))
          => "Mon Mar 11 20:10:44 GMT 2002"

          (waitpid WAIT_ANY)
          => (24160 . 0)

 -- Scheme Procedure: open-output-pipe command
     Equivalent to `open-pipe' with mode `OPEN_WRITE'.

 -- Scheme Procedure: close-pipe port
     Closes the pipe created by `open-pipe', then waits for the process
     to terminate and returns its status value, *Note waitpid:
     Processes, for information on how to interpret this value.

     `close-port' (*note close-port: Closing.) can also be used to
     close a pipe, but doesn't return the status.


File: guile.info,  Node: Networking,  Next: System Identification,  Prev: Pipes,  Up: POSIX

38.11 Networking
================

* Menu:

* Network Address Conversion::
* Network Databases::
* Network Sockets and Communication::
* Internet Socket Examples::


File: guile.info,  Node: Network Address Conversion,  Next: Network Databases,  Up: Networking

38.11.1 Network Address Conversion
----------------------------------

This section describes procedures which convert internet addresses
between numeric and string formats.

38.11.1.1 IPv4 Address Conversion
.................................

 -- Scheme Procedure: inet-aton address
 -- C Function: scm_inet_aton (address)
     Convert an IPv4 Internet address from printable string (dotted
     decimal notation) to an integer.  E.g.,

          (inet-aton "127.0.0.1") => 2130706433

 -- Scheme Procedure: inet-ntoa inetid
 -- C Function: scm_inet_ntoa (inetid)
     Convert an IPv4 Internet address to a printable (dotted decimal
     notation) string.  E.g.,

          (inet-ntoa 2130706433) => "127.0.0.1"

 -- Scheme Procedure: inet-netof address
 -- C Function: scm_inet_netof (address)
     Return the network number part of the given IPv4 Internet address.
     E.g.,

          (inet-netof 2130706433) => 127

 -- Scheme Procedure: inet-lnaof address
 -- C Function: scm_lnaof (address)
     Return the local-address-with-network part of the given IPv4
     Internet address, using the obsolete class A/B/C system.  E.g.,

          (inet-lnaof 2130706433) => 1

 -- Scheme Procedure: inet-makeaddr net lna
 -- C Function: scm_inet_makeaddr (net, lna)
     Make an IPv4 Internet address by combining the network number NET
     with the local-address-within-network number LNA.  E.g.,

          (inet-makeaddr 127 1) => 2130706433

38.11.1.2 IPv6 Address Conversion
.................................

 -- Scheme Procedure: inet-ntop family address
 -- C Function: scm_inet_ntop (family, address)
     Convert a network address into a printable string.  Note that
     unlike the C version of this function, the input is an integer
     with normal host byte ordering.  FAMILY can be `AF_INET' or
     `AF_INET6'.  E.g.,

          (inet-ntop AF_INET 2130706433) => "127.0.0.1"
          (inet-ntop AF_INET6 (- (expt 2 128) 1)) =>
          ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff

 -- Scheme Procedure: inet-pton family address
 -- C Function: scm_inet_pton (family, address)
     Convert a string containing a printable network address to an
     integer address.  Note that unlike the C version of this function,
     the result is an integer with normal host byte ordering.  FAMILY
     can be `AF_INET' or `AF_INET6'.  E.g.,

          (inet-pton AF_INET "127.0.0.1") => 2130706433
          (inet-pton AF_INET6 "::1") => 1


File: guile.info,  Node: Network Databases,  Next: Network Sockets and Communication,  Prev: Network Address Conversion,  Up: Networking

38.11.2 Network Databases
-------------------------

This section describes procedures which query various network databases.
Care should be taken when using the database routines since they are not
reentrant.

38.11.2.1 The Host Database
...........................

A "host object" is a structure that represents what is known about a
network host, and is the usual way of representing a system's network
identity inside software.

   The following functions accept a host object and return a selected
component:

 -- Scheme Procedure: hostent:name host
     The "official" hostname for HOST.

 -- Scheme Procedure: hostent:aliases host
     A list of aliases for HOST.

 -- Scheme Procedure: hostent:addrtype host
     The host address type.  For hosts with Internet addresses, this
     will return `AF_INET'.

 -- Scheme Procedure: hostent:length host
     The length of each address for HOST, in bytes.

 -- Scheme Procedure: hostent:addr-list host
     The list of network addresses associated with HOST.

   The following procedures are used to search the host database:

 -- Scheme Procedure: gethost [host]
 -- Scheme Procedure: gethostbyname hostname
 -- Scheme Procedure: gethostbyaddr address
 -- C Function: scm_gethost (host)
     Look up a host by name or address, returning a host object.  The
     `gethost' procedure will accept either a string name or an integer
     address; if given no arguments, it behaves like `gethostent' (see
     below).  If a name or address is supplied but the address can not
     be found, an error will be thrown to one of the keys:
     `host-not-found', `try-again', `no-recovery' or `no-data',
     corresponding to the equivalent `h_error' values.  Unusual
     conditions may result in errors thrown to the `system-error' or
     `misc_error' keys.

          (gethost "www.gnu.org")
          => #("www.gnu.org" () 2 4 (3353880842))

          (gethostbyname "www.emacs.org")
          => #("emacs.org" ("www.emacs.org") 2 4 (1073448978))

   The following procedures may be used to step through the host
database from beginning to end.

 -- Scheme Procedure: sethostent [stayopen]
     Initialize an internal stream from which host objects may be read.
     This procedure must be called before any calls to `gethostent',
     and may also be called afterward to reset the host entry stream.
     If STAYOPEN is supplied and is not `#f', the database is not
     closed by subsequent `gethostbyname' or `gethostbyaddr' calls,
     possibly giving an efficiency gain.

 -- Scheme Procedure: gethostent
     Return the next host object from the host database, or `#f' if
     there are no more hosts to be found (or an error has been
     encountered).  This procedure may not be used before `sethostent'
     has been called.

 -- Scheme Procedure: endhostent
     Close the stream used by `gethostent'.  The return value is
     unspecified.

 -- Scheme Procedure: sethost [stayopen]
 -- C Function: scm_sethost (stayopen)
     If STAYOPEN is omitted, this is equivalent to `endhostent'.
     Otherwise it is equivalent to `sethostent stayopen'.

38.11.2.2 The Network Database
..............................

The following functions accept an object representing a network and
return a selected component:

 -- Scheme Procedure: netent:name net
     The "official" network name.

 -- Scheme Procedure: netent:aliases net
     A list of aliases for the network.

 -- Scheme Procedure: netent:addrtype net
     The type of the network number.  Currently, this returns only
     `AF_INET'.

 -- Scheme Procedure: netent:net net
     The network number.

   The following procedures are used to search the network database:

 -- Scheme Procedure: getnet [net]
 -- Scheme Procedure: getnetbyname net-name
 -- Scheme Procedure: getnetbyaddr net-number
 -- C Function: scm_getnet (net)
     Look up a network by name or net number in the network database.
     The NET-NAME argument must be a string, and the NET-NUMBER
     argument must be an integer.  `getnet' will accept either type of
     argument, behaving like `getnetent' (see below) if no arguments are
     given.

   The following procedures may be used to step through the network
database from beginning to end.

 -- Scheme Procedure: setnetent [stayopen]
     Initialize an internal stream from which network objects may be
     read.  This procedure must be called before any calls to
     `getnetent', and may also be called afterward to reset the net
     entry stream.  If STAYOPEN is supplied and is not `#f', the
     database is not closed by subsequent `getnetbyname' or
     `getnetbyaddr' calls, possibly giving an efficiency gain.

 -- Scheme Procedure: getnetent
     Return the next entry from the network database.

 -- Scheme Procedure: endnetent
     Close the stream used by `getnetent'.  The return value is
     unspecified.

 -- Scheme Procedure: setnet [stayopen]
 -- C Function: scm_setnet (stayopen)
     If STAYOPEN is omitted, this is equivalent to `endnetent'.
     Otherwise it is equivalent to `setnetent stayopen'.

38.11.2.3 The Protocol Database
...............................

The following functions accept an object representing a protocol and
return a selected component:

 -- Scheme Procedure: protoent:name protocol
     The "official" protocol name.

 -- Scheme Procedure: protoent:aliases protocol
     A list of aliases for the protocol.

 -- Scheme Procedure: protoent:proto protocol
     The protocol number.

   The following procedures are used to search the protocol database:

 -- Scheme Procedure: getproto [protocol]
 -- Scheme Procedure: getprotobyname name
 -- Scheme Procedure: getprotobynumber number
 -- C Function: scm_getproto (protocol)
     Look up a network protocol by name or by number.  `getprotobyname'
     takes a string argument, and `getprotobynumber' takes an integer
     argument.  `getproto' will accept either type, behaving like
     `getprotoent' (see below) if no arguments are supplied.

   The following procedures may be used to step through the protocol
database from beginning to end.

 -- Scheme Procedure: setprotoent [stayopen]
     Initialize an internal stream from which protocol objects may be
     read.  This procedure must be called before any calls to
     `getprotoent', and may also be called afterward to reset the
     protocol entry stream.  If STAYOPEN is supplied and is not `#f',
     the database is not closed by subsequent `getprotobyname' or
     `getprotobynumber' calls, possibly giving an efficiency gain.

 -- Scheme Procedure: getprotoent
     Return the next entry from the protocol database.

 -- Scheme Procedure: endprotoent
     Close the stream used by `getprotoent'.  The return value is
     unspecified.

 -- Scheme Procedure: setproto [stayopen]
 -- C Function: scm_setproto (stayopen)
     If STAYOPEN is omitted, this is equivalent to `endprotoent'.
     Otherwise it is equivalent to `setprotoent stayopen'.

38.11.2.4 The Service Database
..............................

The following functions accept an object representing a service and
return a selected component:

 -- Scheme Procedure: servent:name serv
     The "official" name of the network service.

 -- Scheme Procedure: servent:aliases serv
     A list of aliases for the network service.

 -- Scheme Procedure: servent:port serv
     The Internet port used by the service.

 -- Scheme Procedure: servent:proto serv
     The protocol used by the service.  A service may be listed many
     times in the database under different protocol names.

   The following procedures are used to search the service database:

 -- Scheme Procedure: getserv [name [protocol]]
 -- Scheme Procedure: getservbyname name protocol
 -- Scheme Procedure: getservbyport port protocol
 -- C Function: scm_getserv (name, protocol)
     Look up a network service by name or by service number, and return
     a network service object.  The PROTOCOL argument specifies the name
     of the desired protocol; if the protocol found in the network
     service database does not match this name, a system error is
     signalled.

     The `getserv' procedure will take either a service name or number
     as its first argument; if given no arguments, it behaves like
     `getservent' (see below).

          (getserv "imap" "tcp")
          => #("imap2" ("imap") 143 "tcp")

          (getservbyport 88 "udp")
          => #("kerberos" ("kerberos5" "krb5") 88 "udp")

   The following procedures may be used to step through the service
database from beginning to end.

 -- Scheme Procedure: setservent [stayopen]
     Initialize an internal stream from which service objects may be
     read.  This procedure must be called before any calls to
     `getservent', and may also be called afterward to reset the
     service entry stream.  If STAYOPEN is supplied and is not `#f',
     the database is not closed by subsequent `getservbyname' or
     `getservbyport' calls, possibly giving an efficiency gain.

 -- Scheme Procedure: getservent
     Return the next entry from the services database.

 -- Scheme Procedure: endservent
     Close the stream used by `getservent'.  The return value is
     unspecified.

 -- Scheme Procedure: setserv [stayopen]
 -- C Function: scm_setserv (stayopen)
     If STAYOPEN is omitted, this is equivalent to `endservent'.
     Otherwise it is equivalent to `setservent stayopen'.


File: guile.info,  Node: Network Sockets and Communication,  Next: Internet Socket Examples,  Prev: Network Databases,  Up: Networking

38.11.3 Network Sockets and Communication
-----------------------------------------

Socket ports can be created using `socket' and `socketpair'.  The ports
are initially unbuffered, to make reading and writing to the same port
more reliable.  A buffer can be added to the port using `setvbuf',
*Note Ports and File Descriptors::.

   The convention used for "host" vs "network" addresses is that
addresses are always held in host order at the Scheme level.  The
procedures in this section automatically convert between host and
network order when required.  The arguments and return values are thus
in host order.

 -- Scheme Procedure: socket family style proto
 -- C Function: scm_socket (family, style, proto)
     Return a new socket port of the type specified by FAMILY, STYLE
     and PROTO.  All three parameters are integers.  Supported values
     for FAMILY are `PF_UNIX', `PF_INET' and `PF_INET6'.  Typical
     values for STYLE are `SOCK_STREAM', `SOCK_DGRAM', `SOCK_RAW',
     `SOCK_RDM' and `SOCK_SEQPACKET'.

     PROTO can be obtained from a protocol name using `getprotobyname'.
     A value of zero specifies the default protocol, which is usually
     right.

     A single socket port cannot by used for communication until it has
     been connected to another socket.

 -- Scheme Procedure: socketpair family style proto
 -- C Function: scm_socketpair (family, style, proto)
     Return a pair of connected (but unnamed) socket ports of the type
     specified by FAMILY, STYLE and PROTO.  Many systems support only
     socket pairs of the `AF_UNIX' family.  Zero is likely to be the
     only meaningful value for PROTO.

 -- Scheme Procedure: getsockopt sock level optname
 -- C Function: scm_getsockopt (sock, level, optname)
     Return the value of a particular socket option for the socket port
     SOCK.  LEVEL is an integer code for type of option being
     requested, e.g., `SOL_SOCKET' for socket-level options.  OPTNAME
     is an integer code for the option required and should be specified
     using one of the symbols `SO_DEBUG', `SO_REUSEADDR' etc.

     The returned value is typically an integer but `SO_LINGER' returns
     a pair of integers.

 -- Scheme Procedure: setsockopt sock level optname value
 -- C Function: scm_setsockopt (sock, level, optname, value)
     Set the value of a particular socket option for the socket port
     SOCK.  LEVEL is an integer code for type of option being set,
     e.g., `SOL_SOCKET' for socket-level options.  OPTNAME is an
     integer code for the option to set and should be specified using
     one of the symbols `SO_DEBUG', `SO_REUSEADDR' etc.  VALUE is the
     value to which the option should be set.  For most options this
     must be an integer, but for `SO_LINGER' it must be a pair.

     The return value is unspecified.

 -- Scheme Procedure: shutdown sock how
 -- C Function: scm_shutdown (sock, how)
     Sockets can be closed simply by using `close-port'. The `shutdown'
     procedure allows reception or transmission on a connection to be
     shut down individually, according to the parameter HOW:

    0
          Stop receiving data for this socket.  If further data
          arrives,  reject it.

    1
          Stop trying to transmit data from this socket.  Discard any
          data waiting to be sent.  Stop looking for acknowledgement of
          data already sent; don't retransmit it if it is lost.

    2
          Stop both reception and transmission.

     The return value is unspecified.

 -- Scheme Procedure: connect sock fam address . args
 -- C Function: scm_connect (sock, fam, address, args)
     Initiate a connection from a socket using a specified address
     family to the address specified by ADDRESS and possibly ARGS.  The
     format required for ADDRESS and ARGS depends on the family of the
     socket.

     For a socket of family `AF_UNIX', only ADDRESS is specified and
     must be a string with the filename where the socket is to be
     created.

     For a socket of family `AF_INET', ADDRESS must be an integer IPv4
     host address and ARGS must be a single integer port number.

     For a socket of family `AF_INET6', ADDRESS must be an integer IPv6
     host address and ARGS may be up to three integers: port [flowinfo]
     [scope_id], where flowinfo and scope_id default to zero.

     The return value is unspecified.

 -- Scheme Procedure: bind sock fam address . args
 -- C Function: scm_bind (sock, fam, address, args)
     Assign an address to the socket port SOCK.  Generally this only
     needs to be done for server sockets, so they know where to look
     for incoming connections.  A socket without an address will be
     assigned one automatically when it starts communicating.

     The format of ADDRESS and ARGS depends on the family of the socket.

     For a socket of family `AF_UNIX', only ADDRESS is specified and
     must be a string with the filename where the socket is to be
     created.

     For a socket of family `AF_INET', ADDRESS must be an integer IPv4
     address and ARGS must be a single integer port number.

     The values of the following variables can also be used for ADDRESS:

      -- Variabele: INADDR_ANY
          Allow connections from any address.

      -- Variabele: INADDR_LOOPBACK
          The address of the local host using the loopback device.

      -- Variabele: INADDR_BROADCAST
          The broadcast address on the local network.

      -- Variabele: INADDR_NONE
          No address.

     For a socket of family `AF_INET6', ADDRESS must be an integer IPv6
     address and ARGS may be up to three integers: port [flowinfo]
     [scope_id], where flowinfo and scope_id default to zero.

     The return value is unspecified.

 -- Scheme Procedure: listen sock backlog
 -- C Function: scm_listen (sock, backlog)
     Enable SOCK to accept connection requests.  BACKLOG is an integer
     specifying the maximum length of the queue for pending connections.
     If the queue fills, new clients will fail to connect until the
     server calls `accept' to accept a connection from the queue.

     The return value is unspecified.

 -- Scheme Procedure: accept sock
 -- C Function: scm_accept (sock)
     Accept a connection on a bound, listening socket.  If there are no
     pending connections in the queue, wait until one is available
     unless the non-blocking option has been set on the socket.

     The return value is a pair in which the _car_ is a new socket port
     for the connection and the _cdr_ is an object with address
     information about the client which initiated the connection.

     SOCK does not become part of the connection and will continue to
     accept new requests.

   The following functions take a socket address object, as returned by
`accept' and other procedures, and return a selected component.

`sockaddr:fam'
     The socket family, typically equal to the value of `AF_UNIX' or
     `AF_INET'.

`sockaddr:path'
     If the socket family is `AF_UNIX', returns the path of the
     filename the socket is based on.

`sockaddr:addr'
     If the socket family is `AF_INET', returns the Internet host
     address.

`sockaddr:port'
     If the socket family is `AF_INET', returns the Internet port
     number.

 -- Scheme Procedure: getsockname sock
 -- C Function: scm_getsockname (sock)
     Return the address of SOCK, in the same form as the object
     returned by `accept'.  On many systems the address of a socket in
     the `AF_FILE' namespace cannot be read.

 -- Scheme Procedure: getpeername sock
 -- C Function: scm_getpeername (sock)
     Return the address that SOCK is connected to, in the same form as
     the object returned by `accept'.  On many systems the address of a
     socket in the `AF_FILE' namespace cannot be read.

 -- Scheme Procedure: recv! sock buf [flags]
 -- C Function: scm_recv (sock, buf, flags)
     Receive data from a socket port.  SOCK must already be bound to
     the address from which data is to be received.  BUF is a string
     into which the data will be written.  The size of BUF limits the
     amount of data which can be received: in the case of packet
     protocols, if a packet larger than this limit is encountered then
     some data will be irrevocably lost.

     The optional FLAGS argument is a value or bitwise OR of MSG_OOB,
     MSG_PEEK, MSG_DONTROUTE etc.

     The value returned is the number of bytes read from the socket.

     Note that the data is read directly from the socket file
     descriptor: any unread buffered port data is ignored.

 -- Scheme Procedure: send sock message [flags]
 -- C Function: scm_send (sock, message, flags)
     Transmit the string MESSAGE on a socket port SOCK.  SOCK must
     already be bound to a destination address.  The value returned is
     the number of bytes transmitted - it's possible for this to be
     less than the length of MESSAGE if the socket is set to be
     non-blocking.  The optional FLAGS argument is a value or bitwise
     OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc.

     Note that the data is written directly to the socket file
     descriptor: any unflushed buffered port data is ignored.

 -- Scheme Procedure: recvfrom! sock str [flags [start [end]]]
 -- C Function: scm_recvfrom (sock, str, flags, start, end)
     Return data from the socket port SOCK and also information about
     where the data was received from.  SOCK must already be bound to
     the address from which data is to be received.  `str', is a string
     into which the data will be written.  The size of STR limits the
     amount of data which can be received: in the case of packet
     protocols, if a packet larger than this limit is encountered then
     some data will be irrevocably lost.

     The optional FLAGS argument is a value or bitwise OR of `MSG_OOB',
     `MSG_PEEK', `MSG_DONTROUTE' etc.

     The value returned is a pair: the _car_ is the number of bytes
     read from the socket and the _cdr_ an address object in the same
     form as returned by `accept'.  The address will given as `#f' if
     not available, as is usually the case for stream sockets.

     The START and END arguments specify a substring of STR to which
     the data should be written.

     Note that the data is read directly from the socket file
     descriptor: any unread buffered port data is ignored.

 -- Scheme Procedure: sendto sock message fam address . args_and_flags
 -- C Function: scm_sendto (sock, message, fam, address, args_and_flags)
     Transmit the string MESSAGE on the socket port SOCK.  The
     destination address is specified using the FAM, ADDRESS and
     ARGS_AND_FLAGS arguments, in a similar way to the `connect'
     procedure.  ARGS_AND_FLAGS contains the usual connection arguments
     optionally followed by a flags argument, which is a value or
     bitwise OR of MSG_OOB, MSG_PEEK, MSG_DONTROUTE etc.

     The value returned is the number of bytes transmitted - it's
     possible for this to be less than the length of MESSAGE if the
     socket is set to be non-blocking.  Note that the data is written
     directly to the socket file descriptor: any unflushed buffered
     port data is ignored.

   The following functions can be used to convert short and long
integers between "host" and "network" order.  Although the procedures
above do this automatically for addresses, the conversion will still
need to be done when sending or receiving encoded integer data from the
network.

 -- Scheme Procedure: htons value
 -- C Function: scm_htons (value)
     Convert a 16 bit quantity from host to network byte ordering.
     VALUE is packed into 2 bytes, which are then converted and
     returned as a new integer.

 -- Scheme Procedure: ntohs value
 -- C Function: scm_ntohs (value)
     Convert a 16 bit quantity from network to host byte ordering.
     VALUE is packed into 2 bytes, which are then converted and
     returned as a new integer.

 -- Scheme Procedure: htonl value
 -- C Function: scm_htonl (value)
     Convert a 32 bit quantity from host to network byte ordering.
     VALUE is packed into 4 bytes, which are then converted and
     returned as a new integer.

 -- Scheme Procedure: ntohl value
 -- C Function: scm_ntohl (value)
     Convert a 32 bit quantity from network to host byte ordering.
     VALUE is packed into 4 bytes, which are then converted and
     returned as a new integer.

   These procedures are inconvenient to use at present, but consider:

     (define write-network-long
       (lambda (value port)
         (let ((v (make-uniform-vector 1 1 0)))
           (uniform-vector-set! v 0 (htonl value))
           (uniform-vector-write v port))))

     (define read-network-long
       (lambda (port)
         (let ((v (make-uniform-vector 1 1 0)))
           (uniform-vector-read! v port)
           (ntohl (uniform-vector-ref v 0)))))


File: guile.info,  Node: Internet Socket Examples,  Prev: Network Sockets and Communication,  Up: Networking

38.11.4 Network Socket Examples
-------------------------------

The following sections give examples of how to use network sockets.

* Menu:

* Internet Socket Client::
* Internet Socket Server::


File: guile.info,  Node: Internet Socket Client,  Next: Internet Socket Server,  Up: Internet Socket Examples

38.11.4.1 Internet Socket Client Example
........................................

The following example demonstrates an Internet socket client.  It
connects to the HTTP daemon running on the local machine and returns
the contents of the root index URL.

     (let ((s (socket PF_INET SOCK_STREAM 0)))
       (connect s AF_INET (inet-aton "127.0.0.1") 80)
       (display "GET / HTTP/1.0\r\n\r\n" s)

       (do ((line (read-line s) (read-line s)))
           ((eof-object? line))
         (display line)
         (newline)))


File: guile.info,  Node: Internet Socket Server,  Prev: Internet Socket Client,  Up: Internet Socket Examples

38.11.4.2 Internet Socket Server Example
........................................

The following example shows a simple Internet server which listens on
port 2904 for incoming connections and sends a greeting back to the
client.

     (let ((s (socket PF_INET SOCK_STREAM 0)))
       (setsockopt s SOL_SOCKET SO_REUSEADDR 1)
       ;; Specific address?
       ;; (bind s AF_INET (inet-aton "127.0.0.1") 2904)
       (bind s AF_INET INADDR_ANY 2904)
       (listen s 5)

       (simple-format #t "Listening for clients in pid: ~S" (getpid))
       (newline)

       (while #t
              (let* ((client-connection (accept s))
                     (client-details (cdr client-connection))
                     (client (car client-connection)))
                (simple-format #t "Got new client connection: ~S"
                               client-details)
                (newline)
                (simple-format #t "Client address: ~S"
                               (gethostbyaddr
                                (sockaddr:addr client-details)))
                (newline)
                ;; Send back the greeting to the client port
                (display "Hello client\r\n" client)
                (close client))))


File: guile.info,  Node: System Identification,  Next: Locales,  Prev: Networking,  Up: POSIX

38.12 System Identification
===========================

This section lists the various procedures Guile provides for accessing
information about the system it runs on.

 -- Scheme Procedure: uname
 -- C Function: scm_uname ()
     Return an object with some information about the computer system
     the program is running on.

   The following procedures accept an object as returned by `uname' and
return a selected component.

`utsname:sysname'
     The name of the operating system.

`utsname:nodename'
     The network name of the computer.

`utsname:release'
     The current release level of the operating system implementation.

`utsname:version'
     The current version level within the release of the operating
     system.

`utsname:machine'
     A description of the hardware.

 -- Scheme Procedure: gethostname
 -- C Function: scm_gethostname ()
     Return the host name of the current processor.

 -- Scheme Procedure: sethostname name
 -- C Function: scm_sethostname (name)
     Set the host name of the current processor to NAME. May only be
     used by the superuser.  The return value is not specified.


File: guile.info,  Node: Locales,  Next: Encryption,  Prev: System Identification,  Up: POSIX

38.13 Locales
=============

 -- Scheme Procedure: setlocale category [locale]
 -- C Function: scm_setlocale (category, locale)
     If LOCALE is omitted, return the current value of the specified
     locale category as a system-dependent string.  CATEGORY should be
     specified using the values `LC_COLLATE', `LC_ALL' etc.

     Otherwise the specified locale category is set to the string
     LOCALE and the new value is returned as a system-dependent string.
     If LOCALE is an empty string, the locale will be set using
     environment variables.


File: guile.info,  Node: Encryption,  Prev: Locales,  Up: POSIX

38.14 Encryption
================

Please note that the procedures in this section are not suited for
strong encryption, they are only interfaces to the well-known and
common system library functions of the same name.  They are just as good
(or bad) as the underlying functions, so you should refer to your system
documentation before using them.

 -- Scheme Procedure: crypt key salt
 -- C Function: scm_crypt (key, salt)
     Encrypt KEY using SALT as the salt value to the crypt(3) library
     call.

   Although `getpass' is not an encryption procedure per se, it appears
here because it is often used in combination with `crypt':

 -- Scheme Procedure: getpass prompt
 -- C Function: scm_getpass (prompt)
     Display PROMPT to the standard error output and read a password
     from `/dev/tty'.  If this file is not accessible, it reads from
     standard input.  The password may be up to 127 characters in
     length.  Additional characters and the terminating newline
     character are discarded.  While reading the password, echoing and
     the generation of signals by special characters is disabled.


File: guile.info,  Node: SRFI Support,  Next: Readline Support,  Prev: POSIX,  Up: Top

39 SRFI Support Modules
***********************

SRFI is an acronym for Scheme Request For Implementation.  The SRFI
documents define a lot of syntactic and procedure extensions to standard
Scheme as defined in R5RS.

   Guile has support for a number of SRFIs.  This chapter gives an
overview over the available SRFIs and some usage hints.  For complete
documentation, design rationales and further examples, we advise you to
get the relevant SRFI documents from the SRFI home page
`http://srfi.schemers.org'.

* Menu:

* About SRFI Usage::            What to know about Guile's SRFI support.
* SRFI-0::                      cond-expand
* SRFI-1::                      List library.
* SRFI-2::                      and-let*.
* SRFI-4::                      Homogeneous numeric vector datatypes.
* SRFI-6::                      Basic String Ports.
* SRFI-8::                      receive.
* SRFI-9::                      define-record-type.
* SRFI-10::                     Hash-Comma Reader Extension.
* SRFI-11::                     let-values and let-values*.
* SRFI-13::                     String library.
* SRFI-14::                     Character-set library.
* SRFI-16::                     case-lambda
* SRFI-17::                     Generalized set!
* SRFI-19::                     Time/Date library.
* SRFI-31::                     A special form `rec' for recursive evaluation.


File: guile.info,  Node: About SRFI Usage,  Next: SRFI-0,  Up: SRFI Support

39.1 About SRFI Usage
=====================

SRFI support in Guile is currently implemented partly in the core
library, and partly as add-on modules.  That means that some SRFIs are
automatically available when the interpreter is started, whereas the
other SRFIs require you to use the appropriate support module
explicitly.

   There are several reasons for this inconsistency.  First, the feature
checking syntactic form `cond-expand' (*note SRFI-0::) must be
available immediately, because it must be there when the user wants to
check for the Scheme implementation, that is, before she can know that
it is safe to use `use-modules' to load SRFI support modules.  The
second reason is that some features defined in SRFIs had been
implemented in Guile before the developers started to add SRFI
implementations as modules (for example SRFI-6 (*note SRFI-6::)).  In
the future, it is possible that SRFIs in the core library might be
factored out into separate modules, requiring explicit module loading
when they are needed.  So you should be prepared to have to use
`use-modules' someday in the future to access SRFI-6 bindings.  If you
want, you can do that already.  We have included the module `(srfi
srfi-6)' in the distribution, which currently does nothing, but ensures
that you can write future-safe code.

   Generally, support for a specific SRFI is made available by using
modules named `(srfi srfi-NUMBER)', where NUMBER is the number of the
SRFI needed.  Another possibility is to use the command line option
`--use-srfi', which will load the necessary modules automatically
(*note Invoking Guile::).


File: guile.info,  Node: SRFI-0,  Next: SRFI-1,  Prev: About SRFI Usage,  Up: SRFI Support

39.2 SRFI-0 - cond-expand
=========================

SRFI-0 defines a means for checking whether a Scheme implementation has
support for a specified feature.  The syntactic form `cond-expand',
which implements this means, has the following syntax.

     <cond-expand>
       --> (cond-expand <cond-expand-clause>+)
         | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
     <cond-expand-clause>
       --> (<feature-requirement> <command-or-definition>*)
     <feature-requirement>
       --> <feature-identifier>
         | (and <feature-requirement>*)
         | (or <feature-requirement>*)
         | (not <feature-requirement>)
     <feature-identifier>
       --> <a symbol which is the name or alias of a SRFI>

   When evaluated, this form checks all clauses in order, until it finds
one whose feature requirement is satisfied.  Then the form expands into
the commands or definitions in the clause.  A requirement is tested as
follows:

   * If it is a symbol, it is satisfied if the feature identifier is
     supported.

   * If it is an `and' form, all requirements must be satisfied.  If no
     requirements are given, it is satisfied, too.

   * If it is an `or' form, at least one of the requirements must be
     satisfied.  If no requirements are given, it is not satisfied.

   * If it is a `not' form, the feature requirement must _not_ be
     satisfied.

   * If the feature requirement is the keyword `else' and it is the last
     clause, it is satisfied if no prior clause matched.

   If no clause is satisfied, an error is signalled.

   Since `cond-expand' is needed to tell what a Scheme implementation
provides, it must be accessible without using any
implementation-dependent operations, such as `use-modules' in Guile.
Thus, it is not necessary to use any module to get access to this form.

   Currently, the feature identifiers `guile', `r5rs', `srfi-0' and
`srfi-6' are supported.  The other SRFIs are not in that list by
default, because the SRFI modules must be explicitly used before their
exported bindings can be used.

   So if a Scheme program wishes to use SRFI-8, it has two
possibilities: First, it can check whether the running Scheme
implementation is Guile, and if it is, it can use the appropriate
module:

     (cond-expand
       (guile
         (use-modules (srfi srfi-8)))
       (srfi-8
         #t))
       ;; otherwise fail.

   The other possibility is to use the `--use-srfi' command line option
when invoking Guile (*note Invoking Guile::).  When you do that, the
specified SRFI support modules will be loaded and add their feature
identifier to the list of symbols checked by `cond-expand'.

   So, if you invoke Guile like this:

     $ guile --use-srfi=8

   the following snippet will expand to `'hooray'.

     (cond-expand (srfi-8 'hooray))


File: guile.info,  Node: SRFI-1,  Next: SRFI-2,  Prev: SRFI-0,  Up: SRFI Support

39.3 SRFI-1 - List library
==========================

The list library defined in SRFI-1 contains a lot of useful list
processing procedures for construction, examining, destructuring and
manipulating lists and pairs.

   Since SRFI-1 also defines some procedures which are already contained
in R5RS and thus are supported by the Guile core library, some list and
pair procedures which appear in the SRFI-1 document may not appear in
this section.  So when looking for a particular list/pair processing
procedure, you should also have a look at the sections *Note Lists::
and *Note Pairs::.

* Menu:

* SRFI-1 Constructors::         Constructing new lists.
* SRFI-1 Predicates::           Testing list for specific properties.
* SRFI-1 Selectors::            Selecting elements from lists.
* SRFI-1 Length Append etc::    Length calculation and list appending.
* SRFI-1 Fold and Map::         Higher-order list processing.
* SRFI-1 Filtering and Partitioning::  Filter lists based on predicates.
* SRFI-1 Searching::            Search for elements.
* SRFI-1 Deleting::             Delete elements from lists.
* SRFI-1 Association Lists::    Handle association lists.
* SRFI-1 Set Operations::       Use lists for representing sets.


File: guile.info,  Node: SRFI-1 Constructors,  Next: SRFI-1 Predicates,  Up: SRFI-1

39.3.1 Constructors
-------------------

New lists can be constructed by calling one of the following procedures.

 -- Scheme Procedure: xcons d a
     Like `cons', but with interchanged arguments.  Useful mostly when
     passed to higher-order procedures.

 -- Scheme Procedure: list-tabulate n init-proc
     Return an N-element list, where each list element is produced by
     applying the procedure INIT-PROC to the corresponding list index.
     The order in which INIT-PROC is applied to the indices is not
     specified.

 -- Scheme Procedure: circular-list elt1 elt2 ...
     Return a circular list containing the given arguments ELT1 ELT2
     ....

 -- Scheme Procedure: iota count [start step]
     Return a list containing COUNT elements, where each element is
     calculated as follows:

     START + (COUNT - 1) * STEP

     START defaults to 0 and STEP defaults to 1.


File: guile.info,  Node: SRFI-1 Predicates,  Next: SRFI-1 Selectors,  Prev: SRFI-1 Constructors,  Up: SRFI-1

39.3.2 Predicates
-----------------

The procedures in this section test specific properties of lists.

 -- Scheme Procedure: proper-list? obj
     Return `#t' if OBJ is a proper list, that is a finite list,
     terminated with the empty list.  Otherwise, return `#f'.

 -- Scheme Procedure: circular-list? obj
     Return `#t' if OBJ is a circular list, otherwise return `#f'.

 -- Scheme Procedure: dotted-list? obj
     Return `#t' if OBJ is a dotted list, return `#f' otherwise.  A
     dotted list is a finite list which is not terminated by the empty
     list, but some other value.

 -- Scheme Procedure: null-list? lst
     Return `#t' if LST is the empty list `()', `#f' otherwise.  If
     something else than a proper or circular list is passed as LST, an
     error is signalled.  This procedure is recommended for checking
     for the end of a list in contexts where dotted lists are not
     allowed.

 -- Scheme Procedure: not-pair? obj
     Return `#t' is OBJ is not a pair, `#f' otherwise.  This is
     shorthand notation `(not (pair? OBJ))' and is supposed to be used
     for end-of-list checking in contexts where dotted lists are
     allowed.

 -- Scheme Procedure: list= elt= list1 ...
     Return `#t' if all argument lists are equal, `#f' otherwise.  List
     equality is determined by testing whether all lists have the same
     length and the corresponding elements are equal in the sense of the
     equality predicate ELT=.  If no or only one list is given, `#t' is
     returned.


File: guile.info,  Node: SRFI-1 Selectors,  Next: SRFI-1 Length Append etc,  Prev: SRFI-1 Predicates,  Up: SRFI-1

39.3.3 Selectors
----------------

 -- Scheme Procedure: first pair
 -- Scheme Procedure: second pair
 -- Scheme Procedure: third pair
 -- Scheme Procedure: fourth pair
 -- Scheme Procedure: fifth pair
 -- Scheme Procedure: sixth pair
 -- Scheme Procedure: seventh pair
 -- Scheme Procedure: eighth pair
 -- Scheme Procedure: ninth pair
 -- Scheme Procedure: tenth pair
     These are synonyms for `car', `cadr', `caddr', ....

 -- Scheme Procedure: car+cdr pair
     Return two values, the CAR and the CDR of PAIR.

 -- Scheme Procedure: take lst i
 -- Scheme Procedure: take! lst i
     Return a list containing the first I elements of LST.

     `take!' may modify the structure of the argument list LST in order
     to produce the result.

 -- Scheme Procedure: drop lst i
     Return a list containing all but the first I elements of LST.

 -- Scheme Procedure: take-right lst i
     Return the a list containing the I last elements of LST.

 -- Scheme Procedure: drop-right lst i
 -- Scheme Procedure: drop-right! lst i
     Return the a list containing all but the I last elements of LST.

     `drop-right!' may modify the structure of the argument list LST in
     order to produce the result.

 -- Scheme Procedure: split-at lst i
 -- Scheme Procedure: split-at! lst i
     Return two values, a list containing the first I elements of the
     list LST and a list containing the remaining elements.

     `split-at!' may modify the structure of the argument list LST in
     order to produce the result.

 -- Scheme Procedure: last lst
     Return the last element of the non-empty, finite list LST.


File: guile.info,  Node: SRFI-1 Length Append etc,  Next: SRFI-1 Fold and Map,  Prev: SRFI-1 Selectors,  Up: SRFI-1

39.3.4 Length, Append, Concatenate, etc.
----------------------------------------

 -- Scheme Procedure: length+ lst
     Return the length of the argument list LST.  When LST is a
     circular list, `#f' is returned.

 -- Scheme Procedure: concatenate list-of-lists
 -- Scheme Procedure: concatenate! list-of-lists
     Construct a list by appending all lists in LIST-OF-LISTS.

     `concatenate!' may modify the structure of the given lists in
     order to produce the result.

 -- Scheme Procedure: append-reverse rev-head tail
 -- Scheme Procedure: append-reverse! rev-head tail
     Reverse REV-HEAD, append TAIL and return the result.  This is
     equivalent to `(append (reverse REV-HEAD) TAIL)', but more
     efficient.

     `append-reverse!' may modify REV-HEAD in order to produce the
     result.

 -- Scheme Procedure: zip lst1 lst2 ...
     Return a list as long as the shortest of the argument lists, where
     each element is a list.  The first list contains the first
     elements of the argument lists, the second list contains the
     second elements, and so on.

 -- Scheme Procedure: unzip1 lst
 -- Scheme Procedure: unzip2 lst
 -- Scheme Procedure: unzip3 lst
 -- Scheme Procedure: unzip4 lst
 -- Scheme Procedure: unzip5 lst
     `unzip1' takes a list of lists, and returns a list containing the
     first elements of each list, `unzip2' returns two lists, the first
     containing the first elements of each lists and the second
     containing the second elements of each lists, and so on.


File: guile.info,  Node: SRFI-1 Fold and Map,  Next: SRFI-1 Filtering and Partitioning,  Prev: SRFI-1 Length Append etc,  Up: SRFI-1

39.3.5 Fold, Unfold & Map
-------------------------

 -- Scheme Procedure: fold kons knil lst1 lst2 ...
     Fold the procedure KONS across all elements of LST1, LST2, ....
     Produce the result of

     `(KONS EN1 EN2 ... (KONS E21 E22 (KONS E11 E12 KNIL)))',

     if ENM are the elements of the lists LST1, LST2, ....

 -- Scheme Procedure: fold-right kons knil lst1 lst2 ...
     Similar to `fold', but applies KONS in right-to-left order to the
     list elements, that is:

     `(KONS E11 E12(KONS E21 E22  ... (KONS EN1 EN2 KNIL)))',

 -- Scheme Procedure: pair-fold kons knil lst1 lst2 ...
     Like `fold', but apply KONS to the pairs of the list instead of
     the list elements.

 -- Scheme Procedure: pair-fold-right kons knil lst1 lst2 ...
     Like `fold-right', but apply KONS to the pairs of the list instead
     of the list elements.

 -- Scheme Procedure: reduce f ridentity lst
     `reduce' is a variant of `reduce'.  If LST is `()', RIDENTITY is
     returned.  Otherwise, `(fold (car LST) (cdr LST))' is returned.

 -- Scheme Procedure: reduce-right f ridentity lst
     This is the `fold-right' variant of REDUCE.

 -- Scheme Procedure: unfold p f g seed [tail-gen]
     `unfold' is defined as follows:

          (unfold p f g seed) =
             (if (p seed) (tail-gen seed)
                 (cons (f seed)
                       (unfold p f g (g seed))))

    P
          Determines when to stop unfolding.

    F
          Maps each seed value to the corresponding list element.

    G
          Maps each seed value to next seed valu.

    SEED
          The state value for the unfold.

    TAIL-GEN
          Creates the tail of the list; defaults to `(lambda (x) '())'.

     G produces a series of seed values, which are mapped to list
     elements by F.  These elements are put into a list in
     left-to-right order, and P tells when to stop unfolding.

 -- Scheme Procedure: unfold-right p f g seed [tail]
     Construct a list with the following loop.

          (let lp ((seed seed) (lis tail))
             (if (p seed) lis
                 (lp (g seed)
                     (cons (f seed) lis))))

    P
          Determines when to stop unfolding.

    F
          Maps each seed value to the corresponding list element.

    G
          Maps each seed value to next seed valu.

    SEED
          The state value for the unfold.

    TAIL-GEN
          Creates the tail of the list; defaults to `(lambda (x) '())'.


 -- Scheme Procedure: map f lst1 lst2 ...
     Map the procedure over the list(s) LST1, LST2, ... and return a
     list containing the results of the procedure applications.  This
     procedure is extended with respect to R5RS, because the argument
     lists may have different lengths.  The result list will have the
     same length as the shortest argument lists.  The order in which F
     will be applied to the list element(s) is not specified.

 -- Scheme Procedure: for-each f lst1 lst2 ...
     Apply the procedure F to each pair of corresponding elements of
     the list(s) LST1, LST2, ....  The return value is not specified.
     This procedure is extended with respect to R5RS, because the
     argument lists may have different lengths.  The shortest argument
     list determines the number of times F is called.  F will be
     applied to the list elements in left-to-right order.


 -- Scheme Procedure: append-map f lst1 lst2 ...
 -- Scheme Procedure: append-map! f lst1 lst2 ...
     Equivalent to

          (apply append (map f clist1 clist2 ...))

     and

          (apply append! (map f clist1 clist2 ...))

     Map F over the elements of the lists, just as in the `map'
     function. However, the results of the applications are appended
     together to make the final result. `append-map' uses `append' to
     append the results together; `append-map!' uses `append!'.

     The dynamic order in which the various applications of F are made
     is not specified.

 -- Scheme Procedure: map! f lst1 lst2 ...
     Linear-update variant of `map' - `map!' is allowed, but not
     required, to alter the cons cells of LST1 to construct the result
     list.

     The dynamic order in which the various applications of F are made
     is not specified. In the n-ary case, LST2, LST3, ... must have at
     least as many elements as LST1.

 -- Scheme Procedure: pair-for-each f lst1 lst2 ...
     Like `for-each', but applies the procedure F to the pairs from
     which the argument lists are constructed, instead of the list
     elements.  The return value is not specified.

 -- Scheme Procedure: filter-map f lst1 lst2 ...
     Like `map', but only results from the applications of F which are
     true are saved in the result list.


File: guile.info,  Node: SRFI-1 Filtering and Partitioning,  Next: SRFI-1 Searching,  Prev: SRFI-1 Fold and Map,  Up: SRFI-1

39.3.6 Filtering and Partitioning
---------------------------------

Filtering means to collect all elements from a list which satisfy a
specific condition.  Partitioning a list means to make two groups of
list elements, one which contains the elements satisfying a condition,
and the other for the elements which don't.

 -- Scheme Procedure: filter pred lst
 -- Scheme Procedure: filter! pred lst
     Return a list containing all elements from LST which satisfy the
     predicate PRED.  The elements in the result list have the same
     order as in LST.  The order in which PRED is applied to the list
     elements is not specified.

     `filter!' is allowed, but not required to modify the structure of

 -- Scheme Procedure: partition pred lst
 -- Scheme Procedure: partition! pred lst
     Return two lists, one containing all elements from LST which
     satisfy the predicate PRED, and one list containing the elements
     which do not satisfy the predicated.  The elements in the result
     lists have the same order as in LST.  The order in which PRED is
     applied to the list elements is not specified.

     `partition!' is allowed, but not required to modify the structure
     of the input list.

 -- Scheme Procedure: remove pred lst
 -- Scheme Procedure: remove! pred lst
     Return a list containing all elements from LST which do not
     satisfy the predicate PRED.  The elements in the result list have
     the same order as in LST.  The order in which PRED is applied to
     the list elements is not specified.

     `remove!' is allowed, but not required to modify the structure of
     the input list.


File: guile.info,  Node: SRFI-1 Searching,  Next: SRFI-1 Deleting,  Prev: SRFI-1 Filtering and Partitioning,  Up: SRFI-1

39.3.7 Searching
----------------

The procedures for searching elements in lists either accept a
predicate or a comparison object for determining which elements are to
be searched.

 -- Scheme Procedure: find pred lst
     Return the first element of LST which satisfies the predicate PRED
     and `#f' if no such element is found.

 -- Scheme Procedure: find-tail pred lst
     Return the first pair of LST whose CAR satisfies the predicate
     PRED and `#f' if no such element is found.

 -- Scheme Procedure: take-while pred lst
 -- Scheme Procedure: take-while! pred lst
     Return the longest initial prefix of LST whose elements all
     satisfy the predicate PRED.

     `take-while!' is allowed, but not required to modify the input
     list while producing the result.

 -- Scheme Procedure: drop-while pred lst
     Drop the longest initial prefix of LST whose elements all satisfy
     the predicate PRED.

 -- Scheme Procedure: span pred lst
 -- Scheme Procedure: span! pred lst
 -- Scheme Procedure: break pred lst
 -- Scheme Procedure: break! pred lst
     `span' splits the list LST into the longest initial prefix whose
     elements all satisfy the predicate PRED, and the remaining tail.
     `break' inverts the sense of the predicate.

     `span!' and `break!' are allowed, but not required to modify the
     structure of the input list LST in order to produce the result.

 -- Scheme Procedure: any pred lst1 lst2 ...
     Apply PRED across the lists and return a true value if the
     predicate returns true for any of the list elements(s); return
     `#f' otherwise.  The true value returned is always the result of
     the first successful application of PRED.

 -- Scheme Procedure: every pred lst1 lst2 ...
     Apply PRED across the lists and return a true value if the
     predicate returns true for every of the list elements(s); return
     `#f' otherwise.  The true value returned is always the result of
     the final successful application of PRED.

 -- Scheme Procedure: list-index pred lst1 lst2 ...
     Return the index of the leftmost element that satisfies PRED.

 -- Scheme Procedure: member x lst [=]
     Return the first sublist of LST whose CAR is equal to X.  If X
     does no appear in LST, return `#f'.  Equality is determined by the
     equality predicate =, or `equal?' if = is not given.


File: guile.info,  Node: SRFI-1 Deleting,  Next: SRFI-1 Association Lists,  Prev: SRFI-1 Searching,  Up: SRFI-1

39.3.8 Deleting
---------------

The procedures for deleting elements from a list either accept a
predicate or a comparison object for determining which elements are to
be removed.

 -- Scheme Procedure: delete x lst [=]
 -- Scheme Procedure: delete! x lst [=]
     Return a list containing all elements from LST, but without the
     elements equal to X.  Equality is determined by the equality
     predicate =, which defaults to `equal?' if not given.

     `delete!' is allowed, but not required to modify the structure of
     the argument list in order to produce the result.

 -- Scheme Procedure: delete-duplicates lst [=]
 -- Scheme Procedure: delete-duplicates! lst [=]
     Return a list containing all elements from LST, but without
     duplicate elements.  Equality of elements is determined by the
     equality predicate =, which defaults to `equal?' if not given.

     `delete-duplicates!' is allowed, but not required to modify the
     structure of the argument list in order to produce the result.


File: guile.info,  Node: SRFI-1 Association Lists,  Next: SRFI-1 Set Operations,  Prev: SRFI-1 Deleting,  Up: SRFI-1

39.3.9 Association Lists
------------------------

Association lists are described in detail in section *Note Association
Lists::.  The present section only documents the additional procedures
for dealing with association lists defined by SRFI-1.

 -- Scheme Procedure: assoc key alist [=]
     Return the pair from ALIST which matches KEY.  Equality is
     determined by =, which defaults to `equal?' if not given.  ALIST
     must be an association lists--a list of pairs.

 -- Scheme Procedure: alist-cons key datum alist
     Equivalent to

          (cons (cons KEY DATUM) ALIST)

     This procedure is used to coons a new pair onto an existing
     association list.

 -- Scheme Procedure: alist-copy alist
     Return a newly allocated copy of ALIST, that means that the spine
     of the list as well as the pairs are copied.

 -- Scheme Procedure: alist-delete key alist [=]
 -- Scheme Procedure: alist-delete! key alist [=]
     Return a list containing the pairs of ALIST, but without the pairs
     whose CARS are equal to KEY.  Equality is determined by =, which
     defaults to `equal?' if not given.

     `alist-delete!' is allowed, but not required to modify the
     structure of the list ALIST in order to produce the result.


File: guile.info,  Node: SRFI-1 Set Operations,  Prev: SRFI-1 Association Lists,  Up: SRFI-1

39.3.10 Set Operations on Lists
-------------------------------

Lists can be used for representing sets of objects.  The procedures
documented in this section can be used for such set representations.
Man combining several sets or adding elements, they make sure that no
object is contained more than once in a given list.  Please note that
lists are not a too efficient implementation method for sets, so if you
need high performance, you should think about implementing a custom
data structure for representing sets, such as trees, bitsets, hash
tables or something similar.

   All these procedures accept an equality predicate as the first
argument.  This predicate is used for testing the objects in the list
sets for sameness.

 -- Scheme Procedure: lset<= = list1 ...
     Return `#t' if every LISTI is a subset of LISTI+1, otherwise
     return `#f'.  Returns `#t' if called with less than two arguments.
     = is used for testing element equality.

 -- Scheme Procedure: lset= = list1 list2 ...
     Return `#t' if all argument lists are equal. = is used for testing
     element equality.

 -- Scheme Procedure: lset-adjoin = list elt1 ...
 -- Scheme Procedure: lset-adjoin! = list elt1 ...
     Add all ELTS to the list LIST, suppressing duplicates and return
     the resulting list.  `lset-adjoin!' is allowed, but not required
     to modify its first argument. = is used for testing element
     equality.

 -- Scheme Procedure: lset-union = list1 ...
 -- Scheme Procedure: lset-union! = list1 ...
     Return the union of all argument list sets.  The union is the set
     of all elements which appear in any of the argument sets.
     `lset-union!' is allowed, but not required to modify its first
     argument. = is used for testing element equality.

 -- Scheme Procedure: lset-intersection = list1 list2 ...
 -- Scheme Procedure: lset-intersection! = list1 list2 ...
     Return the intersection of all argument list sets.  The
     intersection is the set containing all elements which appear in
     all argument sets.  `lset-intersection!' is allowed, but not
     required to modify its first argument. = is used for testing
     element equality.

 -- Scheme Procedure: lset-difference = list1 list2 ...
 -- Scheme Procedure: lset-difference! = list1 list2 ...
     Return the difference of all argument list sets.  The difference is
     the the set containing all elements of the first list which do not
     appear in the other lists.  `lset-difference!'  is allowed, but
     not required to modify its first argument. = is used for testing
     element equality.

 -- Scheme Procedure: lset-xor = list1 ...
 -- Scheme Procedure: lset-xor! = list1 ...
     Return the set containing all elements which appear in the first
     argument list set, but not in the second; or, more generally: which
     appear in an odd number of sets.  `lset-xor!'  is allowed, but not
     required to modify its first argument. = is used for testing
     element equality.

 -- Scheme Procedure: lset-diff+intersection = list1 list2 ...
 -- Scheme Procedure: lset-diff+intersection! = list1 list2 ...
     Return two values, the difference and the intersection of the
     argument list sets. This works like a combination of
     `lset-difference' and `lset-intersection', but is more efficient.
     `lset-diff+intersection!'  is allowed, but not required to modify
     its first argument. = is used for testing element equality.  You
     have to use some means to deal with the multiple values these
     procedures return (*note Multiple Values::).


File: guile.info,  Node: SRFI-2,  Next: SRFI-4,  Prev: SRFI-1,  Up: SRFI Support

39.4 SRFI-2 - and-let*
======================

The syntactic form `and-let*' combines the conditional evaluation form
`and' with the binding form LET*.  Each argument expression will be
evaluated sequentially, bound to a variable (if a variable name is
given), but only as long as no expression returns the false value `#f'.

   Use `(use-modules (srfi srfi-2)' to access this syntax form.

   A short example will demonstrate how it works.  In the first
expression, X will get bound to 1, but the next expression (`#f') is
false, so evaluation of the form is stopped, and `#f' is returned.  In
the next expression, X is bound to 1, Y is bound to `#t' and since no
expression in the binding section was false, the body of the `and-let*'
expression is evaluated, which in this case returns the value of X.

     (and-let* ((x 1) (y #f)) 42)
     =>
     #f
     (and-let* ((x 1) (y #t)) x)
     =>
     1


File: guile.info,  Node: SRFI-4,  Next: SRFI-6,  Prev: SRFI-2,  Up: SRFI Support

39.5 SRFI-4 - Homogeneous numeric vector datatypes.
===================================================

SRFI-4 defines a set of datatypes for vectors whose elements are all of
the same numeric type.  Vectors for signed and unsigned exact integer
or inexact real numbers in several precisions are available.

   Procedures similar to the vector procedures (*note Vectors::) are
provided for handling these homogeneous vectors, but they are distinct
datatypes.

   The reason for providing this set of datatypes is that with the
limitation (all elements must have the same type), it is possible to
implement them much more memory-efficient than normal, heterogenous
vectors.

   If you want to use these datatypes and the corresponding procedures,
you have to use the module `(srfi srfi-4)'.

   Ten vector data types are provided: Unsigned and signed integer
values with 8, 16, 32 and 64 bits and floating point values with 32 and
64 bits.  In the following descriptions, the tags `u8', `s8', `u16',
`s16', `u32', `s32', `u64', `s64', `f32', `f64', respectively, are used
for denoting the various types.

* Menu:

* SRFI-4 - Read Syntax::        How to write homogeneous vector literals.
* SRFI-4 - Procedures::         Available homogeneous vector procedures.


File: guile.info,  Node: SRFI-4 - Read Syntax,  Next: SRFI-4 - Procedures,  Up: SRFI-4

39.5.1 SRFI-4 - Read Syntax
---------------------------

Homogeneous numeric vectors have an external representation (read
syntax) similar to normal Scheme vectors, but with an additional tag
telling the vector's type.

     #u16(1 2 3)

   denotes a homogeneous numeric vector of three elements, which are the
values 1, 2 and 3, represented as 16-bit unsigned integers.
Correspondingly,

     #f64(3.1415 2.71)

   denotes a vector of two elements, which are the values 3.1415 and
2.71, represented as floating-point values of 64 bit precision.

   Please note that the read syntax for floating-point vectors conflicts
with Standard Scheme, because there `#f' is defined to be the literal
false value.  That means, that with the loaded SRFI-4 module, it is not
possible to enter some list like

     '(1 #f3)

   and hope that it will be parsed as a three-element list with the
elements 1, `#f' and 3.  In normal use, this should be no problem,
because people tend to terminate tokens sensibly when writing Scheme
expressions.


File: guile.info,  Node: SRFI-4 - Procedures,  Prev: SRFI-4 - Read Syntax,  Up: SRFI-4

39.5.2 SRFI-4 Procedures
------------------------

The procedures listed in this section are provided for all homogeneous
numeric vector datatypes.  For brevity, they are not all documented,
but a summary of the procedures is given.  In the following
descriptions, you can replace `TAG' by any of the datatype indicators
`u8', `s8', `u16', `s16', `u32', `s32', `u64', `s64', `f32' and `f64'.

   For example, you can use the procedures `u8vector?',
`make-s8vector', `u16vector', `u32vector-length', `s64vector-ref',
`f32vector-set!' or `f64vector->list'.

 -- Scheme Procedure: TAGvector? obj
     Return `#t' if OBJ is a homogeneous numeric vector of type `TAG'.

 -- Scheme Procedure: make-TAGvector n [value]
     Create a newly allocated homogeneous numeric vector of type `TAG',
     which can hold N elements.  If VALUE is given, the vector is
     initialized with the value, otherwise, the contents of the
     returned vector is not specified.

 -- Scheme Procedure: TAGvector value1 ...
     Create a newly allocated homogeneous numeric vector of type `TAG'.
     The returned vector is as long as the number of arguments given,
     and is initialized with the argument values.

 -- Scheme Procedure: TAGvector-length TAGvec
     Return the number of elements in TAGVEC.

 -- Scheme Procedure: TAGvector-ref TAGvec i
     Return the element at index I in TAGVEC.

 -- Scheme Procedure: TAGvector-ref TAGvec i value
     Set the element at index I in TAGVEC to VALUE.  The return value
     is not specified.

 -- Scheme Procedure: TAGvector->list TAGvec
     Return a newly allocated list holding all elements of TAGVEC.

 -- Scheme Procedure: list->TAGvector lst
     Return a newly allocated homogeneous numeric vector of type `TAG',
     initialized with the elements of the list LST.


File: guile.info,  Node: SRFI-6,  Next: SRFI-8,  Prev: SRFI-4,  Up: SRFI Support

39.6 SRFI-6 - Basic String Ports
================================

SRFI-6 defines the procedures `open-input-string', `open-output-string'
and `get-output-string'.  These procedures are included in the Guile
core, so using this module does not make any difference at the moment.
But it is possible that support for SRFI-6 will be factored out of the
core library in the future, so using this module does not hurt, after
all.


File: guile.info,  Node: SRFI-8,  Next: SRFI-9,  Prev: SRFI-6,  Up: SRFI Support

39.7 SRFI-8 - receive
=====================

`receive' is a syntax for making the handling of multiple-value
procedures easier.  It is documented in *Note Multiple Values::.


File: guile.info,  Node: SRFI-9,  Next: SRFI-10,  Prev: SRFI-8,  Up: SRFI Support

39.8 SRFI-9 - define-record-type
================================

This is the SRFI way for defining record types.  The Guile
implementation is a layer above Guile's normal record construction
procedures (*note Records::).  The nice thing about this kind of record
definition method is that no new names are implicitly created, all
constructor, accessor and predicates are explicitly given.  This reduces
the risk of variable capture.

   The syntax of a record type definition is:

     <record type definition>
       -> (define-record-type <type name>
            (<constructor name> <field tag> ...)
            <predicate name>
            <field spec> ...)
     <field spec> -> (<field tag> <accessor name>)
                  -> (<field tag> <accessor name> <modifier name>)
     <field tag>  -> <identifier>
     <... name>   -> <identifier>

   Usage example:

     guile> (use-modules (srfi srfi-9))
     guile> (define-record-type :foo (make-foo x) foo?
                                (x get-x) (y get-y set-y!))
     guile> (define f (make-foo 1))
     guile> f
     #<:foo x: 1 y: #f>
     guile> (get-x f)
     1
     guile> (set-y! f 2)
     2
     guile> (get-y f)
     2
     guile> f
     #<:foo x: 1 y: 2>
     guile> (foo? f)
     #t
     guile> (foo? 1)
     #f


File: guile.info,  Node: SRFI-10,  Next: SRFI-11,  Prev: SRFI-9,  Up: SRFI Support

39.9 SRFI-10 - Hash-Comma Reader Extension
==========================================

The module `(srfi srfi-10)' implements the syntax extension `#,()',
also called hash-comma, which is defined in SRFI-10.

   The support for SRFI-10 consists of the procedure
`define-reader-ctor' for defining new reader constructors and the read
syntax form

     #,(CTOR DATUM ...)

   where CTOR must be a symbol for which a read constructor was defined
previously, using `define-reader-ctor'.

   Example:

     (define-reader-ctor 'file open-input-file)
     (define f '#,(file "/etc/passwd"))
     (read-line f)
     =>
     "root:x:0:0:root:/root:/bin/bash"

   Please note the quote before the `#,(file ...)' expression.  This is
necessary because ports are not self-evaluating in Guile.

 -- Scheme Procedure: define-reader-ctor symbol proc
     Define PROC as the reader constructor for hash-comma forms with a
     tag SYMBOL.  PROC will be applied to the datum(s) following the
     tag in the hash-comma expression after the complete form has been
     read in.  The result of PROC is returned by the Scheme reader.


File: guile.info,  Node: SRFI-11,  Next: SRFI-13,  Prev: SRFI-10,  Up: SRFI Support

39.10 SRFI-11 - let-values
==========================

This module implements the binding forms for multiple values
`let-values' and `let-values*'.  These forms are similar to `let' and
`let*' (*note Local Bindings::), but they support binding of the values
returned by multiple-valued expressions.

   Write `(use-modules (srfi srfi-11))' to make the bindings available.

     (let-values (((x y) (values 1 2))
                  ((z f) (values 3 4)))
        (+ x y z f))
     =>
     10

   `let-values' performs all bindings simultaneously, which means that
no expression in the binding clauses may refer to variables bound in the
same clause list.  `let-values*', on the other hand, performs the
bindings sequentially, just like `let*' does for single-valued
expressions.

