1
Fork 0
mirror of https://git.savannah.gnu.org/git/guile.git synced 2025-04-30 03:40:34 +02:00

* Organize documentation into per-manual directories (halfway point commit).

This commit is contained in:
Neil Jerram 2001-08-24 09:40:29 +00:00
parent 80fdeb4e5a
commit a0e07ba4ec
99 changed files with 36066 additions and 4 deletions

View file

View file

View file

View file

View file

View file

View file

23
doc/goops/.cvsignore Normal file
View file

@ -0,0 +1,23 @@
Makefile
Makefile.in
stamp-vti
stamp-vti.1
*.log
*.dvi
*.aux
*.toc
*.cp
*.fn
*.vr
*.tp
*.ky
*.pg
*.cps
*.fns
*.tps
*.vrs
*.ps
*.info*
*.html
version.texi
version-tutorial.texi

View file

@ -0,0 +1,810 @@
@c Original attribution:
@c
@c STk Reference manual (Appendix: An Introduction to STklos)
@c
@c Copyright © 1993-1999 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
@c Permission to use, copy, modify, distribute,and license this
@c software and its documentation for any purpose is hereby granted,
@c provided that existing copyright notices are retained in all
@c copies and that this notice is included verbatim in any
@c distributions. No written agreement, license, or royalty fee is
@c required for any of the authorized uses.
@c This software is provided ``AS IS'' without express or implied
@c warranty.
@c
@c Adapted for use in Guile with the authors permission
@c @macro goops @c was {\stklos}
@c GOOPS
@c @end macro
@c @macro guile @c was {\stk}
@c Guile
@c @end macro
This is chapter was originally written by Erick Gallesio as an appendix
for the STk reference manual, and subsequently adapted to @goops{}.
@menu
* Copyright::
* Intro::
* Class definition and instantiation::
* Inheritance::
* Generic functions::
@end menu
@node Copyright, Intro, Tutorial, Tutorial
@section Copyright
Original attribution:
STk Reference manual (Appendix: An Introduction to STklos)
Copyright © 1993-1999 Erick Gallesio - I3S-CNRS/ESSI <eg@@unice.fr>
Permission to use, copy, modify, distribute,and license this
software and its documentation for any purpose is hereby granted,
provided that existing copyright notices are retained in all
copies and that this notice is included verbatim in any
distributions. No written agreement, license, or royalty fee is
required for any of the authorized uses.
This software is provided ``AS IS'' without express or implied
warranty.
Adapted for use in Guile with the authors permission
@node Intro, Class definition and instantiation, Copyright, Tutorial
@section Introduction
@goops{} is the object oriented extension to @guile{}. Its
implementation is derived from @w{STk-3.99.3} by Erick Gallesio and
version 1.3 of the Gregor Kiczales @cite{Tiny-Clos}. It is very close
to CLOS, the Common Lisp Object System (@cite{CLtL2}) but is adapted for
the Scheme language.
Briefly stated, the @goops{} extension gives the user a full object
oriented system with multiple inheritance and generic functions with
multi-method dispatch. Furthermore, the implementation relies on a true
meta object protocol, in the spirit of the one defined for CLOS
(@cite{Gregor Kiczales: A Metaobject Protocol}).
The purpose of this tutorial is to introduce briefly the @goops{}
package and in no case will it replace the @goops{} reference manual
(which needs to be urgently written now@ @dots{}).
Note that the operations described in this tutorial resides in modules
that may need to be imported before being available. The main module is
imported by evaluating:
@lisp
(use-modules (oop goops))
@end lisp
@findex (oop goops)
@cindex main module
@cindex loading
@cindex preparing
@node Class definition and instantiation, Inheritance, Intro, Tutorial
@section Class definition and instantiation
@menu
* Class definition::
@end menu
@node Class definition, , Class definition and instantiation, Class definition and instantiation
@subsection Class definition
A new class is defined with the @code{define-class}@footnote{Don't
forget to import the @code{(oop goops)} module} macro. The syntax of
@code{define-class} is close to CLOS @code{defclass}:
@findex define-class
@cindex class
@lisp
(define-class @var{class} (@var{superclass} @dots{})
@var{slot-description} @dots{}
@var{class-option} @dots{})
@end lisp
Class options will not be discussed in this tutorial. The list of
@var{superclass}es specifies which classes to inherit properties from
@var{class} (see @ref{Inheritance} for more details). A
@var{slot-description} gives the name of a slot and, eventually, some
``properties'' of this slot (such as its initial value, the function
which permit to access its value, @dots{}). Slot descriptions will be
discussed in @ref{Slot description}.
@cindex slot
As an example, let us define a type for representation of complex
numbers in terms of real numbers. This can be done with the following
class definition:
@lisp
(define-class <complex> (<number>)
r i)
@end lisp
This binds the variable @code{<complex>}@footnote{@code{<complex>} is in
fact a builtin class in GOOPS. Because of this, GOOPS will create a new
class. The old class will still serve as the type for Guile's native
complex numbers.} to a new class whose instances contain two
slots. These slots are called @code{r} an @code{i} and we suppose here
that they contain respectively the real part and the imaginary part of a
complex number. Note that this class inherits from @code{<number>} which
is a pre-defined class. (@code{<number>} is the direct super class of
the pre-defined class @code{<complex>} which, in turn, is the super
class of @code{<real>} which is the super of
@code{<integer>}.)@footnote{With the new definition of @code{<complex>},
a @code{<real>} is not a @code{<complex>} since @code{<real>} inherits
from @code{ <number>} rather than @code{<complex>}. In practice,
inheritance could be modified @emph{a posteriori}, if needed. However,
this necessitates some knowledge of the meta object protocol and it will
not be shown in this document}.
@node Inheritance, Generic functions, Class definition and instantiation, Tutorial
@section Inheritance
@c \label{inheritance}
@menu
* Class hierarchy and inheritance of slots::
* Instance creation and slot access::
* Slot description::
* Class precedence list::
@end menu
@node Class hierarchy and inheritance of slots, Instance creation and slot access, Inheritance, Inheritance
@subsection Class hierarchy and inheritance of slots
Inheritance is specified upon class definition. As said in the
introduction, @goops{} supports multiple inheritance. Here are some
class definitions:
@lisp
(define-class A () a)
(define-class B () b)
(define-class C () c)
(define-class D (A B) d a)
(define-class E (A C) e c)
(define-class F (D E) f)
@end lisp
@code{A}, @code{B}, @code{C} have a null list of super classes. In this
case, the system will replace it by the list which only contains
@code{<object>}, the root of all the classes defined by
@code{define-class}. @code{D}, @code{E}, @code{F} use multiple
inheritance: each class inherits from two previously defined classes.
Those class definitions define a hierarchy which is shown in Figure@ 1.
In this figure, the class @code{<top>} is also shown; this class is the
super class of all Scheme objects. In particular, @code{<top>} is the
super class of all standard Scheme types.
@example
@group
@image{hierarchy}
@center @emph{Fig 1: A class hierarchy}
@iftex
@emph{(@code{<complex>} which is the direct subclass of @code{<number>}
and the direct superclass of @code{<real>} has been omitted in this
figure.)}
@end iftex
@end group
@end example
The set of slots of a given class is calculated by taking the union of the
slots of all its super class. For instance, each instance of the class
D, defined before will have three slots (@code{a}, @code{b} and
@code{d}). The slots of a class can be obtained by the @code{class-slots}
primitive. For instance,
@lisp
(class-slots A) @result{} ((a))
(class-slots E) @result{} ((a) (e) (c))
(class-slots F) @result{} ((e) (c) (b) (d) (a) (f))
@c used to be ((d) (a) (b) (c) (f))
@end lisp
@emph{Note: } The order of slots is not significant.
@node Instance creation and slot access, Slot description, Class hierarchy and inheritance of slots, Inheritance
@subsection Instance creation and slot access
Creation of an instance of a previously defined
class can be done with the @code{make} procedure. This
procedure takes one mandatory parameter which is the class of the
instance which must be created and a list of optional
arguments. Optional arguments are generally used to initialize some
slots of the newly created instance. For instance, the following form
@findex make
@cindex instance
@lisp
(define c (make <complex>))
@end lisp
will create a new @code{<complex>} object and will bind it to the @code{c}
Scheme variable.
Accessing the slots of the new complex number can be done with the
@code{slot-ref} and the @code{slot-set!} primitives. @code{Slot-set!}
primitive permits to set the value of an object slot and @code{slot-ref}
permits to get its value.
@findex slot-set!
@findex slot-ref
@lisp
@group
(slot-set! c 'r 10)
(slot-set! c 'i 3)
(slot-ref c 'r) @result{} 10
(slot-ref c 'i) @result{} 3
@end group
@end lisp
Using the @code{describe} function is a simple way to see all the
slots of an object at one time: this function prints all the slots of an
object on the standard output.
First load the module @code{(oop goops describe)}:
@example
@code{(use-modules (oop goops describe))}
@end example
The expression
@smalllisp
(describe c)
@end smalllisp
will now print the following information on the standard output:
@lisp
#<<complex> 401d8638> is an instance of class <complex>
Slots are:
r = 10
i = 3
@end lisp
@node Slot description, Class precedence list, Instance creation and slot access, Inheritance
@subsection Slot description
@c \label{slot-description}
When specifying a slot, a set of options can be given to the
system. Each option is specified with a keyword. The list of authorized
keywords is given below:
@cindex keyword
@itemize @bullet
@item
@code{#:init-value} permits to supply a default value for the slot. This
default value is obtained by evaluating the form given after the
@code{#:init-form} in the global environment, at class definition time.
@cindex default slot value
@findex #:init-value
@cindex top level environment
@item
@code{#:init-thunk} permits to supply a thunk that will provide a
default value for the slot. The value is obtained by evaluating the
thunk a instance creation time.
@c CHECKME: in the global environment?
@findex default slot value
@findex #:init-thunk
@cindex top level environment
@item
@code{#:init-keyword} permits to specify the keyword for initializing a
slot. The init-keyword may be provided during instance creation (i.e. in
the @code{make} optional parameter list). Specifying such a keyword
during instance initialization will supersede the default slot
initialization possibly given with @code{#:init-form}.
@findex #:init-keyword
@item
@code{#:getter} permits to supply the name for the
slot getter. The name binding is done in the
environment of the @code{define-class} macro.
@findex #:getter
@cindex top level environment
@cindex getter
@item
@code{#:setter} permits to supply the name for the
slot setter. The name binding is done in the
environment of the @code{define-class} macro.
@findex #:setter
@cindex top level environment
@cindex setter
@item
@code{#:accessor} permits to supply the name for the
slot accessor. The name binding is done in the global
environment. An accessor permits to get and
set the value of a slot. Setting the value of a slot is done with the extended
version of @code{set!}.
@findex set!
@findex #:accessor
@cindex top level environment
@cindex accessor
@item
@code{#:allocation} permits to specify how storage for
the slot is allocated. Three kinds of allocation are provided.
They are described below:
@itemize @minus
@item
@code{#:instance} indicates that each instance gets its own storage for
the slot. This is the default.
@item
@code{#:class} indicates that there is one storage location used by all
the direct and indirect instances of the class. This permits to define a
kind of global variable which can be accessed only by (in)direct
instances of the class which defines this slot.
@item
@code{#:each-subclass} indicates that there is one storage location used
by all the direct instances of the class. In other words, if two classes
are not siblings in the class hierarchy, they will not see the same
value.
@item
@code{#:virtual} indicates that no storage will be allocated for this
slot. It is up to the user to define a getter and a setter function for
this slot. Those functions must be defined with the @code{#:slot-ref}
and @code{#:slot-set!} options. See the example below.
@findex #:slot-set!
@findex #:slot-ref
@findex #:virtual
@findex #:class
@findex #:each-subclass
@findex #:instance
@findex #:allocation
@end itemize
@end itemize
To illustrate slot description, we shall redefine the @code{<complex>} class
seen before. A definition could be:
@lisp
(define-class <complex> (<number>)
(r #:init-value 0 #:getter get-r #:setter set-r! #:init-keyword #:r)
(i #:init-value 0 #:getter get-i #:setter set-i! #:init-keyword #:i))
@end lisp
With this definition, the @code{r} and @code{i} slot are set to 0 by
default. Value of a slot can also be specified by calling @code{make}
with the @code{#:r} and @code{#:i} keywords. Furthermore, the generic
functions @code{get-r} and @code{set-r!} (resp. @code{get-i} and
@code{set-i!}) are automatically defined by the system to read and write
the @code{r} (resp. @code{i}) slot.
@lisp
(define c1 (make <complex> #:r 1 #:i 2))
(get-r c1) @result{} 1
(set-r! c1 12)
(get-r c1) @result{} 12
(define c2 (make <complex> #:r 2))
(get-r c2) @result{} 2
(get-i c2) @result{} 0
@end lisp
Accessors provide an uniform access for reading and writing an object
slot. Writing a slot is done with an extended form of @code{set!}
which is close to the Common Lisp @code{setf} macro. So, another
definition of the previous @code{<complex>} class, using the
@code{#:accessor} option, could be:
@findex set!
@lisp
(define-class <complex> (<number>)
(r #:init-value 0 #:accessor real-part #:init-keyword #:r)
(i #:init-value 0 #:accessor imag-part #:init-keyword #:i))
@end lisp
Using this class definition, reading the real part of the @code{c}
complex can be done with:
@lisp
(real-part c)
@end lisp
and setting it to the value contained in the @code{new-value} variable
can be done using the extended form of @code{set!}.
@lisp
(set! (real-part c) new-value)
@end lisp
Suppose now that we have to manipulate complex numbers with rectangular
coordinates as well as with polar coordinates. One solution could be to
have a definition of complex numbers which uses one particular
representation and some conversion functions to pass from one
representation to the other. A better solution uses virtual slots. A
complete definition of the @code{<complex>} class using virtual slots is
given in Figure@ 2.
@example
@group
@lisp
(define-class <complex> (<number>)
;; True slots use rectangular coordinates
(r #:init-value 0 #:accessor real-part #:init-keyword #:r)
(i #:init-value 0 #:accessor imag-part #:init-keyword #:i)
;; Virtual slots access do the conversion
(m #:accessor magnitude #:init-keyword #:magn
#:allocation #:virtual
#:slot-ref (lambda (o)
(let ((r (slot-ref o 'r)) (i (slot-ref o 'i)))
(sqrt (+ (* r r) (* i i)))))
#:slot-set! (lambda (o m)
(let ((a (slot-ref o 'a)))
(slot-set! o 'r (* m (cos a)))
(slot-set! o 'i (* m (sin a))))))
(a #:accessor angle #:init-keyword #:angle
#:allocation #:virtual
#:slot-ref (lambda (o)
(atan (slot-ref o 'i) (slot-ref o 'r)))
#:slot-set! (lambda(o a)
(let ((m (slot-ref o 'm)))
(slot-set! o 'r (* m (cos a)))
(slot-set! o 'i (* m (sin a)))))))
@end lisp
@center @emph{Fig 2: A @code{<complex>} number class definition using virtual slots}
@end group
@end example
@sp 3
This class definition implements two real slots (@code{r} and
@code{i}). Values of the @code{m} and @code{a} virtual slots are
calculated from real slot values. Reading a virtual slot leads to the
application of the function defined in the @code{#:slot-ref}
option. Writing such a slot leads to the application of the function
defined in the @code{#:slot-set!} option. For instance, the following
expression
@findex #:slot-set!
@findex #:slot-ref
@lisp
(slot-set! c 'a 3)
@end lisp
permits to set the angle of the @code{c} complex number. This expression
conducts, in fact, to the evaluation of the following expression
@lisp
((lambda o m)
(let ((m (slot-ref o 'm)))
(slot-set! o 'r (* m (cos a)))
(slot-set! o 'i (* m (sin a))))
c 3)
@end lisp
A more complete example is given below:
@example
@group
@lisp
(define c (make <complex> #:r 12 #:i 20))
(real-part c) @result{} 12
(angle c) @result{} 1.03037682652431
(slot-set! c 'i 10)
(set! (real-part c) 1)
(describe c) @result{}
#<<complex> 401e9b58> is an instance of class <complex>
Slots are:
r = 1
i = 10
m = 10.0498756211209
a = 1.47112767430373
@end lisp
@end group
@end example
Since initialization keywords have been defined for the four slots, we
can now define the @code{make-rectangular} and @code{make-polar} standard
Scheme primitives.
@lisp
(define make-rectangular
(lambda (x y) (make <complex> #:r x #:i y)))
(define make-polar
(lambda (x y) (make <complex> #:magn x #:angle y)))
@end lisp
@node Class precedence list, , Slot description, Inheritance
@subsection Class precedence list
A class may have more than one superclass. @footnote{This section is an
adaptation of Jeff Dalton's (J.Dalton@@ed.ac.uk) @cite{Brief
introduction to CLOS}} With single inheritance (one superclass), it is
easy to order the super classes from most to least specific. This is the
rule:
@display
@cartouche
Rule 1: Each class is more specific than its superclasses.@c was \bf
@end cartouche
@end display
With multiple inheritance, ordering is harder. Suppose we have
@lisp
(define-class X ()
(x #:init-value 1))
(define-class Y ()
(x #:init-value 2))
(define-class Z (X Y)
(@dots{}))
@end lisp
In this case, the @code{Z} class is more specific than the @code{X} or
@code{Y} class for instances of @code{Z}. However, the @code{#:init-value}
specified in @code{X} and @code{Y} leads to a problem: which one
overrides the other? The rule in @goops{}, as in CLOS, is that the
superclasses listed earlier are more specific than those listed later.
So:
@display
@cartouche
Rule 2: For a given class, superclasses listed earlier are more
specific than those listed later.
@end cartouche
@end display
These rules are used to compute a linear order for a class and all its
superclasses, from most specific to least specific. This order is
called the ``class precedence list'' of the class. Given these two
rules, we can claim that the initial form for the @code{x} slot of
previous example is 1 since the class @code{X} is placed before @code{Y}
in class precedence list of @code{Z}.
These two rules are not always enough to determine a unique order,
however, but they give an idea of how things work. Taking the @code{F}
class shown in Figure@ 1, the class precedence list is
@example
(f d e a c b <object> <top>)
@end example
However, it is usually considered a bad idea for programmers to rely on
exactly what the order is. If the order for some superclasses is important,
it can be expressed directly in the class definition.
The precedence list of a class can be obtained by the function
@code{class-precedence-list}. This function returns a ordered
list whose first element is the most specific class. For instance,
@lisp
(class-precedence-list B) @result{} (#<<class> B 401b97c8>
#<<class> <object> 401e4a10>
#<<class> <top> 4026a9d8>)
@end lisp
However, this result is not too much readable; using the function
@code{class-name} yields a clearer result:
@lisp
(map class-name (class-precedence-list B)) @result{} (B <object> <top>)
@end lisp
@node Generic functions, , Inheritance, Tutorial
@section Generic functions
@menu
* Generic functions and methods::
* Next-method::
* Example::
@end menu
@node Generic functions and methods, Next-method, Generic functions, Generic functions
@subsection Generic functions and methods
@c \label{gf-n-methods}
Neither @goops{} nor CLOS use the message mechanism for methods as most
Object Oriented language do. Instead, they use the notion of
@dfn{generic functions}. A generic function can be seen as a methods
``tanker''. When the evaluator requested the application of a generic
function, all the methods of this generic function will be grabbed and
the most specific among them will be applied. We say that a method
@var{M} is @emph{more specific} than a method @var{M'} if the class of
its parameters are more specific than the @var{M'} ones. To be more
precise, when a generic function must be ``called'' the system will:
@cindex generic function
@enumerate
@item
search among all the generic function those which are applicable
@item
sort the list of applicable methods in the ``most specific'' order
@item
call the most specific method of this list (i.e. the first method of
the sorted methods list).
@end enumerate
The definition of a generic function is done with the
@code{define-generic} macro. Definition of a new method is done with the
@code{define-method} macro. Note that @code{define-method} automatically
defines the generic function if it has not been defined
before. Consequently, most of the time, the @code{define-generic} needs
not be used.
@findex define-generic
@findex define-method
Consider the following definitions:
@lisp
(define-generic G)
(define-method (G (a <integer>) b) 'integer)
(define-method (G (a <real>) b) 'real)
(define-method (G a b) 'top)
@end lisp
The @code{define-generic} call defines @var{G} as a generic
function. Note that the signature of the generic function is not given
upon definition, contrarily to CLOS. This will permit methods with
different signatures for a given generic function, as we shall see
later. The three next lines define methods for the @var{G} generic
function. Each method uses a sequence of @dfn{parameter specializers}
that specify when the given method is applicable. A specializer permits
to indicate the class a parameter must belong to (directly or
indirectly) to be applicable. If no specializer is given, the system
defaults it to @code{<top>}. Thus, the first method definition is
equivalent to
@cindex parameter specializers
@lisp
(define-method (G (a <integer>) (b <top>)) 'integer)
@end lisp
Now, let us look at some possible calls to generic function @var{G}:
@lisp
(G 2 3) @result{} integer
(G 2 #t) @result{} integer
(G 1.2 'a) @result{} real
@c (G #3 'a) @result{} real @c was {\sharpsign}
(G #t #f) @result{} top
(G 1 2 3) @result{} error (since no method exists for 3 parameters)
@end lisp
The preceding methods use only one specializer per parameter list. Of
course, each parameter can use a specializer. In this case, the
parameter list is scanned from left to right to determine the
applicability of a method. Suppose we declare now
@lisp
(define-method (G (a <integer>) (b <number>)) 'integer-number)
(define-method (G (a <integer>) (b <real>)) 'integer-real)
(define-method (G (a <integer>) (b <integer>)) 'integer-integer)
(define-method (G a (b <number>)) 'top-number)
@end lisp
In this case,
@lisp
(G 1 2) @result{} integer-integer
(G 1 1.0) @result{} integer-real
(G 1 #t) @result{} integer
(G 'a 1) @result{} top-number
@end lisp
@node Next-method, Example, Generic functions and methods, Generic functions
@subsection Next-method
When a generic function is called, the list of applicable methods is
built. As mentioned before, the most specific method of this list is
applied (see@ @ref{Generic functions and methods}). This method may call
the next method in the list of applicable methods. This is done by using
the special form @code{next-method}. Consider the following definitions
@lisp
(define-method (Test (a <integer>)) (cons 'integer (next-method)))
(define-method (Test (a <number>)) (cons 'number (next-method)))
(define-method (Test a) (list 'top))
@end lisp
With those definitions,
@lisp
(Test 1) @result{} (integer number top)
(Test 1.0) @result{} (number top)
(Test #t) @result{} (top)
@end lisp
@node Example, , Next-method, Generic functions
@subsection Example
In this section we shall continue to define operations on the @code{<complex>}
class defined in Figure@ 2. Suppose that we want to use it to implement
complex numbers completely. For instance a definition for the addition of
two complexes could be
@lisp
(define-method (new-+ (a <complex>) (b <complex>))
(make-rectangular (+ (real-part a) (real-part b))
(+ (imag-part a) (imag-part b))))
@end lisp
To be sure that the @code{+} used in the method @code{new-+} is the standard
addition we can do:
@lisp
(define-generic new-+)
(let ((+ +))
(define-method (new-+ (a <complex>) (b <complex>))
(make-rectangular (+ (real-part a) (real-part b))
(+ (imag-part a) (imag-part b)))))
@end lisp
The @code{define-generic} ensures here that @code{new-+} will be defined
in the global environment. Once this is done, we can add methods to the
generic function @code{new-+} which make a closure on the @code{+}
symbol. A complete writing of the @code{new-+} methods is shown in
Figure@ 3.
@example
@group
@lisp
(define-generic new-+)
(let ((+ +))
(define-method (new-+ (a <real>) (b <real>)) (+ a b))
(define-method (new-+ (a <real>) (b <complex>))
(make-rectangular (+ a (real-part b)) (imag-part b)))
(define-method (new-+ (a <complex>) (b <real>))
(make-rectangular (+ (real-part a) b) (imag-part a)))
(define-method (new-+ (a <complex>) (b <complex>))
(make-rectangular (+ (real-part a) (real-part b))
(+ (imag-part a) (imag-part b))))
(define-method (new-+ (a <number>)) a)
(define-method (new-+) 0)
(define-method (new-+ . args)
(new-+ (car args)
(apply new-+ (cdr args)))))
(set! + new-+)
@end lisp
@center @emph{Fig 3: Extending @code{+} for dealing with complex numbers}
@end group
@end example
@sp 3
We use here the fact that generic function are not obliged to have the
same number of parameters, contrarily to CLOS. The four first methods
implement the dyadic addition. The fifth method says that the addition
of a single element is this element itself. The sixth method says that
using the addition with no parameter always return 0. The last method
takes an arbitrary number of parameters@footnote{The parameter list for
a @code{define-method} follows the conventions used for Scheme
procedures. In particular it can use the dot notation or a symbol to
denote an arbitrary number of parameters}. This method acts as a kind
of @code{reduce}: it calls the dyadic addition on the @emph{car} of the
list and on the result of applying it on its rest. To finish, the
@code{set!} permits to redefine the @code{+} symbol to our extended
addition.
@sp 3
To terminate our implementation (integration?) of complex numbers, we can
redefine standard Scheme predicates in the following manner:
@lisp
(define-method (complex? c <complex>) #t)
(define-method (complex? c) #f)
(define-method (number? n <number>) #t)
(define-method (number? n) #f)
@dots{}
@dots{}
@end lisp
Standard primitives in which complex numbers are involved could also be
redefined in the same manner.

2788
doc/goops/goops.texi Normal file

File diff suppressed because it is too large Load diff

127
doc/goops/hierarchy.eps Normal file
View file

@ -0,0 +1,127 @@
%!PS-Adobe-2.0 EPSF
%%Title: /tmp/xfig-fig016295
%%Creator: fig2dev
%%CreationDate: Fri Jun 10 23:18:16 1994
%%For: eg@kaolin (Erick Gallesio)
%%BoundingBox: 0 0 361 217
%%Pages: 0
%%EndComments
/$F2psDict 200 dict def
$F2psDict begin
$F2psDict /mtrx matrix put
/l {lineto} bind def
/m {moveto} bind def
/s {stroke} bind def
/n {newpath} bind def
/gs {gsave} bind def
/gr {grestore} bind def
/clp {closepath} bind def
/graycol {dup dup currentrgbcolor 4 -2 roll mul 4 -2 roll mul
4 -2 roll mul setrgbcolor} bind def
/col-1 {} def
/col0 {0 0 0 setrgbcolor} bind def
/col1 {0 0 1 setrgbcolor} bind def
/col2 {0 1 0 setrgbcolor} bind def
/col3 {0 1 1 setrgbcolor} bind def
/col4 {1 0 0 setrgbcolor} bind def
/col5 {1 0 1 setrgbcolor} bind def
/col6 {1 1 0 setrgbcolor} bind def
/col7 {1 1 1 setrgbcolor} bind def
end
/$F2psBegin {$F2psDict begin /$F2psEnteredState save def} def
/$F2psEnd {$F2psEnteredState restore end} def
%%EndProlog
$F2psBegin
0 setlinecap 0 setlinejoin
-216.0 288.0 translate 0.900 -0.900 scale
0.500 setlinewidth
n 309 159 m 309 159 l gs col-1 s gr
n 246.401 216.889 m 244.000 209.000 l 249.831 214.831 l gs 2 setlinejoin col-1 s gr
% Polyline
n 244 209 m 274 259 l gs col-1 s gr
n 298.169 214.831 m 304.000 209.000 l 301.599 216.889 l gs 2 setlinejoin col-1 s gr
% Polyline
n 304 209 m 274 259 l gs col-1 s gr
n 255.721 213.778 m 249.000 209.000 l 257.179 210.053 l gs 2 setlinejoin col-1 s gr
% Polyline
n 249 209 m 364 254 l gs col-1 s gr
n 370.312 216.376 m 374.000 209.000 l 374.217 217.243 l gs 2 setlinejoin col-1 s gr
% Polyline
n 374 209 m 364 254 l gs col-1 s gr
n 283.772 280.725 m 279.000 274.000 l 286.376 277.688 l gs 2 setlinejoin col-1 s gr
% Polyline
n 279 274 m 314 304 l gs col-1 s gr
n 351.457 272.333 m 359.000 269.000 l 353.913 275.490 l gs 2 setlinejoin col-1 s gr
% Polyline
n 359 269 m 314 304 l gs col-1 s gr
n 300.950 165.789 m 309.000 164.000 l 302.739 169.367 l gs 2 setlinejoin col-1 s gr
% Polyline
n 309 164 m 249 194 l gs col-1 s gr
n 307.000 172.000 m 309.000 164.000 l 311.000 172.000 l gs 2 setlinejoin col-1 s gr
% Polyline
n 309 164 m 309 199 l gs col-1 s gr
n 315.261 169.367 m 309.000 164.000 l 317.050 165.789 l gs 2 setlinejoin col-1 s gr
% Polyline
n 309 164 m 379 199 l gs col-1 s gr
n 406.949 101.701 m 404.000 94.000 l 410.226 99.407 l gs 2 setlinejoin col-1 s gr
% Polyline
n 404 94 m 439 144 l gs col-1 s gr
n 410.363 99.245 m 404.000 94.000 l 412.083 95.634 l gs 2 setlinejoin col-1 s gr
% Polyline
n 404 94 m 509 144 l gs col-1 s gr
n 411.173 98.068 m 404.000 94.000 l 412.243 94.214 l gs 2 setlinejoin col-1 s gr
% Polyline
n 404 94 m 584 144 l gs col-1 s gr
n 396.075 96.277 m 404.000 94.000 l 398.079 99.739 l gs 2 setlinejoin col-1 s gr
% Polyline
n 404 94 m 309 149 l gs col-1 s gr
% Polyline
n 584 229 m 584 204 l gs col-1 s gr
n 582.000 212.000 m 584.000 204.000 l 586.000 212.000 l gs 2 setlinejoin col-1 s gr
% Polyline
n 584 189 m 584 159 l gs col-1 s gr
n 582.000 167.000 m 584.000 159.000 l 586.000 167.000 l gs 2 setlinejoin col-1 s gr
/Times-Bold findfont 12.00 scalefont setfont
239 209 m
gs 1 -1 scale (A) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
274 274 m
gs 1 -1 scale (D) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
359 269 m
gs 1 -1 scale (E) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
304 209 m
gs 1 -1 scale (B) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
374 209 m
gs 1 -1 scale (C) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
314 319 m
gs 1 -1 scale (F) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
289 159 m
gs 1 -1 scale (<object>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
389 89 m
gs 1 -1 scale (<top>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
424 154 m
gs 1 -1 scale (<pair>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
474 154 m
gs 1 -1 scale (<procedure>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
559 154 m
gs 1 -1 scale (<number>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
629 154 m
gs 1 -1 scale (...) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
569 199 m
gs 1 -1 scale (<real>) col-1 show gr
/Times-Bold findfont 12.00 scalefont setfont
559 239 m
gs 1 -1 scale (<integer>) col-1 show gr
$F2psEnd

14
doc/goops/hierarchy.txt Normal file
View file

@ -0,0 +1,14 @@
<top>
/ \\\_____________________
/ \\___________ \
/ \ \ \
<object> <pair> <procedure> <number>
/ | \ |
/ | \ |
A B C <complex>
|\__/__ | |
\ / \ / |
D E <real>
\ / |
F |
<integer>

66
doc/goops/mop.text Normal file
View file

@ -0,0 +1,66 @@
*** NOTE: This information needs updating! ***
P - procedure
L - local procedure
S - syntax
G - generic
M - method
define-class (S)
make-class (S)
ensure-metaclass (P)
ensure-metaclass-with-supers (P)
make (G)
ensure-class (P)
make (G)
class-redefinition (G)
remove-class-accessors (G)
update-direct-method (G)
update-direct-subclass (G)
define-generic (S)
make-generic-function (S)
ensure-generic-function (P)
make (G)
define-method (S)
ensure-method (P)
ensure-generic-function (P)
make (G)
make (G)
add-method (P)
method (S)
ensure-method (P)
initialize (class) (M)
compute-cpl (P)
compute-slots (G)
compute-getters-n-setters (P)
compute-slot-init-function (L)
compute-get-n-set (G)
compute-slot-accessors (P)
ensure-method (P)
%inherit-magic! (P)
%prep-layout! (P)
initialize (generic) (M)
make (G)
change-class (G)
change-object-class (P)
update-instance-for-different-class (G)
make = make-instance (G)
allocate-instance (G)
%allocate-instance (P)
initialize (G)
%initialize-object (P)
apply-generic (G)
compute-applicable-methods (G)
find-method (P)
sort-applicable-methods (G)
sort (P)
apply-methods (G)
apply-method (G)

View file

View file

View file

View file

View file

View file

View file

View file

View file

23
doc/r5rs/.cvsignore Normal file
View file

@ -0,0 +1,23 @@
Makefile
Makefile.in
stamp-vti
stamp-vti.1
*.log
*.dvi
*.aux
*.toc
*.cp
*.fn
*.vr
*.tp
*.ky
*.pg
*.cps
*.fns
*.tps
*.vrs
*.ps
*.info*
*.html
version.texi
version-tutorial.texi

8538
doc/r5rs/r5rs.texi Normal file

File diff suppressed because it is too large Load diff

23
doc/ref/.cvsignore Normal file
View file

@ -0,0 +1,23 @@
Makefile
Makefile.in
stamp-vti
stamp-vti.1
*.log
*.dvi
*.aux
*.toc
*.cp
*.fn
*.vr
*.tp
*.ky
*.pg
*.cps
*.fns
*.tps
*.vrs
*.ps
*.info*
*.html
version.texi
version-tutorial.texi

View file

@ -0,0 +1,890 @@
2001-03-09 Neil Jerram <neil@ossau.uklinux.net>
Moving texinfo files from guile-doc/ref into guile-core/doc:
* env.texi, indices.texi, mbapi.texi, mltext.texi, scripts.texi,
scsh.texi, tcltk.texi, hierarchy.txt, scheme-indices.texi,
slib.texi, deprecated.texi, scheme-binding.texi, appendices.texi,
scheme-intro.texi, goops.texi, extend.texi, gh.texi, intro.texi,
preface.texi, scm.texi, goops-tutorial.texi, hierarchy.eps,
r4rs.texi, r5rs.texi, texinfo.tex, scheme-reading.texi,
data-rep.texi, scheme-utility.texi, posix.texi,
scheme-control.texi, scheme-debug.texi, scheme-evaluation.texi,
scheme-io.texi, scheme-memory.texi, scheme-modules.texi,
scheme-options.texi, scheme-procedures.texi,
scheme-scheduling.texi, scheme-translation.texi, guile.texi,
scheme-data.texi, scheme-ideas.texi, expect.texi: Removed.
2001-02-28 Gary Houston <ghouston@arglist.com>
* expect.texi (Expect): add missing eof? argument in example code.
2001-02-27 Neil Jerram <neil@ossau.uklinux.net>
* guile.texi, scheme-data.texi, scheme-ideas.texi: Remove the code
that set paragraph indent to zero, then add @noindent to several
places that need not to be indented.
2001-02-24 Neil Jerram <neil@ossau.uklinux.net>
* posix.texi (File System, Time), scheme-control.texi
(Exceptions), scheme-data.texi (Complex, Primitive Numerics,
Random, String Fun, Symbols and Variables, Lists, Bit Vectors,
Hooks), scheme-debug.texi (Debugging), scheme-evaluation.texi
(Reader Extensions, Scheme Read, Fly Evaluation, Loading,
Evaluator Options), scheme-io.texi (Reading, Writing, Default
Ports, File Ports), scheme-memory.texi (Garbage Collection,
Guardians, Objects), scheme-modules.texi (The Guile module
system), scheme-options.texi (Install Config),
scheme-procedures.texi (Procedure Properties, Procedures with
Setters), scheme-scheduling.texi (Arbiters, Asyncs),
scheme-translation.texi (Emacs Lisp Support): Automatic docstring
updates.
* scheme-io.texi (Binary IO): New node.
* scheme-control.texi (Multiple Values): New node.
2001-02-23 Neil Jerram <neil@ossau.uklinux.net>
* scheme-utility.texi (Sorting), scheme-procedures.texi (Procedure
Properties), scheme-memory.texi (Guardians), scheme-io.texi
(Line/Delimited), scheme-data.texi (String Fun, Symbols and
Variables, Vtables), posix.texi (Ports and File Descriptors, File
System, Network Sockets and Communication): Automatic docstring
updates.
2001-02-15 Neil Jerram <neil@ossau.uklinux.net>
* data-rep.texi: Preserve, in comments beginning `@c essay',
material from the standalone version of this essay which is very
soon to be retired from its current location at
guile-core/doc/data-rep.texi.
* data-rep.texi: Incorporate recent changes to smob example
documentation from the standalone version of this essay.
2001-02-02 Neil Jerram <neil@ossau.uklinux.net>
* scheme-reading.texi (Further Reading): Add reference to online
version of SICP.
2001-01-27 Neil Jerram <neil@ossau.uklinux.net>
Further changes to get everything to build to dvi with the latest
texinfo.tex.
* texinfo.tex: Replaced by latest version from ftp.gnu.org.
* r5rs.texi (Binding constructs): Remove @c inside @t{...} at
lines 2207-2209.
(Lexical structure): Remove @c inside @t{...} at line 7517.
* r4rs.texi (Example): Remove @c inside @t{...} at lines 6557 and
6569.
2001-01-26 Neil Jerram <neil@ossau.uklinux.net>
* scm.texi (Handling Errors): Improved markup.
(snarfing): Deleted.
* data-rep.texi: File copied here from sources directory and
integrated into the reference manual structure.
* extend.texi (Libguile Intro): New file, new node, to introduce
new Part.
* guile.texi: Merged Parts V and VI into a single Part: "Extending
Applications Using Guile". Improved some top level node names and
descriptions. Include extend.texi and data-rep.texi.
* preface.texi (Manual Layout): Updated according to merge of
Parts V and VI.
* gh.texi: Restructured into a single chapter.
* scm.texi (C Port Interface, Port Implementation): Moved here
from scheme-io.texi.
* scheme-io.texi (Default Ports): Renamed from `Port
Environment'.
(Port Internals): Contents moved to scm.texi.
* r5rs.texi: Changes to allow building of r5rs.dvi from r5rs.texi.
Aubrey Jaffer's view - which I agree with - is that, given that
people have the option of building r5rs.dvi from the original
LaTeX distribution for R5RS, it is not worth fixing his master
copy of r5rs.texi and the tool which autogenerates it. On the
other hand, it is a marginal convenience for people to be able to
build hardcopy from r5rs.texi, even if the results are less good
than with the original LaTeX. Hence the following fixes.
(lines 714, 725, 728, 1614, 2258): Remove invalid parentheses from
@deffn statements.
(line 2316): Change @deffnx to @deffn, and insert `@end deffn' to
terminate preceding @deffn.
(line 7320): Insert `@c ' at beginning of lines that are intended
to be @ignore'd.
* guile.texi, r4rs.texi, r5rs.texi: Align @direntry descriptions
to start in column 32.
2001-01-24 Neil Jerram <neil@ossau.uklinux.net>
* intro.texi: Licensing and Layout material moved to
preface.texi.
(Whirlwind Tour): New chapter as top level for preexisting
sections.
* guile.texi: Various minor changes to improve the structure at
the beginning of the reference manual.
* preface.texi: New file, to split out "prefatory material".
Initially with Licensing and Layout material taken from
intro.texi.
* Makefile.am (dist_texis): Add preface.texi.
2001-01-19 Neil Jerram <neil@ossau.uklinux.net>
* intro.texi: Change R4RS everywhere to R5RS.
(What is Guile?): Change "compiling" to "translating".
2001-01-07 Neil Jerram <neil@ossau.uklinux.net>
* appendices.texi (Internals): Content merged into Symbols and
Variables node of scheme-data.texi.
(Reporting Bugs): Moved to manual Part I.
* guile.texi: Inserted new Part for `Guile Modules' as distinct
from core Guile Scheme language/features. Other parts renumbered
correspondingly. Module chapters moved into new part.
* intro.texi (Reporting Bugs): Node moved here from
appendices.texi.
* posix.texi (POSIX): Node name changed from `POSIX System Calls
and Networking'.
* scheme-data.texi (Symbols and Variables): Added texinfo markup
to docstrings that didn't have it. Expanded snarfed argument
names like `o' and `s' to `obarray' and `string'.
* scheme-debug.texi (Debugging): Node name changed from `Internal
Debugging Interface'.
* scheme-evaluation.texi (Fly Evaluation): Moved doc for
`interaction-environment' here (previously under module doc).
* scheme-memory.texi: Structure reorganization.
* scheme-modules.texi: Structure reorganization. Removed empty
subsections `First-class Variables' and `First-class Modules'.
* scheme-options.texi (Options and Config): Node name changed from
`Options'.
(Install Config) Node name changed from `Configuration Data'.
* scheme-scheduling.texi (Scheduling): Node name changed from
`Threads and Dynamic Roots'.
* scheme-translation.texi (Translation): New top level node for
translation documentation.
2001-01-05 Neil Jerram <neil@ossau.uklinux.net>
* scheme-exceptions.texi: Removed.
* Makefile.am (dist_texis): Removed scheme-exceptions.texi.
* guile.texi (Top): Renamed/redescribed some top level nodes. No
longer include scheme-exceptions.texi.
* scheme-control.texi: Merge material that was previously in
scheme-exceptions.texi.
* posix.texi: Updated close-port reference.
* scheme-binding.texi, scheme-control.texi,
scheme-evaluation.texi, scheme-intro.texi, scheme-io.texi,
scheme-procedures.texi, scheme-utility.texi: Massaged into desired
structure.
* scheme-data.texi (Generic Data Types): Changed to "Data Types".
(Numbers) Introduction streamlined.
(Complex Numbers) New material.
2001-01-05 Neil Jerram <neil@ossau.uklinux.net>
* scheme-data.texi, scheme-io.texi, scheme-memory.texi,
scheme-options.texi: Where a single docstring documents more than
one primitive, add a docstring comment for each additionally
documented primitive.
* scheme-modules.texi: Update docstring for dynamic-func.
* scheme-data.texi (Numbers, Numerical Tower, Integers, Reals and
Rationals, Number Syntax): New material.
* deprecated.texi (Deprecated): Remove obsolete MD5 comment line.
2000-12-12 Neil Jerram <neil@ossau.uklinux.net>
* scheme-data.texi (Numbers): Documentation added for scientific
functions.
* Makefile.am (dist_texis): Updated following split of scheme.texi
into per-chapter files.
2000-12-07 Neil Jerram <neil@ossau.uklinux.net>
* scheme-data.texi (Booleans): Written.
(Numbers): Introduction written, primitives organized into
subsections.
2000-12-06 Neil Jerram <neil@ossau.uklinux.net>
* scheme-data.texi (Generic Data Types): Added chapter
introduction.
(Bitwise Operations, Random): Moved underneath Numbers.
(Other Data Types): New placeholder section for data types that
are documented elsewhere.
* scheme-indices.texi, scheme-reading.texi: Added Local Variables
block.
2000-12-06 Neil Jerram <neil@ossau.uklinux.net>
This change replaces scheme.texi, which is unmanageably large, by
a set of smaller one-per-chapter files. The set and ordering of
the new files reflects the intended top level structure of the
Guile Scheme part of the reference manual. This structure is not
yet all reflected in the combined Texinfo/Info, though, because I
haven't yet fixed the @node levels appropriately.
* scheme.texi: Removed, after dividing content into new files.
* scheme-procedures.texi, scheme-utility.texi,
scheme-binding.texi, scheme-control.texi, scheme-io.texi,
scheme-evaluation.texi, scheme-exceptions.texi,
scheme-memory.texi, scheme-modules.texi, scheme-scheduling.texi,
scheme-options.texi, scheme-translation.texi, scheme-debug.texi,
slib.texi: New files.
* guile.texi: @include new files instead of scheme.texi. Reorder
existing top level nodes.
2000-12-01 Neil Jerram <neil@ossau.uklinux.net>
* scheme-data.texi: Remove @page breaks (following demotion).
* guile.texi (Top), scheme-ideas.texi: Demote everything one level
so that previous chapters About Data, About Procedures, About
Expressions and About Closure are now combined into a single
Scheme Ideas chapter. Add overall chapter introduction. Fix up
top level nodes accordingly.
* guile.texi (Top), scheme.texi, scheme-data.texi: Gather material
for Generic Data Types chapter into a new file
(scheme-data.texi). @include new file in guile.texi. Fix up top
level nodes accordingly. (This changes demotes all the affected
material by one level, except for that which was already grouped
together under the Data Structures node.)
* guile.texi (Top): @include new files.
* scheme-intro.texi, scheme-ideas.texi: New files.
* scheme.texi (Guile and R5RS Scheme): Moved introductory chapter
to its own file (scheme-intro.texi).
(About Closure) Chapter completed.
(About Data, About Procedures, About Expressions, About Closure):
Ideas chapters moved to their own file (scheme-ideas.texi);
scheme.texi was just getting too large!
2000-11-09 Gary Houston <ghouston@arglist.com>
* posix.texi (Ports and File Descriptors): updated
close-all-ports-except.
2000-11-07 Gary Houston <ghouston@arglist.com>
* posix.texi (Ports and File Descriptors): added dup2, close-fdes
and port-for-each.
(Pipes): synchronise open-input-pipe, open-output-pipe with
popen.scm.
2000-11-04 Gary Houston <ghouston@arglist.com>
* scheme.texi (Generic Port Operations): "port?" added.
2000-11-03 Neil Jerram <neil@ossau.uklinux.net>
* scheme.texi (About Expressions): New material about evaluation
and program execution.
* scheme.texi (About Procedures): Minor textual improvements.
2000-10-29 Neil Jerram <neil@ossau.uklinux.net>
* scheme.texi (About Expressions, About Closure): Placeholder
structure for remaining introductory Scheme material.
* guile.texi (Top): Shorten some menu item lines to fit on a
single console line.
2000-10-28 Neil Jerram <neil@ossau.uklinux.net>
* scheme-indices.texi (R5RS Index, Guile Extensions Index): Print
new indices.
* guile.texi: Define new R5RS and Guile extension indices.
2000-10-27 Neil Jerram <neil@ossau.uklinux.net>
* scheme.texi (Guile and R5RS Scheme): Filled in examples of Guile
extensions.
(About Procedures): New introductory material.
* scheme-reading.texi: New file.
* scheme-indices.texi: New file.
* intro.texi (Scripting Examples): Added @* to fix TeX overfull
hboxes (twice).
(end of file): Added Local Variables block for TeX-master
variable.
* scheme.texi (R4RS Scheme): Node changed to "Guile and R5RS
Scheme". Content changed to indicate that we plan to document
both standard Scheme and Guile extensions.
(About Data, About Procedures, About Expressions): New Scheme
introductory material chapters.
(Options): Moved material on Options into its own chapter.
(Coding With Keywords): New subsection; extends material on use of
keywords to include examples of and references to (ice-9 optargs).
(passim): Change many uses of @example to @lisp, since the
formatting seems to come out better in TeX.
(Optional Arguments): New placeholder chapter (empty).
(end of file): Added Local Variables block for TeX-master
variable.
* guile.texi (Top): "R4RS Scheme" node changed to "Guile and R5RS
Scheme". Added Scheme introductory chapters: About Data, About
Procedures and About Expressions. New Options chapter for options
material. New Optional Arguments chapter as placeholder for
(ice-9 optargs) material. New chapter for "Further Reading". New
chapters for indices showing what is standard Scheme and what is
Guile extension.
2000-10-25 Mikael Djurfeldt <mdj@linnaeus.mit.edu>
* Makefile.am: Added goops.texi and new files to dist_texis.
* goops.texi, goops-tutorial.texi, hierarchy.eps, hierarchy.txt:
New files.
2000-10-15 Neil Jerram <neil@ossau.uklinux.net>
* gh.texi (Starting and controlling the interpreter): Removed
obsolete note about boot-9.scm not being loaded by gh_enter.
(Thanks to Chris Cramer for pointing this out.)
2000-10-06 Neil Jerram <neil@ossau.uklinux.net>
* guile.texi, scheme.texi, posix.texi: Simplified docstring
comments: (i) they new refer to the Texinfo-format file that is
generated by snarfing when libguile is built, rather than to
individual C files in the libguile source; (ii) there is no longer
a need to keep MD5 digest values for the corresponding source
docstring, since I'm now using a different mechanism for keeping
track of source material changes.
* scheme.texi (Lists): Use "@example" in docstring for append.
* guile.texi, scheme.texi (Primitive Properties): New chapter,
documenting new primitive property primitives.
2000-09-22 Neil Jerram <neil@ossau.uklinux.net>
* scm.texi (I/O internals): Add full stops (periods) after
standalone uses of @xref.
* scheme.texi (Structure Layout): Doc for make-struct-layout
changed to remove reference to "read-only" strings, which no
longer exist.
(Structure Basics): Use @pxref rather than @xref for parenthetical
reference.
(Dynamic Roots): Use @code rather than @var for code, in doc for
call-with-dynamic-root.
(Low level thread primitives): Ditto call-with-new-thread.
(Higher level thread procedures): Ditto call-with-new-thread.
(Symbols and Variables): Docs for gensym and symbol-hash updated
according to libguile changes.
* posix.texi (Generic Port Operations): Synchronized docstring
for unread-string.
* gh.texi (Defining new Scheme procedures in C): Avoid texinfo
warning by using @code rather than @var for code.
* scheme.texi: Lots more docstring comments added, and docs
synchronized with libguile source.
(interaction-environment, make-struct, make-vtable-vtable): Newer,
better doc taken from source file.
(cons-source): New docstring written.
(Vectors): New section added.
(Random, Symbols and Variables): New chapters.
* posix.texi: Lots more docstring comments added.
(pipe, tzset) Newer, better documentation taken from source file.
* deprecated.texi: New file, for documenting features that are
deprecated and so planned to disappear.
* guile.texi (Procedures, Reading and Writing, Random, Sorting,
Symbols and Variables, Deprecated): New chapters in the Scheme
part of the reference manual, to hold docstrings that don't
currently fit anywhere else.
2000-08-28 Neil Jerram <neil@ossau.uklinux.net>
* posix.texi (Pipes): open-pipe and close-pipe are procedures (in
ice-9/popen.scm), not primitives.
* scheme.texi (Generic Port Operations): Remove doc for
port-revealed and set-port-revealed!, since these are covered in
posix.texi.
* posix.texi: Inserted docstring synchronization comments and
synchronized docstrings for all primitives defined in posix.c,
simpos.c, scmsigs.c, stime.c.
(Ports and File Descriptors) Similarly synchronized port-revealed
and set-port-revealed!.
2000-08-25 Neil Jerram <neil@ossau.uklinux.net>
* scheme.texi: Lots more docstrings added.
* guile.texi (Top): More new chapters: Pairs, Objects, Guardians,
Emacs Lisp Support.
* scheme.texi (Numbers): New chapter containing docs (many still
empty right now) for numerical primitives.
* guile.texi (Top): Add chapter for numerical primitives.
2000-08-18 Neil Jerram <neil@ossau.uklinux.net>
* posix.texi (Ports and File Descriptors): Docstring for select
substantially changed by update from libguile source.
* scheme.texi, posix.texi: Lots more primitive docstrings added.
* guile.texi (Top): Removed empty Reflection chapter, added new
Hooks chapter.
* scheme.texi: Added docstrings for all Guile primitives from
libguile files from arbiters.c to error.c.
(Reflection): Empty chapter removed.
* guile.texi (Top): New chapters "Booleans" and "Equality"
(temporary - until we improve the overall organization).
* scheme.texi (Uniform Arrays): Fix "indentical" typo.
2000-08-12 Neil Jerram <neil@ossau.uklinux.net>
* scheme.texi: Removed superfluous "@c docstring end" markers -
docstring.el now uses "@end deffn" to find the end of the
docstring.
Added a lot more docstring comments, and synced up docstrings with
libguile - all libguile primitives documented in scheme.texi now
have docstring comments and are up to date.
(Evaluation): Updated docstring for eval and eval-string (now
R5RS-compliant).
* intro.texi (Guile Scripts): Added a couple of blank lines.
2000-08-11 Neil Jerram <neil@ossau.uklinux.net>
* scheme.texi: Add docstring comments and sync up existing
docstrings with libguile source - complete as far as Association
Lists.
(Keywords): Fill out and improve documentation about
keywords.
* guile.texi: Set paragraph indent to zero.
2000-08-07 Neil Jerram <neil@ossau.uklinux.net>
* scm.texi (libguile error handling): Add note (text supplied by
Gary Houston) giving a pointer on how to do C exception handling
since scm_error_callback was removed.
2000-08-01 Dirk Herrmann <D.Herrmann@tu-bs.de>
* scm.texi (libguile error handling): Removed reference to
scm_error_callback, which is not available any more since
guile-1.3. Thanks to Juli-Manel Merino Vidal and to Gary Houston
for pointing this out.
2000-07-31 Neil Jerram <neil@ossau.uklinux.net>
* scm.texi (Relationship between Scheme and C functions):
Expand. (Contributed by Thien-Thi Nguyen <ttn@gnu.org>.)
2000-07-30 Neil Jerram <neil@ossau.uklinux.net>
* scheme.texi (Association Lists): New, more complete
documentation.
* guile.texi: New top-level manual file based on guile-ref.texi
but modified to reflect the better organization suggested in
sources/jimb-org.texi.
* expect.texi: New file to separate out Expect doc.
* indices.texi: New file to separate indices from appendices.
* intro.texi: Invoking Guile and Meta Switch nodes moved to Guile
Scripting part (scripts.texi). Manual layout node moved to end of
introduction.
* posix.texi: All nodes downgraded one level. Expect, SCSH and
Tcl/Tk nodes moved to dedicated files.
* scheme.texi: Stuff moved around in accordance with
sources/jimb-org.texi reorganization (cvs diff totally confused,
I'm afraid).
* scsh.texi: New file to separate out SCSH doc.
* scripts.texi: New file to separate out Guile scripting doc.
* tcltk.texi: New file to separate out Tcl/Tk interface doc.
* Makefile.am: Changed guile-ref to guile; more distribution
texis.
* Makefile.in: Changed guile-ref to guile; more distribution
texis.
2000-05-14 Marius Vollmer <mvo@zagadka.ping.de>
* posix.texi (Conventions): Added example on how to retrieve errno
value from a system-exception. Thanks to Eric Hanchrow!
2000-05-04 Marius Vollmer <mvo@zagadka.ping.de>
* intro.texi: Added chapter about Guile's license.
* guile-ref.texi: Updated menu.
1999-12-15 Gary Houston <ghouston@freewire.co.uk>
* scheme.texi (SLIB installation): new node.
1999-12-06 Gary Houston <ghouston@freewire.co.uk>
* r4rs.texi: tweaked the dircategory/direntry for compatibility
with the r5 version.
guile-ref.texi: tweaked the dircategory.
* Makefile.am (info_TEXINFOS): add r5rs.texi.
* r5rs.texi: new file, lifted from Aubrey Jaffer's site.
1999-12-04 Gary Houston <ghouston@freewire.co.uk>
* scheme.texi (Generic Port Operations): add "port-closed?".
1999-11-22 Jim Blandy <jimb@savonarola.red-bean.com>
* mbapi.texi: Don't promise any behavior on ill-formed text.
1999-11-19 Gary Houston <ghouston@freewire.co.uk>
* scheme.texi: rewrote the intros in the array nodes.
1999-11-18 Gary Houston <ghouston@freewire.co.uk>
* posix.texi (Network Sockets and Communication): add htons etc.
(Ports and File Descriptors, Network Sockets and Communication):
suggest setvbuf instead of duplicate-port for converting
unbuffered ports to buffered.
* scheme.texi (Uniform Array): add missing array types to the
table.
1999-11-17 Gary Houston <ghouston@freewire.co.uk>
* posix.texi (Network Databases): updated.
1999-10-24 Gary Houston <ghouston@freewire.co.uk>
* scheme.texi (String Ports): add with-output-to-string and
with-input-from-string.
(Port Implementation): update for ptob seek.
1999-10-18 Gary Houston <ghouston@freewire.co.uk>
* scheme.texi (C Port Interface): update the description of
the rw_random port flag.
1999-09-22 Gary Houston <ghouston@freewire.co.uk>
* scheme.texi: added a bit of documentation for port internals.
1999-09-12 Gary Houston <ghouston@easynet.co.uk>
* posix.texi (File System): make that "directory-stream?".
1999-09-11 Gary Houston <ghouston@easynet.co.uk>
* posix.texi (File System): added "directory?".
1999-09-06 James Blandy <jimb@mule.m17n.org>
* mbapi.texi, mltext.texi: New files, describing interfaces for
dealing with multilingual code.
1999-07-25 Gary Houston <ghouston@easynet.co.uk>
* scheme.texi, posix.texi: updated for changes in the I/O system
and expect macros.
1999-01-25 Mark Galassi <rosalia@cygnus.com>
* scheme.texi (General option interface): applied a typo fix.
Thanks to Eric Hanchrow (offby1@blarg.net).
1998-11-01 Mark Galassi <rosalia@cygnus.com>
* scheme.texi (Weak References): incorporated David Lutterkort's
chapter on Weak References, which is based on Mikael's email
message exchange with with Michael Livshin.
1998-10-29 Jim Blandy <jimb@zwingli.cygnus.com>
* scheme.texi: Corrected shell commands in example. (Thanks to
Chris Bitmead.)
1998-10-25 Mikael Djurfeldt <mdj@barbara.nada.kth.se>
* gh.texi (C to Scheme, Scheme to C): Completed entries about
vector conversions.
1998-08-26 Mark Galassi <rosalia@cygnus.com>
* gh.texi (Starting and controlling the interpreter): modified the
gh_enter() docs in response to some good comments from Dirk
Herrmann: now they address the issue of loading ice-9/boot-9.scm,
and include Dirk's hackaround for the problem until we fix it
properly.
1998-04-29 Mark Galassi <rosalia@cygnus.com>
* scheme.texi (Dynamic Linking from Marius): added Marius's new
chapter on dynamic linking; there is still a section in dynamic
linking (written by Tim maybe?), and I have to examine how to
resolve that.
1998-03-30 Mikael Djurfeldt <mdj@nada.kth.se>
* scheme.texi (Port Operations): Changed entry for port-column and
port-line. (Thanks to Per Bothner.)
1998-02-02 Mikael Djurfeldt <mdj@mdj.nada.kth.se>
* scheme.texi (Exceptions): Adjusted documentation to reflect the
removal of the (catch #f ...) mechanism.
1998-01-28 Mark Galassi <rosalia@nis.lanl.gov>
* guile-ref.texi: changed @dircategory to "Scheme Programming".
It seems to be the consensus.
1998-01-20 Mikael Djurfeldt <mdj@mdj.nada.kth.se>
* gh.texi (C to Scheme): Added documentation for gh_doubles2scm
and gh_doubles2dvect.
(Scheme to C): Added documentation for gh_scm2doubles.
1998-01-15 Mark Galassi <rosalia@nis.lanl.gov>
* gh.texi (Calling Scheme procedures from C): removed
gh_make_subr() since Mikael pointed out that it is gone from
Guile. I don't remember its history any more, but I don't think
anyone is missing it.
1998-01-03 Tim Pierce <twp@skepsis.com>
* scheme.texi (Evaluation): Several corrections supplied by MDJ.
Sat Dec 27 19:02:36 1997 Tim Pierce <twp@skepsis.com>
* appendices.texi (Internals, Symbols): New nodes.
* scheme.texi (Configuration Data): New node.
1997-12-27 Tim Pierce <twp@skepsis.com>
* guile-ref.texi (Bitwise Operations): New description.
1997-12-24 Tim Pierce <twp@skepsis.com>
* scheme.texi (Port Operations, Evaluation): New nodes.
1997-12-13 Tim Pierce <twp@skepsis.com>
* scheme.texi, posix.texi: Documented each procedure as `procedure',
`primitive' or `syntax' as appropriate.
(Records): Change record-type-field-names to record-type-fields.
(Low level thread primitives): Change with-new-thread to
call-with-new-thread.
Sun Dec 7 22:47:22 1997 Gary Houston <ghouston@actrix.gen.nz>
* posix.texi (Processes): add "system" procedure.
1997-11-23 Mark Galassi <rosalia@cygnus.com>
* gh.texi (Starting and controlling the interpreter): added
documentation for gh_repl() -- gh_repl() has changed since I saw
the scm_shell() routine.
1997-11-19 Tim Pierce <twp@twp.tezcat.com>
* scheme.texi (String Fun): New node.
(Hash Tables): Added `get-handle' and `create-handle!' docs.
* posix.texi (Networking Databases): Add docs for gethost, getnet,
getserv, getproto. Expanded on miscellaneous docs.
1997-11-18 Tim Pierce <twp@twp.tezcat.com>
* posix.texi: New file; moved docs for POSIX interface here.
* Makefile.am: Add posix.texi.
* Makefile.in: Regenerated.
* guile-ref.texi: Reorganize top-level menu. @include posix.texi.
* scheme.texi: Moved many nodes around, some restructuring
(e.g. new "Data Structures" node for records, structures, arrays,
hash tables, and so on).
1997-10-19 Mark Galassi <rosalia@cygnus.com>
* gh.texi (Calling Scheme procedures from C): added many routines
as I go through R4RS and try to complete the gh_ interface.
Wed Oct 8 04:51:54 1997 Gary Houston <ghouston@actrix.gen.nz>
* scheme.texi (Dynamic Roots): added batch mode procedures.
1997-10-03 Mikael Djurfeldt <mdj@nada.kth.se>
* scheme.texi (Vtables): Changed 0 --> @code{vtable-index-layout};
Changed @code{struct-vtable-offset} --> @code{vtable-offset-user};
Added short note about the print call-back initializer. (This
section is in need of review. However, we shoudn't spend much
time on it since the structs will be replaced by something
equivalent, but with a different interface.}
Sun Sep 28 00:02:35 1997 Mark Galassi <rosalia@nis.lanl.gov>
* scheme.texi (Keywords): very small re-organization to take
advantage of the fact that read-options is now documented in
another chapter.
Thu Sep 25 23:37:02 1997 Mark Galassi <rosalia@nis.lanl.gov>
* scheme.texi (Guile options interface): renamed the symbol case
section to "Guile options interface". "Reader options" is now a
subsection of that. I've finally figured a lot of how options
work, thanks to discovering Mikael's comments in options.c and an
old note from Mikael to Jim describing it.
(Guile options interface): reorganized the individual option
groups. This section (on options) of the manual is now reasonably
complete, unless I am completely missing something.
Wed Sep 24 15:25:03 1997 Mark Galassi <rosalia@nis.lanl.gov>
* scheme.texi (The Guile module system): Added a bit more to this
chapter, mostly the more user-friendly (use-modules (ice-9
module-name)) approach.
(Symbol case): tried to write something about this, but it will
need to be reviewed by someone who understands the big picture of
read options. I also think the section name should be changed to
something like "Read options".
Sun Sep 21 18:45:57 1997 Mark Galassi <rosalia@nis.lanl.gov>
* scheme.texi (SLIB): some little details, including splitting off
what does in the installation chapter. Also added a section on
Jacal, which has some open issues.
* appendices.texi (Packages not shipped with Guile): added this
section to describe getting resources on SCSH, SLIB and Jacal (and
who knows what else in the future).
Sat Aug 30 19:31:22 1997 Gary Houston <ghouston@actrix.gen.nz>
* scheme.texi (Uniform Array): mention start and end arguments
for uniform-array-read! and uniform-array-write.
Sat Aug 23 19:05:08 1997 Gary Houston <ghouston@actrix.gen.nz>
* guile-ref.texi (Top): corresponding changes.
* scheme.texi (Exception Handling): add scm-error, strerror.
(Exceptions): renamed from Exception Handling.
(Exceptions): deleted empty section.
Mon Aug 18 16:11:43 1997 Jim Blandy <jimb@totoro.red-bean.com>
* texinfo.tex: Installed from texinfo release 3.11.
Fri Aug 15 08:14:32 1997 Gary Houston <ghouston@actrix.gen.nz>
* scheme.texi (file system): added truncate-file.
chown, fcntl, fseek, ftell updated.
(ports vs file descriptors): added fsync, open, open-fdes.
(time): added times.
Sun Aug 10 07:39:55 1997 Gary Houston <ghouston@actrix.gen.nz>
* scheme.texi (processes): added execle.
Tue Jul 29 02:01:21 1997 Gary Houston <ghouston@actrix.gen.nz>
* setvbuf added. primitive-dup[2] removed.
Sat Jul 26 04:25:40 1997 Gary Houston <ghouston@actrix.gen.nz>
* various close and dup procedures added, plus setenv.
Sat Jul 19 04:04:50 1997 Gary Houston <ghouston@actrix.gen.nz>
* scheme.texi (signals): new section.
(processes): primitive-exit.
(ports vs. file descriptors): force-output, flush-all-ports.
fcntl from NEWS.
Fri Jul 18 07:58:52 1997 Gary Houston <ghouston@actrix.gen.nz>
* scheme.texi (SLIB): update initialization details.
(expect): likewise.
(The Scheme shell (scsh)): likewise.
Fri Jun 27 00:31:25 1997 Tim Pierce <twp@twp.tezcat.com>
* scheme.texi (Regexp Functions): Add docs for make-regexp flags
regexp/icase, regexp/newline, regexp/basic, regexp/extended.
Mon Jun 23 12:35:57 1997 Tim Pierce <twpierce@bio-5.bsd.uchicago.edu>
* appendices.texi (debugger user interface): new text.
(Single-Step, Trace, Backtrace): new nodes.
* scheme.texi: Many revised nodes, some new ones.
(Binary Numeric Operations, Input/Output Ports, File Ports, Soft
Ports, String Ports): Imported documentation from SCM and SLIB manuals.
(Association Lists and Hash Tables, Dictionary Types, Association
Lists, Hash Tables): New nodes.
(Dictionaries in general): Removed.
(Regular Expressions): Replaced.
(Rx Interface): New node, renamed from old `Regular Expressions'.
(Regexp Functions, Match Functions, Backslash Escapes): new nodes.
(Property Lists): new node with documentation for both object and
procedure properties.
(Object Properties): removed.
* guile-ref.texi: change `Object Properties' to `Property Lists'.

185
doc/ref/api.txt Normal file
View file

@ -0,0 +1,185 @@
Scheme objects
==============
There are two basic C data types to represent objects in guile:
- SCM: SCM is the user level abstract C type that is used to represent all of
guile's scheme objects, no matter what the scheme object type is. No C
operation except assignment is guaranteed to work with variables of type SCM.
Only use macros and functions to work with SCM values. Values are converted
between C data types and the SCM type with utility functions and macros.
- scm_bits_t: An integral data type that is guaranteed to be large enough to
hold all information that is required to represent any scheme object. While
this data type is used to implement guile internals, the use of this type is
also necessary to write certain kinds of extensions to guile.
Relationship between SCM and scm_bits_t
=======================================
A variable of type SCM is guaranteed to hold a valid scheme object. A
variable of type scm_bits_t, however, may either hold a representation of a
SCM value as a C integral type, but may also hold any C value, even if it does
not correspond to a valid scheme object.
For a variable x of type SCM, the scheme object's type information is stored
in a form that is not directly usable. To be able to work on the type
encoding of the scheme value, the SCM variable has to be transformed into the
corresponding representation as a scm_bits_t variable y by using the
SCM_UNPACK macro. After this has been done, the type of the scheme object x
can be derived from the content of the bits of the scm_bits_t value y, as is
described in -->data-rep. A valid bit encoding of a scheme value as a
scm_bits_t variable can be transformed into the corresponding SCM value by
using the SCM_PACK macro.
- scm_bits_t SCM_UNPACK (SCM x): Transforms the SCM value x into it's
representation as an integral type. Only after applying SCM_UNPACK it is
possible to access the bits and contents of the SCM value.
- SCM SCM_PACK (scm_bits_t x): Takes a valid integral representation of a
scheme object and transforms it into its representation as a SCM value.
Immediate objects
=================
A scheme object may either be an immediate, i. e. carrying all necessary
information by itself, or it may contain a reference to a 'cell' with
additional information on the heap. While the fact, whether an object is an
immediate or not should be irrelevant for user code, within guile's own code
the distinction is sometimes of importance. Thus, the following low level
macro is provided:
- int SCM_IMP (SCM x): A scheme object is an immediate if it fullfills the
SCM_IMP predicate, otherwise it holds an encoded reference to a heap cell.
The result of the predicate is delivered as a C style boolean value. User
code and code that extends guile should normally not be required to use this
macro.
Summary:
* For a scheme object x of unknown type, check first with SCM_IMP (x) if it is
an immediate object. If so, all of the type and value information can be
determined from the scm_bits_t value that is delivered by SCM_UNPACK (x).
Non immediate objects
=====================
- (scm_cell *) SCM2PTR (SCM x) (FIXME:: this name should be changed)
- SCM PTR2SCM (scm_cell * x) (FIXME:: this name should be changed)
A scheme object of type SCM that does not fullfill the SCM_IMP predicate holds
an encoded reference to a heap cell. This reference can be decoded to a C
pointer to a heap cell using the SCM2PTR macro. The encoding of a pointer to
a heap cell into a SCM value is done using the PTR2SCM macro.
Note that it is also possible to transform a non immediate SCM value by using
SCM_UNPACK into a scm_bits_t variable. Hower, the result of SCM_UNPACK may
not be used as a pointer to a scm_cell: Only SCM2PTR is guaranteed to
transform a SCM object into a valid pointer to a heap cell. Also, it is not
allowed to apply PTR2SCM to anything that is not a valid pointer to a heap
cell.
Summary:
* Only use SCM2PTR for SCM values for which SCM_IMP is false!
* Don't use '(scm_cell*) SCM_UNPACK (x)'! Use 'SCM2PTR (x)' instead!
* Don't use PTR2SCM for anything but a cell pointer!
Heap Cell Type Information
==========================
Heap cells contain a number of entries, each of which is either a scheme
object of type SCM or a raw C value of type scm_bits_t. Which of the cell
entries contain scheme objects and which contain raw C values is determined by
the first entry of the cell, which holds the cell type information.
- scm_bits_t SCM_CELL_TYPE (SCM x): For a non immediate scheme object x,
deliver the content of the first entry of the heap cell referenced by x. This
value holds the information about the cell type as described in -->data-rep.
- void SCM_SET_CELL_TYPE (SCM x, scm_bits_t t): For a non immediate scheme
object x, write the value t into the first entry of the heap cell referenced
by x. The value t must hold a valid cell type as described in -->data-rep.
Accessing Cell Entries
======================
For a non immediate scheme object x, the object type can be determined by
reading the cell type entry using the SCM_CELL_TYPE macro. For the different
types of cells it is known which cell entry holds scheme objects and which cell
entry holds raw C data. To access the different cell entries appropriately,
the following macros are provided:
- scm_bits_t SCM_CELL_WORD (SCM x, unsigned int n): Deliver the cell entry n
of the heap cell referenced by the non immediate scheme object x as raw data.
It is illegal, to access cell entries that hold scheme objects by using these
macros. For convenience, the following macros are also provided:
SCM_CELL_WORD_0 (x) --> SCM_CELL_WORD (x, 0)
SCM_CELL_WORD_1 (x) --> SCM_CELL_WORD (x, 1)
...
SCM_CELL_WORD_n (x) --> SCM_CELL_WORD (x, n)
- SCM SCM_CELL_OBJECT (SCM x, unsigned int n): Deliver the cell entry n of
the heap cell referenced by the non immediate scheme object x as a scheme
object. It is illegal, to access cell entries that do not hold scheme objects
by using these macros. For convenience, the following macros are also
provided:
SCM_CELL_OBJECT_0 (x) --> SCM_CELL_OBJECT (x, 0)
SCM_CELL_OBJECT_1 (x) --> SCM_CELL_OBJECT (x, 1)
...
SCM_CELL_OBJECT_n (x) --> SCM_CELL_OBJECT (x, n)
- void SCM_SET_CELL_WORD (SCM x, unsigned int n, scm_bits_t w): Write the raw
C value w into entry number n of the heap cell referenced by the non immediate
scheme value x. Values that are written into cells this way may only be read
from the cells using the SCM_CELL_WORD macros or, in case cell entry 0 is
written, using the SCM_CELL_TYPE macro. For the special case of cell entry 0
it has to be made sure that w contains a cell type information (see
-->data-rep) which does not describe a scheme object. For convenience, the
following macros are also provided:
SCM_SET_CELL_WORD_0 (x, w) --> SCM_SET_CELL_WORD (x, 0, w)
SCM_SET_CELL_WORD_1 (x, w) --> SCM_SET_CELL_WORD (x, 1, w)
...
SCM_SET_CELL_WORD_n (x, w) --> SCM_SET_CELL_WORD (x, n, w)
- void SCM_SET_CELL_OBJECT (SCM x, unsigned int n, SCM o): Write the scheme
object o into entry number n of the heap cell referenced by the non immediate
scheme value x. Values that are written into cells this way may only be read
from the cells using the SCM_CELL_OBJECT macros or, in case cell entry 0 is
written, using the SCM_CELL_TYPE macro. For the special case of cell entry 0
the writing of a scheme object into this cell is only allowed, if the cell
forms a scheme pair. For convenience, the following macros are also provided:
SCM_SET_CELL_OBJECT_0 (x, o) --> SCM_SET_CELL_OBJECT (x, 0, o)
SCM_SET_CELL_OBJECT_1 (x, o) --> SCM_SET_CELL_OBJECT (x, 1, o)
...
SCM_SET_CELL_OBJECT_n (x, o) --> SCM_SET_CELL_OBJECT (x, n, o)
Summary:
* For a non immediate scheme object x of unknown type, get the type
information by using SCM_CELL_TYPE (x).
* As soon as the cell type information is available, only use the appropriate
access methods to read and write data to the different cell entries.
Basic Rules for Accessing Cell Entries
======================================
For each cell type it is generally up to the implementation of that type which
of the corresponding cell entries hold scheme objects and which hold raw C
values. However, there is one basic rules that has to be followed: Scheme
pairs consist of exactly two cell entries, which both contain scheme objects.
Further, a cell which contains a scheme object in it first entry has to be a
scheme pair. In other words, it is not allowed to store a scheme object in
the first cell entry and a non scheme object in the second cell entry.
Fixme:shouldn't this rather be SCM_PAIRP / SCM_PAIR_P ?
- int SCM_CONSP (SCM x): Determine, whether the scheme object x is a scheme
pair, i. e. whether x references a heap cell consisting of exactly two
entries, where both entries contain a scheme object. In this case, both
entries will have to be accessed using the SCM_CELL_OBJECT macros. On the
contrary, if the SCM_CONSP predicate is not fulfilled, the first entry of the
scheme cell is guaranteed not to be a scheme value and thus the first cell
entry must be accessed using the SCM_CELL_WORD_0 macro.

View file

@ -46,7 +46,7 @@
@c essay @sp 10
@c essay @comment The title is printed in a large font.
@c essay @title Data Representation in Guile
@c essay @subtitle $Id: data-rep.texi,v 1.26 2001-06-08 22:35:30 ossau Exp $
@c essay @subtitle $Id: data-rep.texi,v 1.1 2001-08-24 09:40:29 ossau Exp $
@c essay @subtitle For use with Guile @value{VERSION}
@c essay @author Jim Blandy
@c essay @author Free Software Foundation

138
doc/ref/deprecated.texi Normal file
View file

@ -0,0 +1,138 @@
@page
@node Deprecated
@chapter Deprecated
@menu
* Shared And Read Only Strings::
@end menu
@node Shared And Read Only Strings
@section 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.
@end menu
@node Shared Substrings
@subsection Shared Substrings
Whenever you extract a substring using @code{substring}, the Scheme
interpreter allocates a new string and copies data from the old string.
This is expensive, but @code{substring} is so convenient for
manipulating text that programmers use it often.
Guile Scheme provides the concept of the @dfn{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.
@deffn primitive make-shared-substring str [start [end]]
Return a shared substring of @var{str}. The arguments are the
same as for the @code{substring} function: the shared substring
returned includes all of the text from @var{str} between
indexes @var{start} (inclusive) and @var{end} (exclusive). If
@var{end} is omitted, it defaults to the end of @var{str}. The
shared substring returned by @code{make-shared-substring}
occupies the same storage space as @var{str}.
@end deffn
Example:
@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 =========> |---------|
@end example
The shared substring @var{bar} is not given its own storage space.
Instead, the Guile interpreter notes internally that @var{bar} points to
a portion of the memory allocated to @var{foo}. However, @var{bar}
behaves like an ordinary string in most respects: it may be used with
string primitives like @code{string-length}, @code{string-ref},
@code{string=?}. Guile makes the necessary translation between indices
of @var{bar} and indices of @var{foo} automatically.
@example
(string-length? bar) @result{} 5 ; bar only extends from indices 4 to 9
(string-ref bar 3) @result{} #\c ; same as (string-ref foo 7)
(make-shared-substring bar 2)
@result{} "ick" ; can even make a shared substring!
@end example
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.
@example
(string-set! foo 7 #\r)
bar @result{} "quirk"
@end example
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.
@node Read Only Strings
@subsection Read Only Strings
In previous versions of Guile, there was the idea that some string-based
primitives such as @code{string-append} could equally accept symbols as
arguments. For example, one could write
@lisp
(string-append '/home/ 'vigilia)
@end lisp
@noindent
and get @code{"/home/vigilia"} as the result. The term @dfn{read only
string} was adopted to describe the argument type expected by such
primitives.
This idea has now been removed. The predicate @code{read-only-string?}
still exists, but deprecated, and is equivalent to
@lisp
(lambda (x) (or (string? x) (symbol? x)))
@end lisp
@noindent
But no Guile primitives now use @code{read-only-string?} to validate
their arguments.
String-based primitives such as @code{string-append}
now require strings:
@lisp
(string-append '/home/ 'vigilia)
@result{}
ERROR: Wrong type argument (expecting STRINGP): /home/
@end lisp
@deffn primitive read-only-string? obj
Return @code{#t} if @var{obj} is either a string or a symbol,
otherwise return @code{#f}.
@end deffn

142
doc/ref/expect.texi Normal file
View file

@ -0,0 +1,142 @@
@page
@node Expect
@chapter Expect
The macros in this section are made available with:
@smalllisp
(use-modules (ice-9 expect))
@end smalllisp
@code{expect} is a macro for selecting actions based on the output from
a port. The name comes from a tool of similar functionality by Don Libes.
Actions can be taken when a particular string is matched, when a timeout
occurs, or when end-of-file is seen on the port. The @code{expect} macro
is described below; @code{expect-strings} is a front-end to @code{expect}
based on regexec (see the regular expression documentation).
@defmac expect-strings clause @dots{}
By default, @code{expect-strings} will read from the current input port.
The first term in each clause consists of an expression evaluating to
a string pattern (regular expression). As characters
are read one-by-one from the port, they are accumulated in a buffer string
which is matched against each of the patterns. When a
pattern matches, the remaining expression(s) in
the clause are evaluated and the value of the last is returned. For example:
@smalllisp
(with-input-from-file "/etc/passwd"
(lambda ()
(expect-strings
("^nobody" (display "Got a nobody user.\n")
(display "That's no problem.\n"))
("^daemon" (display "Got a daemon user.\n")))))
@end smalllisp
The regular expression is compiled with the @code{REG_NEWLINE} flag, so
that the ^ and $ anchors will match at any newline, not just at the start
and end of the string.
There are two other ways to write a clause:
The expression(s) to evaluate
can be omitted, in which case the result of the regular expression match
(converted to strings, as obtained from regexec with match-pick set to "")
will be returned if the pattern matches.
The symbol @code{=>} can be used to indicate that the expression is a
procedure which will accept the result of a successful regular expression
match. E.g.,
@smalllisp
("^daemon" => write)
("^d\\(aemon\\)" => (lambda args (for-each write args)))
("^da\\(em\\)on" => (lambda (all sub)
(write all) (newline)
(write sub) (newline)))
@end smalllisp
The order of the substrings corresponds to the order in which the
opening brackets occur.
A number of variables can be used to control the behaviour
of @code{expect} (and @code{expect-strings}).
Most have default top-level bindings to the value @code{#f},
which produces the default behaviour.
They can be redefined at the
top level or locally bound in a form enclosing the expect expression.
@table @code
@item expect-port
A port to read characters from, instead of the current input port.
@item expect-timeout
@code{expect} will terminate after this number of
seconds, returning @code{#f} or the value returned by expect-timeout-proc.
@item expect-timeout-proc
A procedure called if timeout occurs. The procedure takes a single argument:
the accumulated string.
@item expect-eof-proc
A procedure called if end-of-file is detected on the input port. The
procedure takes a single argument: the accumulated string.
@item expect-char-proc
A procedure to be called every time a character is read from the
port. The procedure takes a single argument: the character which was read.
@item expect-strings-compile-flags
Flags to be used when compiling a regular expression, which are passed
to @code{make-regexp} @xref{Regexp Functions}. The default value
is @code{regexp/newline}.
@item expect-strings-exec-flags
Flags to be used when executing a regular expression, which are
passed to regexp-exec @xref{Regexp Functions}.
The default value is @code{regexp/noteol}, which prevents @code{$}
from matching the end of the string while it is still accumulating,
but still allows it to match after a line break or at the end of file.
@end table
Here's an example using all of the variables:
@smalllisp
(let ((expect-port (open-input-file "/etc/passwd"))
(expect-timeout 1)
(expect-timeout-proc
(lambda (s) (display "Times up!\n")))
(expect-eof-proc
(lambda (s) (display "Reached the end of the file!\n")))
(expect-char-proc display)
(expect-strings-compile-flags (logior regexp/newline regexp/icase))
(expect-strings-exec-flags 0))
(expect-strings
("^nobody" (display "Got a nobody user\n"))))
@end smalllisp
@end defmac
@defmac expect clause @dots{}
@code{expect} is used in the same way as @code{expect-strings},
but tests are specified not as patterns, but as procedures. The
procedures are called in turn after each character is read from the
port, with two arguments: the value of the accumulated string and
a flag to indicate whether end-of-file has been reached. The flag
will usually be @code{#f}, but if end-of-file is reached, the procedures
are called an additional time with the final accumulated string and
@code{#t}.
The test is successful if the procedure returns a non-false value.
If the @code{=>} syntax is used, then if the test succeeds it must return
a list containing the arguments to be provided to the corresponding
expression.
In the following example, a string will only be matched at the beginning
of the file:
@smalllisp
(let ((expect-port (open-input-file "/etc/passwd")))
(expect
((lambda (s eof?) (string=? s "fnord!"))
(display "Got a nobody user!\n"))))
@end smalllisp
The control variables described for @code{expect-strings} also
influence the behaviour of @code{expect}, with the exception of
variables whose names begin with @code{expect-strings-}.
@end defmac

44
doc/ref/extend.texi Normal file
View file

@ -0,0 +1,44 @@
@page
@node Libguile Intro
@chapter Using Guile as an Extension Language
The chapters in this part of the manual explain how to use Guile as a
powerful application extension language.
An important change for the 1.6.x series of Guile releases is that the
GH interface is now deprecated. For the reasoning behind this decision,
see @xref{GH deprecation}. The GH interface will continue to be
supported for the 1.6.x and 1.8.x release series, but will be dropped
thereafter, so developers are encouraged to switch progressively to the
scm interface. The last chapter in this part of the manual (@pxref{GH})
documents both how to use GH and how to switch from GH to scm.
The Guile developers believe that clarification of the GH vs. scm
debate, and the consequent deprecation of the GH interface, are in the
long term interests of the project. However it does create an
unfortunate situation for developers who want to start a project using
Guile and so read the manual to find out how to proceed. They will
discover that the GH interface, although quite well documented, is
deprecated, but that there is almost no adequate documentation for its
theoretical replacement, the scm interface. Moreover, the scm interface
still has the odd few rough edges which need smoothing down.
Therefore, although deprecated, it is quite OK to continue to use the GH
interface if you feel uncomfortable with the `scm_' interface as it
stands today. By the time that support for GH is dropped, we plan to
have thoroughly documented the `scm_' interface, and to have enhanced it
such that conversion from GH to the `scm_' interface will be very
straightforward, and probably mostly automated.
As far as documentation of the scm interface is concerned, the current
position is that it is a bit confused, but that the situation should
improve rapidly once the 1.6.0 release is out. The plan is to refocus
the bulk of Part II, currently ``Guile Scheme'', as the ``Guile API
Reference'' so that it covers both Scheme and C interfaces. (This makes
sense because almost all of Guile's primitive procedures on the Scheme
level --- e.g. @code{memq} --- are also available as C level primitives
in the scm interface --- e.g. @code{scm_memq}.) There will then remain
a certain amount of Scheme-specific (such as the ``Basic Ideas''
chapter) and C-specific documentation (such as SMOB usage and
interaction with the garbage collector) to collect into corresponding
chapters.

1164
doc/ref/gh.texi Normal file

File diff suppressed because it is too large Load diff

View file

@ -80,7 +80,7 @@ by the Free Software Foundation.
@sp 10
@comment The title is printed in a large font.
@title Guile Reference Manual
@subtitle $Id: guile.texi,v 1.12 2001-06-29 21:43:17 mgrabmue Exp $
@subtitle $Id: guile.texi,v 1.1 2001-08-24 09:40:29 ossau Exp $
@subtitle For use with Guile @value{VERSION}
@include AUTHORS

54
doc/ref/indices.texi Normal file
View file

@ -0,0 +1,54 @@
@node Concept Index
@unnumbered Concept Index
This index contains concepts, keywords and non-Schemey names for several
features, to make it easier to locate the desired sections.
@printindex cp
@page
@node Procedure Index
@unnumbered Procedure Index
@c FIXME::martin: Review me!
This is an alphabetical list of all the procedures and macros in Guile.
When looking for a particular procedure, please look under its Scheme
name as well as under its C name. The C name can be constructed from
the Scheme names by a simple transformation described in the section
@xref{Transforming Scheme name to C name}.
@printindex fn
@page
@node Variable Index
@unnumbered Variable Index
@c FIXME::martin: Review me!
This is an alphabetical list of all the important variables and
constants in Guile.
When looking for a particular variable or constant, please look under
its Scheme name as well as under its C name. The C name can be
constructed from the Scheme names by a simple transformation described
in the section @xref{Transforming Scheme name to C name}.
@printindex vr
@page
@c Spell out this node fully, because it is the last real node
@c in the top-level menu. Leaving off the pointers here causes
@c spurious makeinfo errors.
@node Type Index
@unnumbered Type Index
This is an alphabetical list of all the important data types defined in
the Guile Programmers Manual.
@printindex tp

View file

@ -1,4 +1,4 @@
@c $Id: intro.texi,v 1.12 2001-06-14 17:36:41 mvo Exp $
@c $Id: intro.texi,v 1.1 2001-08-24 09:40:29 ossau Exp $
@page
@node What is Guile?

291
doc/ref/misc-modules.texi Normal file
View file

@ -0,0 +1,291 @@
@page
@node Pretty Printing
@chapter Pretty Printing
@c FIXME::martin: Review me!
@cindex pretty printing
The module @code{(ice-9 pretty-print)} provides the procedure
@code{pretty-print}, which provides nicely formatted output of Scheme
objects. This is especially useful for deeply nested or complex data
structures, such as lists and vectors.
The module is loaded by simply saying.
@lisp
(use-modules (ice-9 pretty-print))
@end lisp
This makes the procedure @code{pretty-print} available. As an example
how @code{pretty-print} will format the output, see the following:
@lisp
(pretty-print '(define (foo) (lambda (x)
(cond ((zero? x) #t) ((negative? x) -x) (else (if (= x 1) 2 (* x x x)))))))
@print{}
(define (foo)
(lambda (x)
(cond ((zero? x) #t)
((negative? x) -x)
(else (if (= x 1) 2 (* x x x))))))
@end lisp
@deffn procedure pretty-print obj [port]
Print the textual representation of the Scheme object @var{obj} to
@var{port}. @var{port} defaults to the current output port, if not
given.
@end deffn
Beware: Since @code{pretty-print} uses it's own write procedure, it's
output will not be the same as for example the output of @code{write}.
Consider the following example.
@lisp
(write (lambda (x) x))
@print{}
#<procedure #f (x)>
(pretty-print (lambda (x) x))
@print{}
#[procedure]
@end lisp
The reason is that @code{pretty-print} does not know as much about
Guile's object types as the builtin procedures. This is particularly
important for smobs, for which a write procedure can be defined and be
used by @code{write}, but not by @code{pretty-print}.
@page
@node Formatted Output
@chapter Formatted Output
@c FIXME::martin: Review me!
@cindex format
@cindex formatted output
Outputting messages or other texts which are composed of literal
strings, variable contents, newlines and other formatting can be
cumbersome, when only the standard procedures like @code{display},
@code{write} and @code{newline} are available. Additionally, one
often wants to collect the output in strings. With the standard
routines, the user is required to set up a string port, add this port
as a parameter to the output procedure calls and then retrieve the
resulting string from the string port.
The @code{format} procedure, to be found in module @code{(ice-9
format)}, can do all this, and even more. If you are a C programmer,
you can think of this procedure as Guile's @code{fprintf}.
@deffn procedure format destination format-string args @dots{}
The first parameter is the @var{destination}, it determines where the
output of @code{format} will go.
@table @asis
@item @code{#t}
Send the formatted output to the current output port and return
@code{#t}.
@item @code{#f}
Return the formatted output as a string.
@item Any number value
Send the formatted output to the current error port and return
@code{#t}.
@item A valid output port
Send the formatted output to the port @var{destination} and return
@code{#t}.
@end table
The second parameter is the format string. It has a similar function
to the format string in calls to @code{printf} or @code{fprintf} in C.
It is output to the specified destination, but all escape sequences
are replaced by the results of formatting the corresponding sequence.
Note that escape sequences are marked with the character @code{~}
(tilde), and not with a @code{%} (percent sign), as in C.
The escape sequences in the following table are supported. When there
appears ``corresponding @var{arg}', that means any of the additional
arguments, after dropping all arguments which have been used up by
escape sequences which have been processed earlier. Some of the
format characters (the characters following the tilde) can be prefixed
by @code{:}, @code{@@}, or @code{:@@}, to modify the behaviour of the
format character. How the modified behaviour differs from the default
behaviour is described for every character in the table where
appropriate.
@table @code
@item ~~
Output a single @code{~} (tilde) character.
@item ~%
Output a newline character, thus advancing to the next output line.
@item ~&
Start a new line, that is, output a newline character if not already
at the statr of a line.
@item ~_
Output a single space character.
@item ~/
Output a single tabulator character.
@item ~|
Output a page separator (formfeed) character.
@item ~t
Advance to the next tabulator position.
@item ~y
Pretty-print the correspinding @var{arg}.
@item ~a
Output the corresponding @var{arg} like @code{display}.
@item ~s
Output the corresponding @var{arg} like @code{write}.
@item ~d
Output the corresponding @var{arg} as a decimal number.
@item ~x
Output the corresponding @var{arg} as a hexadecimal number.
@item ~o
Output the corresponding @var{arg} as an octal number.
@item ~b
Output the corresponding @var{arg} as a binary number.
@item ~r
Output the corresponding @var{arg} as a number word, e.g. 10 prints as
@code{ten}. If prefixed with @code{:}, @code{tenth} is printed, if
prefixed with @code{:@@}, roman numbers are printed.
@item ~f
Output the corresponding @var{arg} as a fixed format floating point
number, such as @code{1.34}.
@item ~e
Output the corresponding @var{arg} in exponential notation, such as
@code{1.34E+0}.
@item ~g
%% FIXME::martin: There must be a difference. Does anybody know?
Like @code{~f}.
@item ~$
Like @code{~f}, but only with two digits after the decimal point.
@item ~i
Output the corresponding @var{arg} as a complex number.
@item ~c
Output the corresponding @var{arg} as a character. If prefixed with
@code{@@}, it is printed like with @code{write}. If prefixed with
@code{:}, control characters are treated specially, for example
@code{#\newline} will be printed as @code{^J}.
@item ~p
``Plural''. If the corresponding @var{arg} is 1, nothing is printed
(or @code{y} if prefixed with @code{@@} or @code{:@@}), otherwise
@code{s} is printed (or @code{ies} if prefixed with @code{@@} or
@code{:@@}).
@item ~?, ~k
Take the corresponding argument as a format string, and the following
argument as a list of values. Then format the values with respect to
the format string.
@item ~!
Flush the output to the output port.
@item ~#\newline (tilde-newline)
@c FIXME::martin: I don't understand this from the source.
Continuation lines.
@item ~*
Argument jumping. Navigate in the argument list as specified by the
corresponding argument. If prefixed with @code{:}, jump backwards in
the argument list, if prefixed by @code{:@@}, jump to the parameter
with the absolute index, otherwise jump forward in the argument list.
@item ~(
Case conversion begin. If prefixed by @code{:}, the following output
string will be capitalized, if prefixed by @code{@@}, the first
character will be capitalized, if prefixed by @code{:@@} it will be
upcased and otherwise it will be downcased. Conversion stops when the
``Case conversion end'' @code{~)}sequence is encountered.
@item ~)
Case conversion end. Stop any case conversion currently in effect.
@item ~[
@c FIXME::martin: I don't understand this from the source.
Conditional begin.
@item ~;
@c FIXME::martin: I don't understand this from the source.
Conditional separator.
@item ~]
@c FIXME::martin: I don't understand this from the source.
Conditional end.
@item ~@{
@c FIXME::martin: I don't understand this from the source.
Iteration begin.
@item ~@}
@c FIXME::martin: I don't understand this from the source.
Iteration end.
@item ~^
@c FIXME::martin: I don't understand this from the source.
Up and out.
@item ~'
@c FIXME::martin: I don't understand this from the source.
Character parameter.
@item ~0 @dots{} ~9, ~-, ~+
@c FIXME::martin: I don't understand this from the source.
Numeric parameter.
@item ~v
@c FIXME::martin: I don't understand this from the source.
Variable parameter from next argument.
@item ~#
Parameter is number of remaining args. The number of the remaining
arguments is prepended to the list of unprocessed arguments.
@item ~,
@c FIXME::martin: I don't understand this from the source.
Parameter separators.
@item ~q
Inquiry message. Insert a copyright message into the output.
@end table
If any type conversions should fail (for example when using an escape
sequence for number output, but the argument is a string), an error
will be signalled.
@end deffn
You may have noticed that Guile contains a @code{format} procedure
even when the module @code{(ice-9 format)} is not loaded. The default
@code{format} procedure does not support all escape sequences
documented in this chapter, and will signal an error if you try to use
one of them. The reason for providing two versions of @code{format}
is that the full-featured module is fairly large and requires some
time to get loaded. So the Guile maintainers decided not to load the
large version of @code{format} by default, so that the start-up time
of the interpreter is not unnecessarily increased.
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

532
doc/ref/new-docstrings.texi Normal file
View file

@ -0,0 +1,532 @@
@c module (guile)
@deffn primitive environment? obj
Return @code{#t} if @var{obj} is an environment, or @code{#f}
otherwise.
@end deffn
@deffn primitive environment-bound? env sym
Return @code{#t} if @var{sym} is bound in @var{env}, or
@code{#f} otherwise.
@end deffn
@deffn primitive environment-ref env sym
Return the value of the location bound to @var{sym} in
@var{env}. If @var{sym} is unbound in @var{env}, signal an
@code{environment:unbound} error.
@end deffn
@deffn primitive environment-fold env proc init
Iterate over all the bindings in @var{env}, accumulating some
value.
For each binding in @var{env}, apply @var{proc} to the symbol
bound, its value, and the result from the previous application
of @var{proc}.
Use @var{init} as @var{proc}'s third argument the first time
@var{proc} is applied.
If @var{env} contains no bindings, this function simply returns
@var{init}.
If @var{env} binds the symbol sym1 to the value val1, sym2 to
val2, and so on, then this procedure computes:
@lisp
(proc sym1 val1
(proc sym2 val2
...
(proc symn valn
init)))
@end lisp
Each binding in @var{env} will be processed exactly once.
@code{environment-fold} makes no guarantees about the order in
which the bindings are processed.
Here is a function which, given an environment, constructs an
association list representing that environment's bindings,
using environment-fold:
@lisp
(define (environment->alist env)
(environment-fold env
(lambda (sym val tail)
(cons (cons sym val) tail))
'()))
@end lisp
@end deffn
@deffn primitive environment-define env sym val
Bind @var{sym} to a new location containing @var{val} in
@var{env}. If @var{sym} is already bound to another location
in @var{env} and the binding is mutable, that binding is
replaced. The new binding and location are both mutable. The
return value is unspecified.
If @var{sym} is already bound in @var{env}, and the binding is
immutable, signal an @code{environment:immutable-binding} error.
@end deffn
@deffn primitive environment-undefine env sym
Remove any binding for @var{sym} from @var{env}. If @var{sym}
is unbound in @var{env}, do nothing. The return value is
unspecified.
If @var{sym} is already bound in @var{env}, and the binding is
immutable, signal an @code{environment:immutable-binding} error.
@end deffn
@deffn primitive environment-set! env sym val
If @var{env} binds @var{sym} to some location, change that
location's value to @var{val}. The return value is
unspecified.
If @var{sym} is not bound in @var{env}, signal an
@code{environment:unbound} error. If @var{env} binds @var{sym}
to an immutable location, signal an
@code{environment:immutable-location} error.
@end deffn
@deffn primitive environment-cell env sym for_write
Return the value cell which @var{env} binds to @var{sym}, or
@code{#f} if the binding does not live in a value cell.
The argument @var{for-write} indicates whether the caller
intends to modify the variable's value by mutating the value
cell. If the variable is immutable, then
@code{environment-cell} signals an
@code{environment:immutable-location} error.
If @var{sym} is unbound in @var{env}, signal an
@code{environment:unbound} error.
If you use this function, you should consider using
@code{environment-observe}, to be notified when @var{sym} gets
re-bound to a new value cell, or becomes undefined.
@end deffn
@deffn primitive environment-observe env proc
Whenever @var{env}'s bindings change, apply @var{proc} to
@var{env}.
This function returns an object, token, which you can pass to
@code{environment-unobserve} to remove @var{proc} from the set
of procedures observing @var{env}. The type and value of
token is unspecified.
@end deffn
@deffn primitive environment-observe-weak env proc
This function is the same as environment-observe, except that
the reference @var{env} retains to @var{proc} is a weak
reference. This means that, if there are no other live,
non-weak references to @var{proc}, it will be
garbage-collected, and dropped from @var{env}'s
list of observing procedures.
@end deffn
@deffn primitive environment-unobserve token
Cancel the observation request which returned the value
@var{token}. The return value is unspecified.
If a call @code{(environment-observe env proc)} returns
@var{token}, then the call @code{(environment-unobserve token)}
will cause @var{proc} to no longer be called when @var{env}'s
bindings change.
@end deffn
@deffn primitive make-leaf-environment
Create a new leaf environment, containing no bindings.
All bindings and locations created in the new environment
will be mutable.
@end deffn
@deffn primitive leaf-environment? object
Return @code{#t} if object is a leaf environment, or @code{#f}
otherwise.
@end deffn
@deffn primitive make-eval-environment local imported
Return a new environment object eval whose bindings are the
union of the bindings in the environments @var{local} and
@var{imported}, with bindings from @var{local} taking
precedence. Definitions made in eval are placed in @var{local}.
Applying @code{environment-define} or
@code{environment-undefine} to eval has the same effect as
applying the procedure to @var{local}.
Note that eval incorporates @var{local} and @var{imported} by
reference:
If, after creating eval, the program changes the bindings of
@var{local} or @var{imported}, those changes will be visible
in eval.
Since most Scheme evaluation takes place in eval environments,
they transparently cache the bindings received from @var{local}
and @var{imported}. Thus, the first time the program looks up
a symbol in eval, eval may make calls to @var{local} or
@var{imported} to find their bindings, but subsequent
references to that symbol will be as fast as references to
bindings in finite environments.
In typical use, @var{local} will be a finite environment, and
@var{imported} will be an import environment
@end deffn
@deffn primitive eval-environment? object
Return @code{#t} if object is an eval environment, or @code{#f}
otherwise.
@end deffn
@deffn primitive eval-environment-local env
Return the local environment of eval environment @var{env}.
@end deffn
@deffn primitive eval-environment-set-local! env local
Change @var{env}'s local environment to @var{local}.
@end deffn
@deffn primitive eval-environment-imported env
Return the imported environment of eval environment @var{env}.
@end deffn
@deffn primitive eval-environment-set-imported! env imported
Change @var{env}'s imported environment to @var{imported}.
@end deffn
@deffn primitive make-import-environment imports conflict_proc
Return a new environment @var{imp} whose bindings are the union
of the bindings from the environments in @var{imports};
@var{imports} must be a list of environments. That is,
@var{imp} binds a symbol to a location when some element of
@var{imports} does.
If two different elements of @var{imports} have a binding for
the same symbol, the @var{conflict-proc} is called with the
following parameters: the import environment, the symbol and
the list of the imported environments that bind the symbol.
If the @var{conflict-proc} returns an environment @var{env},
the conflict is considered as resolved and the binding from
@var{env} is used. If the @var{conflict-proc} returns some
non-environment object, the conflict is considered unresolved
and the symbol is treated as unspecified in the import
environment.
The checking for conflicts may be performed lazily, i. e. at
the moment when a value or binding for a certain symbol is
requested instead of the moment when the environment is
created or the bindings of the imports change.
All bindings in @var{imp} are immutable. If you apply
@code{environment-define} or @code{environment-undefine} to
@var{imp}, Guile will signal an
@code{environment:immutable-binding} error. However,
notice that the set of bindings in @var{imp} may still change,
if one of its imported environments changes.
@end deffn
@deffn primitive import-environment? object
Return @code{#t} if object is an import environment, or
@code{#f} otherwise.
@end deffn
@deffn primitive import-environment-imports env
Return the list of environments imported by the import
environment @var{env}.
@end deffn
@deffn primitive import-environment-set-imports! env imports
Change @var{env}'s list of imported environments to
@var{imports}, and check for conflicts.
@end deffn
@deffn primitive make-export-environment private signature
Return a new environment @var{exp} containing only those
bindings in private whose symbols are present in
@var{signature}. The @var{private} argument must be an
environment.
The environment @var{exp} binds symbol to location when
@var{env} does, and symbol is exported by @var{signature}.
@var{signature} is a list specifying which of the bindings in
@var{private} should be visible in @var{exp}. Each element of
@var{signature} should be a list of the form:
(symbol attribute ...)
where each attribute is one of the following:
@table @asis
@item the symbol @code{mutable-location}
@var{exp} should treat the
location bound to symbol as mutable. That is, @var{exp}
will pass calls to @code{environment-set!} or
@code{environment-cell} directly through to private.
@item the symbol @code{immutable-location}
@var{exp} should treat
the location bound to symbol as immutable. If the program
applies @code{environment-set!} to @var{exp} and symbol, or
calls @code{environment-cell} to obtain a writable value
cell, @code{environment-set!} will signal an
@code{environment:immutable-location} error. Note that, even
if an export environment treats a location as immutable, the
underlying environment may treat it as mutable, so its
value may change.
@end table
It is an error for an element of signature to specify both
@code{mutable-location} and @code{immutable-location}. If
neither is specified, @code{immutable-location} is assumed.
As a special case, if an element of signature is a lone
symbol @var{sym}, it is equivalent to an element of the form
@code{(sym)}.
All bindings in @var{exp} are immutable. If you apply
@code{environment-define} or @code{environment-undefine} to
@var{exp}, Guile will signal an
@code{environment:immutable-binding} error. However,
notice that the set of bindings in @var{exp} may still change,
if the bindings in private change.
@end deffn
@deffn primitive export-environment? object
Return @code{#t} if object is an export environment, or
@code{#f} otherwise.
@end deffn
@deffn primitive export-environment-private env
Return the private environment of export environment @var{env}.
@end deffn
@deffn primitive export-environment-set-private! env private
Change the private environment of export environment @var{env}.
@end deffn
@deffn primitive export-environment-signature env
Return the signature of export environment @var{env}.
@end deffn
@deffn primitive export-environment-set-signature! env signature
Change the signature of export environment @var{env}.
@end deffn
@deffn primitive %compute-slots class
Return a list consisting of the names of all slots belonging to
class @var{class}, i. e. the slots of @var{class} and of all of
its superclasses.
@end deffn
@deffn primitive get-keyword key l default_value
Determine an associated value for the keyword @var{key} from
the list @var{l}. The list @var{l} has to consist of an even
number of elements, where, starting with the first, every
second element is a keyword, followed by its associated value.
If @var{l} does not hold a value for @var{key}, the value
@var{default_value} is returned.
@end deffn
@deffn primitive slot-ref-using-class class obj slot_name
@end deffn
@deffn primitive slot-set-using-class! class obj slot_name value
@end deffn
@deffn primitive class-of x
Return the class of @var{x}.
@end deffn
@deffn primitive %goops-loaded
Announce that GOOPS is loaded and perform initialization
on the C level which depends on the loaded GOOPS modules.
@end deffn
@deffn primitive %method-more-specific? m1 m2 targs
@end deffn
@deffn primitive find-method . l
@end deffn
@deffn primitive primitive-generic-generic subr
@end deffn
@deffn primitive enable-primitive-generic! . subrs
@end deffn
@deffn primitive generic-capability? proc
@end deffn
@deffn primitive %invalidate-method-cache! gf
@end deffn
@deffn primitive %invalidate-class class
@end deffn
@deffn primitive %modify-class old new
@end deffn
@deffn primitive %modify-instance old new
@end deffn
@deffn primitive %set-object-setter! obj setter
@end deffn
@deffn primitive %allocate-instance class initargs
Create a new instance of class @var{class} and initialize it
from the arguments @var{initargs}.
@end deffn
@deffn primitive slot-exists? obj slot_name
Return @code{#t} if @var{obj} has a slot named @var{slot_name}.
@end deffn
@deffn primitive slot-bound? obj slot_name
Return @code{#t} if the slot named @var{slot_name} of @var{obj}
is bound.
@end deffn
@deffn primitive slot-set! obj slot_name value
Set the slot named @var{slot_name} of @var{obj} to @var{value}.
@end deffn
@deffn primitive slot-exists-using-class? class obj slot_name
@end deffn
@deffn primitive slot-bound-using-class? class obj slot_name
@end deffn
@deffn primitive %fast-slot-set! obj index value
Set the slot with index @var{index} in @var{obj} to
@var{value}.
@end deffn
@deffn primitive %fast-slot-ref obj index
Return the slot value with index @var{index} from @var{obj}.
@end deffn
@deffn primitive @@assert-bound-ref obj index
Like @code{assert-bound}, but use @var{index} for accessing
the value from @var{obj}.
@end deffn
@deffn primitive assert-bound value obj
Return @var{value} if it is bound, and invoke the
@var{slot-unbound} method of @var{obj} if it is not.
@end deffn
@deffn primitive unbound? obj
Return @code{#t} if @var{obj} is unbound.
@end deffn
@deffn primitive make-unbound
Return the unbound value.
@end deffn
@deffn primitive accessor-method-slot-definition obj
Return the slot definition of the accessor @var{obj}.
@end deffn
@deffn primitive method-procedure obj
Return the procedure of the method @var{obj}.
@end deffn
@deffn primitive method-specializers obj
Return specializers of the method @var{obj}.
@end deffn
@deffn primitive method-generic-function obj
Return the generic function fot the method @var{obj}.
@end deffn
@deffn primitive generic-function-methods obj
Return the methods of the generic function @var{obj}.
@end deffn
@deffn primitive generic-function-name obj
Return the name of the generic function @var{obj}.
@end deffn
@deffn primitive class-environment obj
Return the environment of the class @var{obj}.
@end deffn
@deffn primitive class-slots obj
Return the slot list of the class @var{obj}.
@end deffn
@deffn primitive class-precedence-list obj
Return the class precedence list of the class @var{obj}.
@end deffn
@deffn primitive class-direct-methods obj
Return the direct methods of the class @var{obj}
@end deffn
@deffn primitive class-direct-subclasses obj
Return the direct subclasses of the class @var{obj}.
@end deffn
@deffn primitive class-direct-slots obj
Return the direct slots of the class @var{obj}.
@end deffn
@deffn primitive class-direct-supers obj
Return the direct superclasses of the class @var{obj}.
@end deffn
@deffn primitive class-name obj
Return the class name of @var{obj}.
@end deffn
@deffn primitive instance? obj
Return @code{#t} if @var{obj} is an instance.
@end deffn
@deffn primitive %inherit-magic! class dsupers
@end deffn
@deffn primitive %prep-layout! class
@end deffn
@deffn primitive %initialize-object obj initargs
Initialize the object @var{obj} with the given arguments
@var{initargs}.
@end deffn
@deffn primitive make . args
Make a new object. @var{args} must contain the class and
all necessary initialization information.
@end deffn
@deffn primitive slot-ref obj slot_name
Return the value from @var{obj}'s slot with the name
@var{slot_name}.
@end deffn
@deffn primitive builtin-bindings
Create and return a copy of the global symbol table, removing all
unbound symbols.
@end deffn
@deffn primitive %tag-body body
Internal GOOPS magic---don't use this function!
@end deffn
@deffn primitive list*
scm_cons_star
@end deffn
@deffn primitive set-current-module module
Set the current module to @var{module} and return
the previous current module.
@end deffn
@deffn primitive current-module
Return the current module.
@end deffn
@deffn primitive c-clear-registered-modules
Destroy the list of modules registered with the current Guile process.
The return value is unspecified. @strong{Warning:} this function does
not actually unlink or deallocate these modules, but only destroys the
records of which modules have been loaded. It should therefore be used
only by module bookkeeping operations.
@end deffn
@deffn primitive c-registered-modules
Return a list of the object code modules that have been imported into
the current Guile process. Each element of the list is a pair whose
car is the name of the module, and whose cdr is the function handle
for that module's initializer function. The name is the string that
has been passed to scm_register_module_xxx.
@end deffn
@deffn primitive include-deprecated-features
Return @code{#t} iff deprecated features should be included
in public interfaces.
@end deffn
@deffn primitive issue-deprecation-warning . msgs
Output @var{msgs} to @code{(current-error-port)} when this
is the first call to @code{issue-deprecation-warning} with
this specific @var{msg}. Do nothing otherwise.
The argument @var{msgs} should be a list of strings;
they are printed in turn, each one followed by a newline.
@end deffn

2328
doc/ref/posix.texi Normal file

File diff suppressed because it is too large Load diff

182
doc/ref/preface.texi Normal file
View file

@ -0,0 +1,182 @@
@iftex
@page
@unnumbered Preface
This reference manual documents Guile, GNU's Ubiquitous Intelligent
Language for Extensions. It describes how to use Guile in many useful
and interesting ways.
This is edition 1.0 of the reference manual, and corresponds to Guile
version @value{VERSION}.
@end iftex
@iftex
@section The Guile License
@end iftex
@ifnottex
@node Guile License
@chapter The Guile License
@end ifnottex
The license of Guile consists of the GNU GPL plus a special statement
giving blanket permission to link with non-free software. This is the
license statement as found in any individual file that it applies to:
@quotation
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with this software; see the file COPYING. If not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
As a special exception, the Free Software Foundation gives permission
for additional uses of the text contained in its release of GUILE.
The exception is that, if you link the GUILE library with other files to
produce an executable, this does not by itself cause the resulting
executable to be covered by the GNU General Public License. Your use of
that executable is in no way restricted on account of linking the GUILE
library code into it.
This exception does not however invalidate any other reasons why the
executable file might be covered by the GNU General Public License.
This exception applies only to the code released by the Free Software
Foundation under the name GUILE. If you copy code from other Free
Software Foundation releases into a copy of GUILE, as the General Public
License permits, the exception does not apply to the code that you add
in this way. To avoid misleading anyone as to the status of such
modified files, you must delete this exception notice from them.
If you write modifications of your own for GUILE, it is your choice
whether to permit this exception to apply to your modifications. If you
do not wish that, delete this exception notice.
@end quotation
@iftex
@section Layout of this Manual
@end iftex
@ifnottex
@node Manual Layout
@chapter Layout of this Manual
@end ifnottex
This manual is divided into five parts.
@strong{Part I: Introduction to Guile} provides an overview of what
Guile is and how you can use it. A whirlwind tour shows how Guile can
be used interactively and as a script interpreter, how to link Guile
into your own applications, and how to write modules of interpreted and
compiled code for use with Guile. All of the ideas introduced here are
documented in full by the later parts of the manual.
@strong{Part II: Guile Scheme} documents the core Scheme language and
features that Guile implements. Although the basis for this is the
Scheme language described in R5RS, this part of the manual does not
assume any prior familiarity with R5RS in particular, or with Scheme in
general. Basic Scheme concepts, standard aspects of the Scheme language
and Guile extensions on top of R5RS are all documented from scratch, and
organized by functionality rather than by the defining standards.
@strong{Part III: Guile Modules} describes some important modules,
distributed as part of the Guile distribution, that extend the
functionality provided by the Guile Scheme core, most notably:
@itemize @bullet
@item
the POSIX module, which provides Scheme level procedures for system and
network programming, conforming to the POSIX standard
@item
the SLIB module, which makes Aubrey Jaffer's portable Scheme library
available for use in Guile.
@end itemize
@strong{Part IV: Guile Scripting} documents the use of Guile as a script
interpreter, and illustrates this with a series of examples.
@strong{Part V: Extending Applications Using Guile} explains the options
available for using Guile as a application extension language. At the
simpler end of the scale, an application might use Guile to define some
application-specific primitives in C and then load an application Scheme
file. In this case most of the application code is written on the
Scheme level, and uses the application-specific primitives as an
extension to standard Scheme. At the other end of the scale, an
application might be predominantly written in C --- with its main
control loop implemented in C --- but make occasional forays into Scheme
to, say, read configuration data or run user-defined customization code.
This part of the manual covers the complete range of application
extension options.
Finally, the appendices explain how to obtain the latest version of
Guile, how to install it, where to find modules to work with Guile, and
how to use the Guile debugger.
@iftex
@section Manual Conventions
@end iftex
@ifnottex
@node Manual Conventions
@chapter Conventions used in this Manual
@end ifnottex
We use some conventions in this manual.
@itemize @bullet
@item
For some procedures, notably type predicates, we use @dfn{iff} to
mean `if and only if'. The construct is usually something like:
`Return @var{val} iff @var{condition}', where @var{val} is usually
`@code{#t}' or `non-@code{#f}'. This typically means that @var{val}
is returned if @var{condition} holds, and that @samp{#f} is returned
otherwise.
@cindex iff
@item
In examples and procedure descriptions and all other places where the
evaluation of Scheme expression is shown, we use some notation for
denoting the output and evaluation results of expressions.
The symbol @code{@result{}} is used to tell which value is returned by
an evaluation:
@lisp
(+ 1 2)
@result{}
3
@end lisp
Some procedures produce some output besides returning a value. This
is denoted by the symbol @code{@print{}}.
@lisp
(begin (display 1) (newline) 'hooray)
@print{} 1
@result{}
hooray
@end lisp
@c Add other conventions here.
@end itemize
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

131
doc/ref/repl-modules.texi Normal file
View file

@ -0,0 +1,131 @@
@page
@node Readline Support
@chapter Readline Support
@c FIXME::martin: Review me!
@cindex readline
@cindex command line history
Guile comes with an interface module to the readline library. This
makes interactive use much more convenient, because of the command-line
editing features of readline. Using @code{(ice-9 readline)}, you can
navigate through the current input line with the cursor keys, retrieve
older command lines from the input history and even search through the
history entries.
@menu
* Loading Readline Support:: How to load readline support into Guile.
* Readline Options:: How to modify readline's behaviour.
@end menu
@node Loading Readline Support
@section Loading Readline Support
The module is not loaded by default and so has to be loaded and
activated explicitly. This is done with two simple lines of code:
@lisp
(use-modules (ice-9 readline))
(activate-readline)
@end lisp
@c FIXME::martin: Review me!
The first line will load the necessary code, and the second will
activate readline's features for the REPL. If you plan to use this
module often, you should save these to lines to your @file{.guile}
personal startup file.
You will notice that the REPL's behaviour changes a bit when you have
loaded the readline module. For examle, when you press Enter before
typing in the closing parentheses of a list, you will see the
@dfn{continuation} prompt, three dots: @code{...} This gives you a nice
visual feedback when trying to match parentheses. To make this even
easier, @dfn{bouncing parentheses} are implemented. That means that
when you type in a closing parentheses, the cursor will jump to the
corresponding opening paren for a short time, making it trivial to make
them match.
Once the readline module is activated, all lines entered interactively
will be stored in a history and can be recalled later using the
cursor-up and -down keys. Readline also understands the Emacs keys for
navigating through the command line and history.
When you quit your Guile session by evaluating @code{(quit)} or pressing
Ctrl-D, the history will be saved to the file @file{.guile_history} and
read in when you start Guile for the next time. Thus you can start a
new Guile session and still have the (probably long-winded) definition
expressions available.
@node Readline Options
@section Readline Options
@c FIXME::martin: Review me!
@cindex readline options
The readline interface module can be configured in several ways to
better suit the user's needs. Configuration is done via the readline
module's options interface, in a similar way to the evaluator and
debugging options (@pxref{General option interface}.)
Here is the list of readline options generated by typing
@code{(readline-options 'full)} in Guile. You can also see the
default values.
@smalllisp
bounce-parens 500 Time (ms) to show matching opening parenthesis (0 = off).
history-length 200 History length.
history-file yes Use history file.
@end smalllisp
The history length specifies how many input lines will be remembered.
If the history contains that many lines and additional lines are
entered, the oldest lines will be lost. You can switch on/off the
usage of the history file using the following call.
@lisp
(readline-disable 'history)
@end lisp
The readline options interface can only be used @emph{after} loading
the readline module, because it is defined in that module.
@page
@node Value History
@chapter Value History
@c FIXME::martin: Review me!
@cindex value history
Another module which makes command line usage more convenient is
@code{(ice-9 history)}. This module will change the REPL so that each
value which is evaluated and printed will be remembered under a name
constructed from the dollar character (@code{$}) and the number of the
evaluated expression.
Consider an example session.
@example
guile> (use-modules (ice-9 history))
guile> 1
$1 = 1
guile> (+ $1 $1)
$2 = 2
guile> (* $2 $2)
$3 = 4
@end example
After loading the value history module @code{(ice-9 history)}, one
(trivial) expression is evaluated. The result is stored into the
variable @code{$1}. This fact is indicated by the output @code{$1 = },
which is also caused by @code{(ice-9 history)}. In the next line, this
variable is used two times, to produce the value @code{$2}, which in
turn is used in the calculation for @code{$3}.
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

242
doc/ref/scheme-binding.texi Normal file
View file

@ -0,0 +1,242 @@
@page
@node Binding Constructs
@chapter Definitions and Variable Bindings
@c FIXME::martin: Review me!
Scheme supports the definition of variables in different contexts.
Variables can be defined at the top level, so that they are visible in
the entire program, and variables can be defined locally to procedures
and expressions. This is important for modularity and data abstraction.
@menu
* Top Level:: Top level variable definitions.
* Local Bindings:: Local variable bindings.
* Internal Definitions:: Internal definitions.
* Binding Reflection:: Querying variable bindings.
@end menu
@node Top Level
@section Top Level Variable Definitions
@c FIXME::martin: Review me!
@cindex variable definition
On the top level of a program (e.g. when not inside of a procedure
definition or a @code{let}, @code{let*} or @code{letrec} expression), a
definition of the form
@lisp
(define a 1)
@end lisp
@noindent
defines a variable called @var{a} and sets it to the value 1. When the
variable already was bound with a @code{define} expression, the above
form is completely equivalent to
@lisp
(set! a 1)
@end lisp
@noindent
that means that @code{define} can be used interchangeably with
@code{set!} when at the top level of the REPL or a Scheme source file.
But note that a @code{set!} is not allowed if the variable was not bound
before.
Attention: definitions inside local binding constructs (@pxref{Local
Bindings}) act differently (@pxref{Internal Definitions}).
@node Local Bindings
@section Local Variable Bindings
@c FIXME::martin: Review me!
@cindex local bindings
@cindex local variables
As opposed to definitions at the top level, which are visible in the
whole program (or current module, when Guile modules are used), it is
also possible to define variables which are only visible in a
well-defined part of the program. Normally, this part of a program
will be a procedure or a subexpression of a procedure.
With the constructs for local binding (@code{let}, @code{let*} and
@code{letrec}), the Scheme language has a block structure like most
other programming languages since the days of @sc{Algol 60}. Readers
familiar to languages like C or Java should already be used to this
concept, but the family of @code{let} expressions has a few properties
which are well worth knowing.
The first local binding construct is @code{let}. The other constructs
@code{let*} and @code{letrec} are specialized versions for usage where
using plain @code{let} is a bit inconvenient.
@deffn syntax let bindings body
@var{bindings} has the form
@lisp
((@var{variable1} @var{init1}) @dots{})
@end lisp
that is zero or more two-element lists of a variable and an arbitrary
expression each. All @var{variable} names must be distinct.
A @code{let} expression is evaluated as follows.
@itemize @bullet
@item
All @var{init} expressions are evaluated.
@item
New storage is allocated for the @var{variables}.
@item
The values of the @var{init} expressions are stored into the variables.
@item
The expressions in @var{body} are evaluated in order, and the value of
the last expression is returned as the value of the @code{let}
expression.
@item
The storage for the @var{variables} is freed.
@end itemize
The @var{init} expressions are not allowed to refer to any of the
@var{variables}.
@end deffn
@deffn syntax let* bindings body
Similar to @code{let}, but the variable bindings are performed
sequentially, that means that all @var{init} expression are allowed to
use the variables defined on their left in the binding list.
A @code{let*} expression can always be expressed with nested @code{let}
expressions.
@lisp
(let* ((a 1) (b a))
b)
@equiv{}
(let ((a 1))
(let ((b a))
b))
@end lisp
@end deffn
@deffn syntax letrec bindings body
Similar to @code{let}, but it is possible to refer to the @var{variable}
from lambda expression created in any of the @var{inits}. That is,
procedures created in the @var{init} expression can recursively refer to
the defined variables.
@lisp
(letrec ((even?
(lambda (n)
(if (zero? n)
#t
(odd? (- n 1)))))
(odd?
(lambda (n)
(if (zero? n)
#f
(even? (- n 1))))))
(even? 88))
@result{}
#t
@end lisp
@end deffn
There is also an alternative form of the @code{let} form, which is used
for expressing iteration. Because of the use as a looping construct,
this form (the @dfn{named let}) is documented in the section about
iteration (@pxref{while do, Iteration})
@node Internal Definitions
@section Internal definitions
@c FIXME::martin: Review me!
A @code{define} form which appears inside the body of a @code{lambda},
@code{let}, @code{let*}, @code{letrec} or equivalent expression is
called an @dfn{internal definition}. An internal definition differs
from a top level definition (@pxref{Top Level}), because the definition
is only visible inside the complete body of the enclosing form. Let us
examine the following example.
@lisp
(let ((frumble "froz"))
(define banana (lambda () (apple 'peach)))
(define apple (lambda (x) x))
(banana))
@result{}
peach
@end lisp
Here the enclosing form is a @code{let}, so the @code{define}s in the
@code{let}-body are internal definitions. Because the scope of the
internal definitions is the @strong{complete} body of the
@code{let}-expression, the @code{lambda}-expression which gets bound
to the variable @code{banana} may refer to the variable @code{apple},
even thogh it's definition appears lexically @emph{after} the definition
of @code{banana}. This is because a sequence of internal definition
acts as if it were a @code{letrec} expression.
@lisp
(let ()
(define a 1)
(define b 2)
(+ a b))
@end lisp
@noindent
is equivalent to
@lisp
(let ()
(letrec ((a 1) (b 2))
(+ a b)))
@end lisp
Another noteworthy difference to top level definitions is that within
one group of internal definitions all variable names must be distinct.
That means where on the top level a second define for a given variable
acts like a @code{set!}, an exception is thrown for internal definitions
with duplicate bindings.
@c FIXME::martin: The following is required by R5RS, but Guile does not
@c signal an error. Document it anyway, saying that Guile is sloppy?
@c Internal definitions are only allowed at the beginning of the body of an
@c enclosing expression. They may not be mixed with other expressions.
@c @lisp
@c (let ()
@c (define a 1)
@c a
@c (define b 2)
@c b)
@c @end lisp
@node Binding Reflection
@section Querying variable bindings
Guile provides a procedure for checking wehther a symbol is bound in the
top level environment. If you want to test whether a symbol is locally
bound in expression, you can use the @code{bound?} macro from the module
@code{(ice-9 optargs)}, documented in @ref{Optional Arguments}.
@c NJFIXME explain [env]
@deffn primitive defined? sym [env]
Return @code{#t} if @var{sym} is defined in the top-level environment.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

823
doc/ref/scheme-control.texi Normal file
View file

@ -0,0 +1,823 @@
@page
@node Control Mechanisms
@chapter Controlling the Flow of Program Execution
@menu
* begin:: Evaluating a sequence of expressions.
* if cond case:: Simple conditional evaluation.
* and or:: Conditional evaluation of a sequence.
* while do:: Iteration mechanisms.
* Continuations:: Continuations.
* Multiple Values:: Returning and accepting multiple values.
* Exceptions:: Throwing and catching exceptions.
* Error Reporting:: Procedures for signaling errors.
* Dynamic Wind:: Guarding against non-local entrance/exit.
@end menu
@node begin
@section Evaluating a Sequence of Expressions
@c FIXME::martin: Review me!
@c FIXME::martin: Maybe add examples?
@cindex begin
@cindex sequencing
@cindex expression sequencing
@code{begin} is used for grouping several expression together so that
they syntactically are treated as if they were one expression. This is
particularly important when syntactic expressions are used which only
allow one expression, but the programmer wants to use more than one
expression in that place. As an example, consider the conditional
expression below:
@lisp
(if (> x 0)
(begin (display "greater") (newline)))
@end lisp
If the two calls to @code{display} and @code{newline} were not embedded
in a @code{begin}-statement, the call to @code{newline} would get
misinterpreted as the else-branch of the @code{if}-expression.
@deffn syntax begin expr1 expr2 @dots{}
The expression(s) are evaluated in left-to-right order and the value
of the last expression is returned as the value of the
@code{begin}-expression. This expression type is used when the
expressions before the last one are evaluated for their side effects.
@end deffn
@node if cond case
@section Simple Conditional Evaluation
@c FIXME::martin: Review me!
@c FIXME::martin: Maybe add examples?
@cindex conditional evaluation
@cindex if
@cindex case
@cindex cond
Guile provides three syntactic constructs for conditional evaluation.
@code{if} is the normal if-then-else expression (with an optional else
branch), @code{cond} is a conditional expression with multiple branches
and @code{case} branches if an expression has one of a set of constant
values.
@deffn syntax if test consequent [alternate]
All arguments may be arbitrary expressions. First, @var{test} is
evaluated. If it returns a true value, the expression @var{consequent}
is evaluated and @var{alternate} is ignoret. If @var{test} evaluates to
@code{#f}, @var{alternate} is evaluated instead. The value of the
evaluated branch (@var{consequent} or @var{alternate}) is returned as
the value of the @code{if} expression.
When @var{alternate} is omitted and the @var{test} evaluates to
@code{#f}, the value of the expression is not specified.
@end deffn
@deffn syntax cond clause1 clause2 @dots{}
Each @code{cond}-clause must look like this:
@lisp
(@var{test} @var{expression} @dots{})
@end lisp
where @var{test} and @var{expression} are arbitrary expression, or like
this
@lisp
(@var{test} => @var{expression}
@end lisp
where @var{expression} must evaluate to a procedure.
The @var{test}s of the clauses are evaluated in order and as soon as one
of them evaluates to a true values, the corresponding @var{expression}s
are evaluated in order and the last value is returned as the value of
the @code{cond}-expression. For the @code{=>} clause type,
@var{expression} is evaluated and the resulting procedure is applied to
the value of @var{test}. The result of this procedure application is
then the result of the @code{cond}-expression.
The @var{test} of the last @var{clause} may be the keyword @code{else}.
Then, if none of the preceding @var{test}s is true, the @var{expression}s following the @code{else} are evaluated to produce the result of the @code{cond}-expression.
@end deffn
@deffn syntax case key clause1 clause2 @dots{}
@var{key} may be any expression, the @var{clause}s must have the form
@lisp
((@var{datum1} @dots{}) @var{expr1} @var{expr2} @dots{})
@end lisp
and the last @var{clause} may have the form
@lisp
(else @var{expr1} @var{expr2} @dots{})
@end lisp
All @var{datum}s must be distinct. First, @var{key} is evaluated. The
the result of this evaluation is compared against all @var{datum}s using
@code{eqv?}. When this comparison succeeds, the epression(s) following
the @var{datum} are evaluated from left to right, returning the value of
the last expression as the result of the @code{case} expression.
If the @var{key} matches no @var{datum} and there is an
@code{else}-clause, the expressions following the @code{else} are
evaluated. If there is no such clause, the result of the expression is
unspecified.
@end deffn
@node and or
@section Conditional Evaluation of a Sequence of Expressions
@c FIXME::martin: Review me!
@c FIXME::martin: Maybe add examples?
@code{and} and @code{or} evaluate all their arguments, similar to
@code{begin}, but evaluation stops as soon as one of the expressions
evaluates to false or true, respectively.
@deffn syntax and expr @dots{}
Evaluate the @var{expr}s from left to right and stop evaluation as soon
as one expression evaluates to @code{#f}; the remaining expressions are
not evaluated. The value of the last evaluated expression is returned.
If no expression evaluates to @code{#f}, the value of the last
expression is returned.
If used without expressions, @code{#t} is returned.
@end deffn
@deffn syntax or expr @dots{}
Evaluate the @var{expr}s from left to right and stop evaluation as soon
as one expression evaluates to a true value (that is, a value different
from @code{#f}); the remaining expressions are not evaluated. The value
of the last evaluated expression is returned. If all expressions
evaluate to @code{#f}, @code{#f} is returned.
If used without expressions, @code{#f} is returned.
@end deffn
@node while do
@section Iteration mechanisms
@c FIXME::martin: Review me!
@c FIXME::martin: Maybe add examples?
@cindex iteration
@cindex looping
@cindex named let
Scheme has only few iteration mechanisms, mainly because iteration in
Scheme programs is normally expressed using recursion. Nevertheless,
R5RS defines a construct for programming loops, calling @code{do}. In
addition, Guile has an explicit looping syntax called @code{while}.
@deffn syntax do ((variable1 init1 step1) @dots{}) (test expr @dots{}) command @dots{}
The @var{init} expressions are evaluated and the @var{variables} are
bound to their values. Then looping starts with testing the @var{test}
expression. If @var{test} evaluates to a true value, the @var{expr}
following the @var{test} are evaluated and the value of the last
@var{expr} is returned as the value of the @code{do} expression. If
@var{test} evaluates to false, the @var{command}s are evaluated in
order, the @var{step}s are evaluated and stored into the @var{variables}
and the next iteration starts.
Any of the @var{step} expressions may be omitted, so that the
corresponding variable is not changed during looping.
@end deffn
@deffn syntax while cond body @dots{}
Evaluate all expressions in @var{body} in order, as long as @var{cond}
evaluates to a true value. The @var{cond} expression is tested before
every iteration, so that the body is not evaluated at all if @var{cond}
is @code{#f} right from the start.
@end deffn
@cindex named let
Another very common way of expressing iteration in Scheme programs is
the use of the so-called @dfn{named let}.
Named let is a variant of @code{let} which creates a procedure and calls
it in one step. Because of the newly created procedure, named let is
more powerful than @code{do}--it can be used for iteration, but also
for arbitrary recursion.
@deffn syntax let variable bindings body
For the definition of @var{bindings} see the documentation about
@code{let} (@pxref{Local Bindings}).
Named @code{let} works as follows:
@itemize @bullet
@item
A new procedure which accepts as many arguments as are in @var{bindings}
is created and bound locally (using @code{let}) to @var{variable}. The
new procedure's formal argument names are the name of the
@var{variables}.
@item
The @var{body} expressions are inserted into the newly created procedure.
@item
The procedure is called with the @var{init} expressions as the formal
arguments.
@end itemize
The next example implements a loop which iterates (by recursion) 1000
times.
@lisp
(let lp ((x 1000))
(if (positive? x)
(lp (- x 1))
x))
@result{}
0
@end lisp
@end deffn
@node Continuations
@section Continuations
@cindex call/cc
@cindex call-with-current-continuation
The ability to explicitly capture continuations using
@code{call-with-current-continuation} (also often called @code{call/cc}
for short), and to invoke such continuations later any number of times,
and from any other point in a program, provides maybe the most powerful
control structure known. All other control structures, such as loops
and coroutines, can be emulated using continuations.
@c NJFIXME - need a little something here about what continuations are
@c and what they do for you.
The implementation of continuations in Guile is not as efficient as one
might hope, because it is constrained by the fact that Guile is designed
to cooperate with programs written in other languages, such as C, which
do not know about continuations. So continuations should be used when
there is no other simple way of achieving the desired behaviour, or
where the advantages of the elegant continuation mechanism outweigh the
need for optimum performance. If you find yourself using @code{call/cc}
for escape procedures and your program is running too slow, you might
want to use exceptions (@pxref{Exceptions}) instead.
@rnindex call-with-current-continuation
@deffn primitive call-with-current-continuation proc
Capture the current continuation and call @var{proc} with the captured
continuation as the single argument. This continuation can then be
called with arbitrarily many arguments. Such a call will work like a
goto to the invocation location of
@code{call-with-current-continuation}, passing the arguments in a way
that they are returned by the call to
@code{call-with-current-continuation}. Since it is legal to store the
captured continuation in a variable or to pass it to other procedures,
it is possible that a procedure returns more than once, even if it is
called only one time. This can be confusing at times.
@end deffn
@c FIXME::martin: Better example needed.
@lisp
(define kont #f)
(call-with-current-continuation
(lambda (k)
(set! kont k)
1))
@result{}
1
(kont 2)
@result{}
2
@end lisp
@node Multiple Values
@section Returning and Accepting Multiple Values
@c FIXME::martin: Review me!
@cindex multiple values
@cindex receive
Scheme allows a procedure to return more than one value to its caller.
This is quite different to other languages which only allow
single-value returns. Returning multiple values is different from
returning a list (or pair or vector) of values to the caller, because
conceptionally not @emph{one} compound object is returned, but several
distinct values.
The primitive procedures for handling multiple values are @code{values}
and @code{call-with-values}. @code{values} is used for returning
multiple values from a procedure. This is done by placing a call to
@code{values} with zero or more arguments in tail position in a
procedure body. @code{call-with-values} combines a procedure returning
multiple values with a procedure which accepts these values as
parameters.
@rnindex values
@deffn primitive values expr @dots{}
Delivers all of its arguments to its continuation. Except for
continuations created by the @code{call-with-values} procedure,
all continuations take exactly one value. The effect of
passing no value or more than one value to continuations that
were not created by @code{call-with-values} is unspecified.
@end deffn
@rnindex call-with-values
@deffn primitive call-with-values producer consumer
Calls its @var{producer} argument with no values and a
continuation that, when passed some values, calls the
@var{consumer} procedure with those values as arguments. The
continuation for the call to @var{consumer} is the continuation
of the call to @code{call-with-values}.
@example
(call-with-values (lambda () (values 4 5))
(lambda (a b) b))
==> 5
@end example
@example
(call-with-values * -) ==> -1
@end example
@end deffn
In addition to the fundamental procedures described above, Guile has a
module which exports a syntax called @code{receive}, which is much more
convenient. If you want to use it in your programs, you have to load
the module @code{(ice-9 receive)} with the statement
@lisp
(use-modules (ice-9 receive))
@end lisp
@deffn {library syntax} receive formals expr body @dots{}
Evaluate the expression @var{expr}, and bind the result values (zero or
more) to the formal arguments in the formal argument list @var{formals}.
@var{formals} must have the same syntax like the formal argument list
used in @code{lambda} (@pxref{Lambda}). After binding the variables,
the expressions in @var{body} @dots{} are evaluated in order.
@end deffn
@node Exceptions
@section Exceptions
@cindex error handling
@cindex exception handling
A common requirement in applications is to want to jump
@dfn{non-locally} from the depths of a computation back to, say, the
application's main processing loop. Usually, the place that is the
target of the jump is somewhere in the calling stack of procedures that
called the procedure that wants to jump back. For example, typical
logic for a key press driven application might look something like this:
@example
main-loop:
read the next key press and call dispatch-key
dispatch-key:
lookup the key in a keymap and call an appropriate procedure,
say find-file
find-file:
interactively read the required file name, then call
find-specified-file
find-specified-file:
check whether file exists; if not, jump back to main-loop
@dots{}
@end example
The jump back to @code{main-loop} could be achieved by returning through
the stack one procedure at a time, using the return value of each
procedure to indicate the error condition, but Guile (like most modern
programming languages) provides an additional mechanism called
@dfn{exception handling} that can be used to implement such jumps much
more conveniently.
@menu
* Exception Terminology:: Different ways to say the same thing.
* Catch:: Setting up to catch exceptions.
* Throw:: Throwing an exception.
* Lazy Catch:: Catch without unwinding the stack.
* Exception Implementation:: How Guile implements exceptions.
@end menu
@node Exception Terminology
@subsection Exception Terminology
There are several variations on the terminology for dealing with
non-local jumps. It is useful to be aware of them, and to realize
that they all refer to the same basic mechanism.
@itemize @bullet
@item
Actually making a non-local jump may be called @dfn{raising an
exception}, @dfn{raising a signal}, @dfn{throwing an exception} or
@dfn{doing a long jump}. When the jump indicates an error condition,
people may talk about @dfn{signalling}, @dfn{raising} or @dfn{throwing}
@dfn{an error}.
@item
Handling the jump at its target may be referred to as @dfn{catching} or
@dfn{handling} the @dfn{exception}, @dfn{signal} or, where an error
condition is involved, @dfn{error}.
@end itemize
Where @dfn{signal} and @dfn{signalling} are used, special care is needed
to avoid the risk of confusion with POSIX signals. (Especially
considering that Guile handles POSIX signals by throwing a corresponding
kind of exception: REFFIXME.)
This manual prefers to speak of throwing and catching exceptions, since
this terminology matches the corresponding Guile primitives.
@node Catch
@subsection Catching Exceptions
@code{catch} is used to set up a target for a possible non-local jump.
The arguments of a @code{catch} expression are a @dfn{key}, which
restricts the set of exceptions to which this @code{catch} applies, a
thunk that specifies the @dfn{normal case} code --- i.e. what should
happen if no exceptions are thrown --- and a @dfn{handler} procedure
that says what to do if an exception is thrown. Note that if the
@dfn{normal case} thunk executes @dfn{normally}, which means without
throwing any exceptions, the handler procedure is not executed at all.
When an exception is thrown using the @code{throw} primitive, the first
argument of the @code{throw} is a symbol that indicates the type of the
exception. For example, Guile throws an exception using the symbol
@code{numerical-overflow} to indicate numerical overflow errors such as
division by zero:
@lisp
(/ 1 0)
@result{}
ABORT: (numerical-overflow)
@end lisp
The @var{key} argument in a @code{catch} expression corresponds to this
symbol. @var{key} may be a specific symbol, such as
@code{numerical-overflow}, in which case the @code{catch} applies
specifically to exceptions of that type; or it may be @code{#t}, which
means that the @code{catch} applies to all exceptions, irrespective of
their type.
The second argument of a @code{catch} expression should be a thunk
(i.e. a procedure that accepts no arguments) that specifies the normal
case code. The @code{catch} is active for the execution of this thunk,
including any code called directly or indirectly by the thunk's body.
Evaluation of the @code{catch} expression activates the catch and then
calls this thunk.
The third argument of a @code{catch} expression is a handler procedure.
If an exception is thrown, this procedure is called with exactly the
arguments specified by the @code{throw}. Therefore, the handler
procedure must be designed to accept a number of arguments that
corresponds to the number of arguments in all @code{throw} expressions
that can be caught by this @code{catch}.
@deffn primitive catch key thunk handler
Invoke @var{thunk} in the dynamic context of @var{handler} for
exceptions matching @var{key}. If thunk throws to the symbol
@var{key}, then @var{handler} is invoked this way:
@lisp
(handler key args ...)
@end lisp
@var{key} is a symbol or @code{#t}.
@var{thunk} takes no arguments. If @var{thunk} returns
normally, that is the return value of @code{catch}.
Handler is invoked outside the scope of its own @code{catch}.
If @var{handler} again throws to the same key, a new handler
from further up the call chain is invoked.
If the key is @code{#t}, then a throw to @emph{any} symbol will
match this call to @code{catch}.
@end deffn
If the handler procedure needs to match a variety of @code{throw}
expressions with varying numbers of arguments, you should write it like
this:
@lisp
(lambda (key . args)
@dots{})
@end lisp
@noindent
The @var{key} argument is guaranteed always to be present, because a
@code{throw} without a @var{key} is not valid. The number and
interpretation of the @var{args} varies from one type of exception to
another, but should be specified by the documentation for each exception
type.
Note that, once the handler procedure is invoked, the catch that led to
the handler procedure being called is no longer active. Therefore, if
the handler procedure itself throws an exception, that exception can
only be caught by another active catch higher up the call stack, if
there is one.
@node Throw
@subsection Throwing Exceptions
The @code{throw} primitive is used to throw an exception. One argument,
the @var{key}, is mandatory, and must be a symbol; it indicates the type
of exception that is being thrown. Following the @var{key},
@code{throw} accepts any number of additional arguments, whose meaning
depends on the exception type. The documentation for each possible type
of exception should specify the additional arguments that are expected
for that kind of exception.
@deffn primitive throw key . args
Invoke the catch form matching @var{key}, passing @var{args} to the
@var{handler}.
@var{key} is a symbol. It will match catches of the same symbol or of
@code{#t}.
If there is no handler at all, Guile prints an error and then exits.
@end deffn
When an exception is thrown, it will be caught by the innermost
@code{catch} expression that applies to the type of the thrown
exception; in other words, the innermost @code{catch} whose @var{key} is
@code{#t} or is the same symbol as that used in the @code{throw}
expression. Once Guile has identified the appropriate @code{catch}, it
handles the exception by applying that @code{catch} expression's handler
procedure to the arguments of the @code{throw}.
If there is no appropriate @code{catch} for a thrown exception, Guile
prints an error to the current error port indicating an uncaught
exception, and then exits. In practice, it is quite difficult to
observe this behaviour, because Guile when used interactively installs a
top level @code{catch} handler that will catch all exceptions and print
an appropriate error message @emph{without} exiting. For example, this
is what happens if you try to throw an unhandled exception in the
standard Guile REPL; note that Guile's command loop continues after the
error message:
@lisp
guile> (throw 'badex)
<unnamed port>:3:1: In procedure gsubr-apply @dots{}
<unnamed port>:3:1: unhandled-exception: badex
ABORT: (misc-error)
guile>
@end lisp
The default uncaught exception behaviour can be observed by evaluating a
@code{throw} expression from the shell command line:
@example
$ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
guile: uncaught throw to badex: ()
$
@end example
@noindent
That Guile exits immediately following the uncaught exception
is shown by the absence of any output from the @code{display}
expression, because Guile never gets to the point of evaluating that
expression.
@node Lazy Catch
@subsection Catch Without Unwinding
A @dfn{lazy catch} is used in the same way as a normal @code{catch},
with @var{key}, @var{thunk} and @var{handler} arguments specifying the
exception type, normal case code and handler procedure, but differs in
one important respect: the handler procedure is executed without
unwinding the call stack from the context of the @code{throw} expression
that caused the handler to be invoked.
@deffn primitive lazy-catch key thunk handler
This behaves exactly like @code{catch}, except that it does
not unwind the stack before invoking @var{handler}.
The @var{handler} procedure is not allowed to return:
it must throw to another catch, or otherwise exit non-locally.
@end deffn
Typically, @var{handler} should save any desired state associated with
the stack at the point where the corresponding @code{throw} occurred,
and then throw an exception itself --- usually the same exception as the
one it caught. If @var{handler} is invoked and does @emph{not} throw an
exception, Guile itself throws an exception with key @code{misc-error}.
Not unwinding the stack means that throwing an exception that is caught
by a @code{lazy-catch} is @emph{almost} equivalent to calling the
@code{lazy-catch}'s handler inline instead of each @code{throw}, and
then omitting the surrounding @code{lazy-catch}. In other words,
@lisp
(lazy-catch 'key
(lambda () @dots{} (throw 'key args @dots{}) @dots{})
handler)
@end lisp
@noindent
is @emph{almost} equivalent to
@lisp
((lambda () @dots{} (handler 'key args @dots{}) @dots{}))
@end lisp
@noindent
But why only @emph{almost}? The difference is that with
@code{lazy-catch} (as with normal @code{catch}), the dynamic context is
unwound back to just outside the @code{lazy-catch} expression before
invoking the handler. (For an introduction to what is meant by dynamic
context, @xref{Dynamic Wind}.)
Then, when the handler @emph{itself} throws an exception, that exception
must be caught by some kind of @code{catch} (including perhaps another
@code{lazy-catch}) higher up the call stack.
The dynamic context also includes @code{with-fluids} blocks (REFFIXME),
so the effect of unwinding the dynamic context can also be seen in fluid
variable values. This is illustrated by the following code, in which
the normal case thunk uses @code{with-fluids} to temporarily change the
value of a fluid:
@lisp
(define f (make-fluid))
(fluid-set! f "top level value")
(define (handler . args)
(cons (fluid-ref f) args))
(lazy-catch 'foo
(lambda ()
(with-fluids ((f "local value"))
(throw 'foo)))
handler)
@result{}
("top level value" foo)
((lambda ()
(with-fluids ((f "local value"))
(handler 'foo))))
@result{}
("local value" foo)
@end lisp
@noindent
In the @code{lazy-catch} version, the unwinding of dynamic context
restores @code{f} to its value outside the @code{with-fluids} block
before the handler is invoked, so the handler's @code{(fluid-ref f)}
returns the external value.
@code{lazy-catch} is useful because it permits the implementation of
debuggers and other reflective programming tools that need to access the
state of the call stack at the exact point where an exception or an
error is thrown. For an example of this, see REFFIXME:stack-catch.
@node Exception Implementation
@subsection How Guile Implements Exceptions
It is traditional in Scheme to implement exception systems using
@code{call-with-current-continuation}. Continuations
(@pxref{Continuations}) are such a powerful concept that any other
control mechanism --- including @code{catch} and @code{throw} --- can be
implemented in terms of them.
Guile does not implement @code{catch} and @code{throw} like this,
though. Why not? Because Guile is specifically designed to be easy to
integrate with applications written in C. In a mixed Scheme/C
environment, the concept of @dfn{continuation} must logically include
``what happens next'' in the C parts of the application as well as the
Scheme parts, and it turns out that the only reasonable way of
implementing continuations like this is to save and restore the complete
C stack.
So Guile's implementation of @code{call-with-current-continuation} is a
stack copying one. This allows it to interact well with ordinary C
code, but means that creating and calling a continuation is slowed down
by the time that it takes to copy the C stack.
The more targeted mechanism provided by @code{catch} and @code{throw}
does not need to save and restore the C stack because the @code{throw}
always jumps to a location higher up the stack of the code that executes
the @code{throw}. Therefore Guile implements the @code{catch} and
@code{throw} primitives independently of
@code{call-with-current-continuation}, in a way that takes advantage of
this @emph{upwards only} nature of exceptions.
@node Error Reporting
@section Procedures for Signaling Errors
Guile provides a set of convenience procedures for signaling error
conditions that are implemented on top of the exception primitives just
described.
@deffn procedure error msg args @dots{}
Raise an error with key @code{misc-error} and a message constructed by
displaying @var{msg} and writing @var{args}.
@end deffn
@deffn primitive scm-error key subr message args data
Raise an error with key @var{key}. @var{subr} can be a string
naming the procedure associated with the error, or @code{#f}.
@var{message} is the error message string, possibly containing
@code{~S} and @code{~A} escapes. When an error is reported,
these are replaced by formatting the corresponding members of
@var{args}: @code{~A} (was @code{%s} in older versions of
Guile) formats using @code{display} and @code{~S} (was
@code{%S}) formats using @code{write}. @var{data} is a list or
@code{#f} depending on @var{key}: if @var{key} is
@code{system-error} then it should be a list containing the
Unix @code{errno} value; If @var{key} is @code{signal} then it
should be a list containing the Unix signal number; otherwise
it will usually be @code{#f}.
@end deffn
@deffn primitive strerror err
Return the Unix error message corresponding to @var{err}, which
must be an integer value.
@end deffn
@c begin (scm-doc-string "boot-9.scm" "false-if-exception")
@deffn syntax false-if-exception expr
Returns the result of evaluating its argument; however
if an exception occurs then @code{#f} is returned instead.
@end deffn
@c end
@node Dynamic Wind
@section Dynamic Wind
[FIXME: this is pasted in from Tom Lord's original guile.texi and should
be reviewed]
@rnindex dynamic-wind
@deffn primitive dynamic-wind in_guard thunk out_guard
All three arguments must be 0-argument procedures.
@var{in_guard} is called, then @var{thunk}, then
@var{out_guard}.
If, any time during the execution of @var{thunk}, the
continuation of the @code{dynamic_wind} expression is escaped
non-locally, @var{out_guard} is called. If the continuation of
the dynamic-wind is re-entered, @var{in_guard} is called. Thus
@var{in_guard} and @var{out_guard} may be called any number of
times.
@lisp
(define x 'normal-binding)
@result{} x
(define a-cont (call-with-current-continuation
(lambda (escape)
(let ((old-x x))
(dynamic-wind
;; in-guard:
;;
(lambda () (set! x 'special-binding))
;; thunk
;;
(lambda () (display x) (newline)
(call-with-current-continuation escape)
(display x) (newline)
x)
;; out-guard:
;;
(lambda () (set! x old-x)))))))
;; Prints:
special-binding
;; Evaluates to:
@result{} a-cont
x
@result{} normal-binding
(a-cont #f)
;; Prints:
special-binding
;; Evaluates to:
@result{} a-cont ;; the value of the (define a-cont...)
x
@result{} normal-binding
a-cont
@result{} special-binding
@end lisp
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

5230
doc/ref/scheme-data.texi Executable file

File diff suppressed because it is too large Load diff

187
doc/ref/scheme-debug.texi Normal file
View file

@ -0,0 +1,187 @@
@page
@node Debugging
@chapter Internal Debugging Interface
--- The name of this chapter needs to clearly distinguish it
from the appendix describing the debugger UI. The intro
should have a pointer to the UI appendix.
@deffn primitive display-error stack port subr message args rest
Display an error message to the output port @var{port}.
@var{stack} is the saved stack for the error, @var{subr} is
the name of the procedure in which the error occured and
@var{message} is the actual error message, which may contain
formatting instructions. These will format the arguments in
the list @var{args} accordingly. @var{rest} is currently
ignored.
@end deffn
@deffn primitive display-application frame [port [indent]]
Display a procedure application @var{frame} to the output port
@var{port}. @var{indent} specifies the indentation of the
output.
@end deffn
@deffn primitive display-backtrace stack port [first [depth]]
Display a backtrace to the output port @var{port}. @var{stack}
is the stack to take the backtrace from, @var{first} specifies
where in the stack to start and @var{depth} how much frames
to display. Both @var{first} and @var{depth} can be @code{#f},
which means that default values will be used.
@end deffn
@deffn primitive backtrace
Display a backtrace of the stack saved by the last error
to the current output port.
@end deffn
@deffn primitive malloc-stats
Return an alist ((@var{what} . @var{n}) ...) describing number
of malloced objects.
@var{what} is the second argument to @code{scm_must_malloc},
@var{n} is the number of objects of that type currently
allocated.
@end deffn
@deffn primitive debug-options-interface [setting]
Option interface for the debug options. Instead of using
this procedure directly, use the procedures @code{debug-enable},
@code{debug-disable}, @code{debug-set!} and @var{debug-options}.
@end deffn
@deffn primitive with-traps thunk
Call @var{thunk} with traps enabled.
@end deffn
@deffn primitive memoized? obj
Return @code{#t} if @var{obj} is memoized.
@end deffn
@deffn primitive unmemoize m
Unmemoize the memoized expression @var{m},
@end deffn
@deffn primitive memoized-environment m
Return the environment of the memoized expression @var{m}.
@end deffn
@deffn primitive procedure-name proc
Return the name of the procedure @var{proc}
@end deffn
@deffn primitive procedure-source proc
Return the source of the procedure @var{proc}.
@end deffn
@deffn primitive procedure-environment proc
Return the environment of the procedure @var{proc}.
@end deffn
@deffn primitive debug-object? obj
Return @code{#t} if @var{obj} is a debug object.
@end deffn
@deffn primitive frame-arguments frame
Return the arguments of @var{frame}.
@end deffn
@deffn primitive frame-evaluating-args? frame
Return @code{#t} if @var{frame} contains evaluated arguments.
@end deffn
@deffn primitive frame-next frame
Return the next frame of @var{frame}, or @code{#f} if
@var{frame} is the last frame in its stack.
@end deffn
@deffn primitive frame-number frame
Return the frame number of @var{frame}.
@end deffn
@deffn primitive frame-overflow? frame
Return @code{#t} if @var{frame} is an overflow frame.
@end deffn
@deffn primitive frame-previous frame
Return the previous frame of @var{frame}, or @code{#f} if
@var{frame} is the first frame in its stack.
@end deffn
@deffn primitive frame-procedure frame
Return the procedure for @var{frame}, or @code{#f} if no
procedure is associated with @var{frame}.
@end deffn
@deffn primitive frame-procedure? frame
Return @code{#t} if a procedure is associated with @var{frame}.
@end deffn
@deffn primitive frame-real? frame
Return @code{#t} if @var{frame} is a real frame.
@end deffn
@deffn primitive frame-source frame
Return the source of @var{frame}.
@end deffn
@deffn primitive frame? obj
Return @code{#t} if @var{obj} is a stack frame.
@end deffn
@deffn primitive last-stack-frame obj
Return a stack which consists of a single frame, which is the
last stack frame for @var{obj}. @var{obj} must be either a
debug object or a continuation.
@end deffn
@deffn primitive make-stack obj . args
Create a new stack. If @var{obj} is @code{#t}, the current
evaluation stack is used for creating the stack frames,
otherwise the frames are taken from @var{obj} (which must be
either a debug object or a continuation).
@var{args} should be a list containing any combination of
integer, procedure and @code{#t} values.
These values specify various ways of cutting away uninteresting
stack frames from the top and bottom of the stack that
@code{make-stack} returns. They come in pairs like this:
@code{(@var{inner_cut_1} @var{outer_cut_1} @var{inner_cut_2}
@var{outer_cut_2} @dots{})}.
Each @var{inner_cut_N} can be @code{#t}, an integer, or a
procedure. @code{#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 @var{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 @var{outer_cut_N} of the last pair is missing, it is
taken as 0.
@end deffn
@deffn primitive stack-id stack
Return the identifier given to @var{stack} by @code{start-stack}.
@end deffn
@deffn primitive stack-length stack
Return the length of @var{stack}.
@end deffn
@deffn primitive stack-ref stack i
Return the @var{i}'th frame from @var{stack}.
@end deffn
@deffn primitive stack? obj
Return @code{#t} if @var{obj} is a calling stack.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

View file

@ -0,0 +1,419 @@
@page
@node Read/Load/Eval
@chapter 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.
@end menu
@node Scheme Syntax
@section Scheme Syntax: Standard and Guile Extensions
@menu
* Expression Syntax::
* Comments::
* Block Comments::
* Case Sensitivity::
* Keyword Syntax::
* Reader Extensions::
@end menu
@node Expression Syntax
@subsection Expression Syntax
@node Comments
@subsection Comments
@c FIXME::martin: Review me!
Comments in Scheme source files are written by starting them with a
semicolon character (@code{;}). 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.
@lisp
; Comment
;; Comment too
(define x 1) ; Comment after expression
(let ((y 1))
;; Display something.
(display y)
;;; Comment at left margin.
(display (+ y 1)))
@end lisp
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.
@node Block Comments
@subsection Block Comments
@c FIXME::martin: Review me!
@cindex multiline comments
In addition to the standard line comments defined by R5RS, Guile has
another comment type for multiline comments, called @dfn{block
comments}. This type of comment begins with the character sequence
@code{#!} and ends with the characters @code{!#}, which must appear on a
line of their own. These comments are compatible with the block
comments in the Scheme Shell @file{scsh} (@pxref{The Scheme shell
(scsh)}). The characters @code{#!} 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.
@lisp
#! /usr/local/bin/guile -s
!#
@end lisp
More details on Guile scripting can be found in the scripting section
(@pxref{Guile Scripting}).
@node Case Sensitivity
@subsection Case Sensitivity
@c FIXME::martin: Review me!
Scheme as defined in R5RS is not case sensitive when reading symbols.
Guile, on the contrary is case sensitive by default, so the identifiers
@lisp
guile-whuzzy
Guile-Whuzzy
@end lisp
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 @code{case-insensitive}. More on reader options can be
found at (@pxref{Reader options}).
@lisp
(read-enable 'case-insensitive)
@end lisp
Note that this is seldom a problem, because Scheme programmers tend not
to use uppercase letters in their identifiers anyway.
@node Keyword Syntax
@subsection Keyword Syntax
@node Reader Extensions
@subsection Reader Extensions
@deffn primitive read-hash-extend chr proc
Install the procedure @var{proc} for reading expressions
starting with the character sequence @code{#} and @var{chr}.
@var{proc} will be called with two arguments: the character
@var{chr} and the port to read further data from. The object
returned will be the return value of @code{read}.
@end deffn
@node Scheme Read
@section Reading Scheme Code
@rnindex read
@deffn primitive read [port]
Read an s-expression from the input port @var{port}, or from
the current input port if @var{port} is not specified.
Any whitespace before the next token is discarded.
@end deffn
The behaviour of Guile's Scheme reader can be modified by manipulating
its read options. For more information about options, @xref{General
option interface}. If you want to know which reader options are
available, @xref{Reader options}.
@c FIXME::martin: This is taken from libguile/options.c. Is there
@c actually a difference between 'help and 'full?
@deffn procedure read-options [setting]
Display the current settings of the read options. If @var{setting} is
omitted, only a short form of the current read options is printed.
Otherwise, @var{setting} should be one of the following symbols:
@table @code
@item help
Display the complete option settings.
@item full
Like @code{help}, but also print programmer options.
@end table
@end deffn
@deffn procedure read-enable option-name
@deffnx procedure read-disable option-name
@deffnx procedure read-set! option-name value
Modify the read options. @code{read-enable} should be used with boolean
options and switches them on, @code{read-disable} switches them off.
@code{read-set!} can be used to set an option to a specific value.
@end deffn
@deffn primitive read-options-interface [setting]
Option interface for the read options. Instead of using
this procedure directly, use the procedures @code{read-enable},
@code{read-disable}, @code{read-set!} and @code{read-options}.
@end deffn
@node Fly Evaluation
@section Procedures for On the Fly Evaluation
@rnindex eval
@c ARGFIXME environment/environment specifier
@deffn primitive eval exp environment
Evaluate @var{exp}, a list representing a Scheme expression, in the
environment given by @var{environment specifier}.
@end deffn
@rnindex interaction-environment
@deffn primitive 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.
@end deffn
@deffn primitive eval-string string
Evaluate @var{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 @code{interaction-environment}.
@end deffn
@deffn primitive apply:nconc2last lst
Given a list (@var{arg1} @dots{} @var{args}), this function
conses the @var{arg1} @dots{} arguments onto the front of
@var{args}, and returns the resulting list. Note that
@var{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, @code{apply:nconc2last}
destroys its argument, so use with care.
@end deffn
@rnindex apply
@deffn primitive apply proc arg1 @dots{} args
@var{proc} must be a procedure and @var{args} must be a list. Call
@var{proc} with the elements of the list @code{(append (list @var{arg1}
@dots{}) @var{args})} as the actual arguments.
@end deffn
@deffn primitive primitive-eval exp
Evaluate @var{exp} in the top-level environment specified by
the current module.
@end deffn
@deffn primitive eval2 obj env_thunk
Evaluate @var{exp}, a Scheme expression, in the environment
designated by @var{lookup}, a symbol-lookup function.
Do not use this version of eval, it does not play well
with the module system. Use @code{eval} or
@code{primitive-eval} instead.
@end deffn
@deffn primitive read-and-eval! [port]
Read a form from @var{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 @var{port}, an @code{end-of-file} error is
signalled.
@end deffn
@node Loading
@section Loading Scheme Code from File
@rnindex load
@deffn procedure load filename
Load @var{filename} and evaluate its contents in the top-level
environment. The load paths are not searched. If the variable
@code{%load-hook} is defined, it should be bound to a procedure that
will be called before any code is loaded. See documentation for
@code{%load-hook} later in this section.
@end deffn
@deffn procedure load-from-path filename
Similar to @code{load}, but searches for @var{filename} in the load
paths.
@end deffn
@deffn primitive primitive-load filename
Load the file named @var{filename} and evaluate its contents in
the top-level environment. The load paths are not searched;
@var{filename} must either be a full pathname or be a pathname
relative to the current directory. If the variable
@code{%load-hook} is defined, it should be bound to a procedure
that will be called before any code is loaded. See the
documentation for @code{%load-hook} later in this section.
@end deffn
@deffn primitive primitive-load-path filename
Search @var{%load-path} for the file named @var{filename} and
load it into the top-level environment. If @var{filename} is a
relative pathname and is not found in the list of search paths,
an error is signalled.
@end deffn
@deffn primitive %search-load-path filename
Search @var{%load-path} for the file named @var{filename},
which must be readable by the current user. If @var{filename}
is found in the list of paths to search or is an absolute
pathname, return its full pathname. Otherwise, return
@code{#f}. Filenames may have any of the optional extensions
in the @code{%load-extensions} list; @code{%search-load-path}
will try each extension automatically.
@end deffn
@defvar %load-hook
A procedure to be run whenever @code{primitive-load} is called. If this
procedure is defined, it will be called with the filename argument that
was passed to @code{primitive-load}.
@example
(define %load-hook (lambda (file)
(display "Loading ")
(display file)
(write-line "...."))) @result{} undefined
(load-from-path "foo.scm")
@print{} Loading /usr/local/share/guile/site/foo.scm....
@end example
@end defvar
@deffn primitive current-load-port
Return the current-load-port.
The load port is used internally by @code{primitive-load}.
@end deffn
@defvar %load-extensions
A list of default file extensions for files containing Scheme code.
@code{%search-load-path} tries each of these extensions when looking for
a file to load. By default, @code{%load-extensions} is bound to the
list @code{("" ".scm")}.
@end defvar
@node Delayed Evaluation
@section Delayed Evaluation
[delay]
@deffn primitive promise? obj
Return true if @var{obj} is a promise, i.e. a delayed computation
(@pxref{Delayed evaluation,,,r5rs.info,The Revised^5 Report on Scheme}).
@end deffn
@rnindex force
@deffn primitive force x
If the promise @var{x} has not been computed yet, compute and
return @var{x}, otherwise just return the previously computed
value.
@end deffn
@node Local Evaluation
@section Local Evaluation
[the-environment]
@deffn primitive local-eval exp [env]
Evaluate @var{exp} in its environment. If @var{env} is supplied,
it is the environment in which to evaluate @var{exp}. Otherwise,
@var{exp} must be a memoized code object (in which case, its environment
is implicit).
@end deffn
@node Evaluator Behaviour
@section Evaluator Behaviour
@c FIXME::martin: Maybe this node name is bad, but the old name clashed with
@c `Evaluator options' under `Options and Config'.
The behaviour of Guile's evaluator can be modified by manipulating the
evaluator options. For more information about options, @xref{General
option interface}. If you want to know which evaluator options are
available, @xref{Evaluator options}.
@c FIXME::martin: This is taken from libguile/options.c. Is there
@c actually a difference between 'help and 'full?
@deffn procedure eval-options [setting]
Display the current settings of the evaluator options. If @var{setting}
is omitted, only a short form of the current evaluator options is
printed. Otherwise, @var{setting} should be one of the following
symbols:
@table @code
@item help
Display the complete option settings.
@item full
Like @code{help}, but also print programmer options.
@end table
@end deffn
@deffn procedure eval-enable option-name
@deffnx procedure eval-disable option-name
@deffnx procedure eval-set! option-name value
Modify the evaluator options. @code{eval-enable} should be used with boolean
options and switches them on, @code{eval-disable} switches them off.
@code{eval-set!} can be used to set an option to a specific value.
@end deffn
@deffn primitive eval-options-interface [setting]
Option interface for the evaluation options. Instead of using
this procedure directly, use the procedures @code{eval-enable},
@code{eval-disable}, @code{eval-set!} and @code{eval-options}.
@end deffn
@c FIXME::martin: Why aren't these procedure named like the other options
@c procedures?
@deffn procedure traps [setting]
Display the current settings of the evaluator traps options. If
@var{setting} is omitted, only a short form of the current evaluator
traps options is printed. Otherwise, @var{setting} should be one of the
following symbols:
@table @code
@item help
Display the complete option settings.
@item full
Like @code{help}, but also print programmer options.
@end table
@end deffn
@deffn procedure trap-enable option-name
@deffnx procedure trap-disable option-name
@deffnx procedure trap-set! option-name value
Modify the evaluator options. @code{trap-enable} should be used with boolean
options and switches them on, @code{trap-disable} switches them off.
@code{trap-set!} can be used to set an option to a specific value.
@end deffn
@deffn primitive evaluator-traps-interface [setting]
Option interface for the evaluator trap options.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

1458
doc/ref/scheme-ideas.texi Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,17 @@
@page
@node R5RS Index
@chapter R5RS Index
@printindex rn
@page
@node Guile Extensions Index
@chapter Guile Extensions Index
@printindex ge
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

55
doc/ref/scheme-intro.texi Normal file
View file

@ -0,0 +1,55 @@
@page
@node Scheme Intro
@chapter Introduction to Guile Scheme
Guile's core language is Scheme, which is specified and described in the
series of reports known as @dfn{RnRS}. @dfn{RnRS} is shorthand for the
@iftex
@dfn{Revised$^n$ Report on the Algorithmic Language Scheme}.
@end iftex
@ifnottex
@dfn{Revised^n Report on the Algorithmic Language Scheme}.
@end ifnottex
The current latest revision of RnRS is version 5
(@pxref{Top,R5RS,,r5rs}), and Guile 1.4 is fully compliant with the
Scheme specification in this revision.
But Guile, like most Scheme implementations, also goes beyond R5RS in
many ways, because R5RS does not give specifications (or even
recommendations) regarding many issues that are important in practical
programming. Some of the areas where Guile extends R5RS are:
@itemize @bullet
@item
Guile's interactive documentation system
@item
Guile's support for POSIX-compliant network programming
@item
GOOPS -- Guile's framework for object oriented programming.
@end itemize
@menu
* Scheme Layout:: The layout of this part of the manual.
@end menu
@node Scheme Layout
@section Layout
This part of the reference manual documents all of Guile's core
Scheme-level language and features in functionally-related groups.
Where a particular section of the manual includes both R5RS-compliant
parts and Guile-specific extensions, the text indicates which parts of
the documentation describe R5RS behaviour and which parts describe Guile
extensions.
For a breakdown of Guile's core language and features in terms of what
is R5RS-compliant and what is Guile-specific, see the corresponding
indices: @ref{R5RS Index} and @ref{Guile Extensions Index}.
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

826
doc/ref/scheme-io.texi Normal file
View file

@ -0,0 +1,826 @@
@page
@node Input and Output
@chapter Input and Output
@menu
* Ports:: The idea of the port abstraction.
* Reading:: Procedures for reading from a port.
* Writing:: Procedures for writing to a port.
* Closing:: Procedures to close a port.
* Random Access:: Moving around a random access port.
* Line/Delimited:: Read and write lines or delimited text.
* Block Reading and Writing:: Reading and writing blocks of text.
* Default Ports:: Defaults for input, output and errors.
* Port Types:: Types of port and how to make them.
@end menu
@node Ports
@section Ports
[Concept of the port abstraction.]
Sequential input/output in Scheme is represented by operations on a
@dfn{port}. Characters can be read from an input port and
written to an output port. This chapter explains the operations
that Guile provides for working with ports.
The formal definition of a port is very generic: an input port is
simply ``an object which can deliver characters on command,'' and
an output port is ``an object which can accept characters.''
Because this definition is so loose, it is easy to write functions
that simulate ports in software. @dfn{Soft ports} and @dfn{string
ports} are two interesting and powerful examples of this technique.
@rnindex input-port?
@deffn primitive input-port? x
Return @code{#t} if @var{x} is an input port, otherwise return
@code{#f}. Any object satisfying this predicate also satisfies
@code{port?}.
@end deffn
@rnindex output-port?
@deffn primitive output-port? x
Return @code{#t} if @var{x} is an output port, otherwise return
@code{#f}. Any object satisfying this predicate also satisfies
@code{port?}.
@end deffn
@deffn primitive port? x
Return a boolean indicating whether @var{x} is a port.
Equivalent to @code{(or (input-port? @var{x}) (output-port?
@var{x}))}.
@end deffn
@node Reading
@section Reading
[Generic procedures for reading from ports.]
@rnindex eof-object?
@deffn primitive eof-object? x
Return @code{#t} if @var{x} is an end-of-file object; otherwise
return @code{#f}.
@end deffn
@rnindex char-ready?
@deffn primitive char-ready? [port]
Return @code{#t} if a character is ready on input @var{port}
and return @code{#f} otherwise. If @code{char-ready?} returns
@code{#t} then the next @code{read-char} operation on
@var{port} is guaranteed not to hang. If @var{port} is a file
port at end of file then @code{char-ready?} returns @code{#t}.
@footnote{@code{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 @code{char-ready?} cannot be rubbed out.
If @code{char-ready?} were to return @code{#f} at end of file,
a port at end of file would be indistinguishable from an
interactive port that has no ready characters.}
@end deffn
@rnindex read-char?
@deffn primitive read-char [port]
Return the next character available from @var{port}, updating
@var{port} to point to the following character. If no more
characters are available, the end-of-file object is returned.
@end deffn
@rnindex peek-char?
@deffn primitive peek-char [port]
Return the next character available from @var{port},
@emph{without} updating @var{port} to point to the following
character. If no more characters are available, the
end-of-file object is returned.@footnote{The value returned by
a call to @code{peek-char} is the same as the value that would
have been returned by a call to @code{read-char} on the same
port. The only difference is that the very next call to
@code{read-char} or @code{peek-char} on that @var{port} will
return the value returned by the preceding call to
@code{peek-char}. In particular, a call to @code{peek-char} on
an interactive port will hang waiting for input whenever a call
to @code{read-char} would have hung.}
@end deffn
@deffn primitive unread-char cobj port
Place @var{char} in @var{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 @var{port} is
not supplied, the current input port is used.
@end deffn
@deffn primitive unread-string str port
Place the string @var{str} in @var{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
@var{port} is not supplied, the current-input-port is used.
@end deffn
@deffn primitive drain-input port
Drain @var{port}'s read buffers (including any pushed-back
characters) and return the content as a single string.
@end deffn
@deffn primitive port-column port
@deffnx primitive port-line port
Return the current column number or line number of @var{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.)
@end deffn
@deffn primitive set-port-column! port column
@deffnx primitive set-port-line! port line
Set the current column or line number of @var{port}, using the
current input port if none is specified.
@end deffn
@node Writing
@section Writing
[Generic procedures for writing to ports.]
@deffn primitive get-print-state port
Return the print state of the port @var{port}. If @var{port}
has no associated print state, @code{#f} is returned.
@end deffn
@rnindex newline
@deffn primitive newline [port]
Send a newline to @var{port}.
@end deffn
@deffn primitive port-with-print-state port pstate
Create a new port which behaves like @var{port}, but with an
included print state @var{pstate}.
@end deffn
@deffn primitive print-options-interface [setting]
Option interface for the print options. Instead of using
this procedure directly, use the procedures
@code{print-enable}, @code{print-disable}, @code{print-set!}
and @code{print-options}.
@end deffn
@deffn primitive simple-format destination message . args
Write @var{message} to @var{destination}, defaulting to
the current output port.
@var{message} can contain @code{~A} (was @code{%s}) and
@code{~S} (was @code{%S}) escapes. When printed,
the escapes are replaced with corresponding members of
@var{ARGS}:
@code{~A} formats using @code{display} and @code{~S} formats
using @code{write}.
If @var{destination} is @code{#t}, then use the current output
port, if @var{destination} is @code{#f}, then return a string
containing the formatted text. Does not add a trailing newline.
@end deffn
@rnindex write-char
@deffn primitive write-char chr [port]
Send character @var{chr} to @var{port}.
@end deffn
@findex fflush
@deffn primitive force-output [port]
Flush the specified output port, or the current output port if @var{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.
@end deffn
@deffn primitive flush-all-ports
Equivalent to calling @code{force-output} on
all open output ports. The return value is unspecified.
@end deffn
@node Closing
@section Closing
@deffn primitive close-port port
Close the specified port object. Return @code{#t} if it
successfully closes a port or @code{#f} if it was already
closed. An exception may be raised if an error occurs, for
example when flushing buffered output. See also @ref{Ports and
File Descriptors, close}, for a procedure which can close file
descriptors.
@end deffn
@rnindex close-input-port
@deffn primitive 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 @ref{Ports and File Descriptors, close}, for a procedure
which can close file descriptors.
@end deffn
@rnindex close-output-port
@deffn primitive 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 @ref{Ports and File Descriptors, close}, for a procedure
which can close file descriptors.
@end deffn
@deffn primitive port-closed? port
Return @code{#t} if @var{port} is closed or @code{#f} if it is
open.
@end deffn
@node Random Access
@section Random Access
@deffn primitive seek fd_port offset whence
Sets the current position of @var{fd/port} to the integer
@var{offset}, which is interpreted according to the value of
@var{whence}.
One of the following variables should be supplied for
@var{whence}:
@defvar SEEK_SET
Seek from the beginning of the file.
@end defvar
@defvar SEEK_CUR
Seek from the current position.
@end defvar
@defvar SEEK_END
Seek from the end of the file.
@end defvar
If @var{fd/port} is a file descriptor, the underlying system
call is @code{lseek}. @var{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:
@lisp
(seek port 0 SEEK_CUR)
@end lisp
@end deffn
@deffn primitive ftell fd_port
Return an integer representing the current position of
@var{fd/port}, measured from the beginning. Equivalent to:
@lisp
(seek port 0 SEEK_CUR)
@end lisp
@end deffn
@findex truncate
@findex ftruncate
@deffn primitive truncate-file object [length]
Truncates the object referred to by @var{object} to at most
@var{length} bytes. @var{object} can be a string containing a
file name or an integer file descriptor or a port.
@var{length} may be omitted if @var{object} is not a file name,
in which case the truncation occurs at the current port.
position. The return value is unspecified.
@end deffn
@node Line/Delimited
@section Line Oriented and Delimited Text
The delimited-I/O module can be accessed with:
@smalllisp
(use-modules (ice-9 rdelim))
@end smalllisp
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 @code{(scsh rdelim)}
module from guile-scsh, but does not use multiple values or character
sets and has an extra procedure @code{write-line}.
@c begin (scm-doc-string "rdelim.scm" "read-line")
@deffn procedure read-line [port] [handle-delim]
Return a line of text from @var{port} if specified, otherwise from the
value returned by @code{(current-input-port)}. Under Unix, a line of text
is terminated by the first end-of-line character or by end-of-file.
If @var{handle-delim} is specified, it should be one of the following
symbols:
@table @code
@item 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.
@item concat
Append the terminating delimiter (if any) to the returned string.
@item peek
Push the terminating delimiter (if any) back on to the port.
@item split
Return a pair containing the string read from the port and the
terminating delimiter or end-of-file object.
@end table
@end deffn
@c begin (scm-doc-string "rdelim.scm" "read-line!")
@deffn procedure read-line! buf [port]
Read a line of text into the supplied string @var{buf} and return the
number of characters added to @var{buf}. If @var{buf} is filled, then
@code{#f} is returned.
Read from @var{port} if
specified, otherwise from the value returned by @code{(current-input-port)}.
@end deffn
@c begin (scm-doc-string "rdelim.scm" "read-delimited")
@deffn procedure read-delimited delims [port] [handle-delim]
Read text until one of the characters in the string @var{delims} is found
or end-of-file is reached. Read from @var{port} if supplied, otherwise
from the value returned by @code{(current-input-port)}.
@var{handle-delim} takes the same values as described for @code{read-line}.
@end deffn
@c begin (scm-doc-string "rdelim.scm" "read-delimited!")
@deffn procedure read-delimited! delims buf [port] [handle-delim] [start] [end]
Read text into the supplied string @var{buf} and return the number of
characters added to @var{buf} (subject to @var{handle-delim}, which takes
the same values specified for @code{read-line}. If @var{buf} is filled,
@code{#f} is returned for both the number of characters read and the
delimiter. Also terminates if one of the characters in the string
@var{delims} is found
or end-of-file is reached. Read from @var{port} if supplied, otherwise
from the value returned by @code{(current-input-port)}.
@end deffn
@deffn primitive write-line obj [port]
Display @var{obj} and a newline character to @var{port}. If
@var{port} is not specified, @code{(current-output-port)} is
used. This function is equivalent to:
@lisp
(display obj [port])
(newline [port])
@end lisp
@end deffn
Some of the abovementioned I/O functions rely on the following C
primitives. These will mainly be of interest to people hacking Guile
internals.
@deffn primitive %read-delimited! delims str gobble [port [start [end]]]
Read characters from @var{port} into @var{str} until one of the
characters in the @var{delims} string is encountered. If
@var{gobble} is true, discard the delimiter character;
otherwise, leave it in the input stream for the next read. If
@var{port} is not specified, use the value of
@code{(current-input-port)}. If @var{start} or @var{end} are
specified, store data only into the substring of @var{str}
bounded by @var{start} and @var{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
@var{eof-object}; if the string was filled without encountering
a delimiter, this value is @code{#f}.
@end deffn
@deffn primitive %read-line [port]
Read a newline-terminated line from @var{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 @var{eof-object}; if
@code{%read-line} is called at the end of file, it returns the pair
@code{(#<eof> . #<eof>)}.
@end deffn
@node Block Reading and Writing
@section Block reading and writing
The Block-string-I/O module can be accessed with:
@smalllisp
(use-modules (ice-9 rw))
@end smalllisp
It currently contains procedures that help to implement the
@code{(scsh rw)} module in guile-scsh.
@deffn primitive read-string!/partial str [port_or_fdes start end]
Read characters from a port or file descriptor into a
string @var{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:
@itemize
@item
attempt to fill the entire string, unless the @var{start}
and/or @var{end} arguments are supplied. i.e., @var{start}
defaults to 0 and @var{end} defaults to
@code{(string-length str)}
@item
use the current input port if @var{port_or_fdes} is not
supplied.
@item
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.
@item
wait indefinitely for some input if no characters are
currently available,
unless the port is in non-blocking mode.
@item
read characters from the port's input buffers if available,
instead from the underlying file descriptor.
@item
return @code{#f} if end-of-file is encountered before reading
any characters, otherwise return the number of characters
read.
@item
return 0 if the port is in non-blocking mode and no characters
are immediately available.
@item
return 0 if the request is for 0 bytes, with no
end-of-file check.
@end itemize
@end deffn
@deffn primitive write-string/partial str [port_or_fdes start end]
Write characters from a string @var{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:
@itemize
@item
attempt to write the entire string, unless the @var{start}
and/or @var{end} arguments are supplied. i.e., @var{start}
defaults to 0 and @var{end} defaults to
@code{(string-length str)}
@item
use the current output port if @var{port_of_fdes} is not
supplied.
@item
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
@code{EAGAIN} system-error exception will be raised (Note:
scsh does not support the use of non-blocking buffered ports.)
@item
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.
@item
wait indefinitely for at least one character
from @var{str} to be accepted by the port, unless the port is
in non-blocking mode.
@item
return the number of characters accepted by the port.
@item
return 0 if the port is in non-blocking mode and can not accept
at least one character from @var{str} immediately
@item
return 0 immediately if the request size is 0 bytes.
@end itemize
@end deffn
@node Default Ports
@section Default Ports for Input, Output and Errors
@rnindex current-input-port
@deffn primitive current-input-port
Return the current input port. This is the default port used
by many input procedures. Initially, @code{current-input-port}
returns the @dfn{standard input} in Unix and C terminology.
@end deffn
@rnindex current-output-port
@deffn primitive current-output-port
Return the current output port. This is the default port used
by many output procedures. Initially,
@code{current-output-port} returns the @dfn{standard output} in
Unix and C terminology.
@end deffn
@deffn primitive current-error-port
Return the port to which errors and warnings should be sent (the
@dfn{standard error} in Unix and C terminology).
@end deffn
@deffn primitive set-current-input-port port
@deffnx primitive set-current-output-port port
@deffnx primitive set-current-error-port port
Change the ports returned by @code{current-input-port},
@code{current-output-port} and @code{current-error-port}, respectively,
so that they use the supplied @var{port} for input or output.
@end deffn
@deffn primitive set-current-output-port port
Set the current default output port to PORT.
@end deffn
@deffn primitive set-current-error-port port
Set the current default error port to PORT.
@end deffn
@node Port Types
@section 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.
@end menu
@node File Ports
@subsection File Ports
The following procedures are used to open file ports.
See also @ref{Ports and File Descriptors, open}, for an interface
to the Unix @code{open} system call.
@deffn primitive open-file filename mode
Open the file whose name is @var{filename}, and return a port
representing that file. The attributes of the port are
determined by the @var{mode} string. The way in which this is
interpreted is similar to C stdio. The first character must be
one of the following:
@table @samp
@item r
Open an existing file for input.
@item w
Open a file for output, creating it if it doesn't already exist
or removing its contents if it does.
@item 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
@pxref{Ports and File Descriptors, fcntl}
@end table
The following additional characters can be appended:
@table @samp
@item +
Open the port for both input and output. E.g., @code{r+}: open
an existing file for both input and output.
@item 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 @pxref{Ports and File Descriptors,
setvbuf}
@item l
Add line-buffering to the port. The port output buffer will be
automatically flushed whenever a newline character is written.
@end table
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, @code{open-file} throws an exception.
@end deffn
@rnindex open-input-file
@deffn procedure open-input-file filename
Open @var{filename} for input. Equivalent to
@smalllisp
(open-file @var{filename} "r")
@end smalllisp
@end deffn
@rnindex open-output-file
@deffn procedure open-output-file filename
Open @var{filename} for output. Equivalent to
@smalllisp
(open-file @var{filename} "w")
@end smalllisp
@end deffn
@rnindex call-with-input-file
@deffn procedure call-with-input-file file proc
@var{proc} should be a procedure of one argument, and @var{file} should
be a string naming a file. The file must already exist. These
procedures call @var{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.
@end deffn
@rnindex call-with-output-file
@deffn procedure call-with-output-file file proc
@var{proc} should be a procedure of one argument, and @var{file} should
be a string naming a file. The behaviour is unspecified if the file
already exists. These procedures call @var{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.
@end deffn
@rnindex with-input-from-file
@deffn procedure with-input-from-file file thunk
@var{thunk} must be a procedure of no arguments, and @var{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 @code{current-input-port}, and the @var{thunk} is called
with no arguments. When the @var{thunk} returns, the port is closed and
the previous default is restored. Returns the value yielded by
@var{thunk}. If an escape procedure is used to escape from the
continuation of these procedures, their behavior is implementation
dependent.
@end deffn
@rnindex with-output-to-file
@deffn procedure with-output-to-file file thunk
@var{thunk} must be a procedure of no arguments, and @var{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 @code{current-output-port}, and
the @var{thunk} is called with no arguments. When the @var{thunk}
returns, the port is closed and the previous default is restored.
Returns the value yielded by @var{thunk}. If an escape procedure is
used to escape from the continuation of these procedures, their behavior
is implementation dependent.
@end deffn
@deffn procedure with-error-to-file file thunk
@var{thunk} must be a procedure of no arguments, and @var{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 @code{current-error-port}, and the
@var{thunk} is called with no arguments. When the @var{thunk} returns,
the port is closed and the previous default is restored. Returns the
value yielded by @var{thunk}. If an escape procedure is used to escape
from the continuation of these procedures, their behavior is
implementation dependent.
@end deffn
@deffn primitive port-mode port
Returns the port modes associated with the open port @var{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.
@end deffn
@deffn primitive port-filename port
Return the filename associated with @var{port}. This function returns
the strings "standard input", "standard output" and "standard error"
when called on the current input, output and error ports respectively.
@end deffn
@deffn primitive set-port-filename! port filename
Change the filename associated with @var{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
@code{port-filename} and reported in diagnostic output.
@end deffn
@deffn primitive file-port? obj
Determine whether @var{obj} is a port that is related to a file.
@end deffn
@node String Ports
@subsection String Ports
The following allow string ports to be opened by analogy to R4R*
file port facilities:
@deffn primitive call-with-output-string proc
Calls the one-argument procedure @var{proc} with a newly created output
port. When the function returns, the string composed of the characters
written into the port is returned.
@end deffn
@deffn primitive call-with-input-string string proc
Calls the one-argument procedure @var{proc} with a newly
created input port from which @var{string}'s contents may be
read. The value yielded by the @var{proc} is returned.
@end deffn
@deffn procedure with-output-to-string thunk
Calls the zero-argument procedure @var{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.
@end deffn
@deffn procedure with-input-from-string string thunk
Calls the zero-argument procedure @var{thunk} with the current input
port set temporarily to a string port opened on the specified
@var{string}. The value yielded by @var{thunk} is returned.
@end deffn
@deffn primitive open-input-string str
Take a string and return an input port that delivers characters
from the string. The port can be closed by
@code{close-input-port}, though its storage will be reclaimed
by the garbage collector if it becomes inaccessible.
@end deffn
@deffn primitive open-output-string
Return an output port that will accumulate characters for
retrieval by @code{get-output-string}. The port can be closed
by the procedure @code{close-output-port}, though its storage
will be reclaimed by the garbage collector if it becomes
inaccessible.
@end deffn
@deffn primitive get-output-string port
Given an output port created by @code{open-output-string},
return a string consisting of the characters that have been
output to the port so far.
@end deffn
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.
@node Soft Ports
@subsection Soft Ports
A @dfn{soft-port} is a port based on a vector of procedures capable of
accepting or delivering characters. It allows emulation of I/O ports.
@deffn primitive make-soft-port pv modes
Return a port capable of receiving or delivering characters as
specified by the @var{modes} string (@pxref{File Ports,
open-file}). @var{pv} must be a vector of length 5. Its
components are as follows:
@enumerate 0
@item
procedure accepting one character for output
@item
procedure accepting a string for output
@item
thunk for flushing output
@item
thunk for getting one character
@item
thunk for closing port (not by garbage collection)
@end enumerate
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 @code{#f} if
there is no useful operation for them to perform.
If thunk 3 returns @code{#f} or an @code{eof-object}
(@pxref{Input, eof-object?, ,r5rs, The Revised^5 Report on
Scheme}) it indicates that the port has reached end-of-file.
For example:
@lisp
(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) @result{} #<input-output: soft 8081e20>
@end lisp
@end deffn
@node Void Ports
@subsection 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.
@deffn primitive %make-void-port mode
Create and return a new void port. A void port acts like
@code{/dev/null}. The @var{mode} argument specifies the input/output
modes for this port: see the documentation for @code{open-file} in
@ref{File Ports}.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

222
doc/ref/scheme-memory.texi Normal file
View file

@ -0,0 +1,222 @@
@page
@node Memory Management
@chapter Memory Management and Garbage Collection
@menu
* Garbage Collection::
* Weak References::
* Guardians::
@end menu
@node Garbage Collection
@section Garbage Collection
[FIXME: this is pasted in from Tom Lord's original guile.texi and should
be reviewed]
@deffn primitive gc
Scans all of SCM objects and reclaims for further use those that are
no longer accessible.
@end deffn
@deffn primitive gc-stats
Return an association list of statistics about Guile's current
use of storage.
@end deffn
@deffn primitive object-address obj
Return an integer that for the lifetime of @var{obj} is uniquely
returned by this function for @var{obj}
@end deffn
@deffn primitive unhash-name name
Flushes the glocs for @var{name}, or all glocs if @var{name}
is @code{#t}.
@end deffn
@node Weak References
@section 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
referneced 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.
Property lists offer the same kind of functionality as weak key hashes
in many situations. (@pxref{Property Lists})
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::
@end menu
@node Weak key hashes
@subsection Weak key hashes
@deffn primitive make-weak-key-hash-table size
@deffnx primitive make-weak-value-hash-table size
@deffnx primitive make-doubly-weak-hash-table size
Return a weak hash table with @var{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. (@pxref{Hash Tables})
@end deffn
@deffn primitive weak-key-hash-table? obj
@deffnx primitive weak-value-hash-table? obj
@deffnx primitive doubly-weak-hash-table? obj
Return @code{#t} if @var{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.
@end deffn
@deffn primitive make-weak-value-hash-table k
@end deffn
@deffn primitive weak-value-hash-table? x
@end deffn
@deffn primitive make-doubly-weak-hash-table k
@end deffn
@deffn primitive doubly-weak-hash-table? x
@end deffn
@node Weak vectors
@subsection Weak vectors
Weak vectors are mainly useful in Guile's implementation of weak hash
tables.
@deffn primitive make-weak-vector size [fill]
Return a weak vector with @var{size} elements. If the optional
argument @var{fill} is given, all entries in the vector will be
set to @var{fill}. The default value for @var{fill} is the
empty list.
@end deffn
@deffn primitive weak-vector . l
@deffnx primitive list->weak-vector l
Construct a weak vector from a list: @code{weak-vector} uses
the list of its arguments while @code{list->weak-vector} uses
its only argument @var{l} (a list) to construct a weak vector
the same way @code{list->vector} would.
@end deffn
@deffn primitive weak-vector? obj
Return @code{#t} if @var{obj} is a weak vector. Note that all
weak hashes are also weak vectors.
@end deffn
@node Guardians
@section Guardians
@deffn primitive make-guardian [greedy?]
Create a new guardian.
A guardian protects a set of objects from garbage collection,
allowing a program to apply cleanup or other actions.
@code{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 @code{#f} if no such object is available.
Objects which are returned in this way are removed from
the guardian.
@code{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).
@end deffn
@deffn primitive destroy-guardian! guardian
Destroys @var{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 @var{guardian}.
@end deffn
@deffn primitive guardian-greedy? guardian
Return @code{#t} if @var{guardian} is a greedy guardian, otherwise @code{#f}.
@end deffn
@deffn primitive guardian-destroyed? guardian
Return @code{#t} if @var{guardian} has been destroyed, otherwise @code{#f}.
@end deffn
@page
@node Objects
@chapter Objects
@deffn primitive entity? obj
Return @code{#t} if @var{obj} is an entity.
@end deffn
@deffn primitive operator? obj
Return @code{#t} if @var{obj} is an operator.
@end deffn
@deffn primitive set-object-procedure! obj proc
Return the object procedure of @var{obj} to @var{proc}.
@var{obj} must be either an entity or an operator.
@end deffn
@deffn primitive make-class-object metaclass layout
Create a new class object of class @var{metaclass}, with the
slot layout specified by @var{layout}.
@end deffn
@deffn primitive make-subclass-object class layout
Create a subclass object of @var{class}, with the slot layout
specified by @var{layout}.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

826
doc/ref/scheme-modules.texi Normal file
View file

@ -0,0 +1,826 @@
@page
@node Modules
@chapter Modules
@cindex 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 @emph{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 @emph{information
encapsulation}, which consists of packaging functional units into a
given name space that is clearly separated from other name spaces.
@cindex encapsulation
@cindex information encapsulation
@cindex name space
The language features that allow this are usually called @emph{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 @code{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
@emph{renaming} of objects from a foreign module, so they will not
clutter the global name space.
@cindex name space - private
@menu
* Scheme and modules:: How modules are handled in standard Scheme.
* The Guile module system:: How Guile does it.
* Dynamic Libraries:: Loading libraries of compiled code at run time.
@end menu
@node Scheme and modules
@section Scheme and modules
Scheme, as defined in R5RS, does @emph{not} have a module system at all.
Aubrey Jaffer, mostly to support his portable Scheme library SLIB,
implemented a provide/require mechanism for many Scheme implementations.
Library files in SLIB @emph{provide} a feature, and when user programs
@emph{require} that feature, the library file is loaded in.
For example, the file @file{random.scm} in the SLIB package contains the
line
@smalllisp
(provide 'random)
@end smalllisp
so to use its procedures, a user would type
@smalllisp
(require 'random)
@end smalllisp
and they would magically become available, @emph{but still have the same
names!} So this method is nice, but not as good as a full-featured
module system.
@node The Guile module system
@section The Guile module system
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 Guile version 1.4.
@c fixme: Actually, was it available before? 1.4 seems a bit late...
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.
@c fixme: Review: Need better C code interface commentary.
@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.
* More Module Procedures:: Low-level module code.
* Module System Quirks:: Strange things to be aware of.
* Included Guile Modules:: Which modules come with Guile?
@end menu
@node General Information about Modules
@subsection General Information about Modules
A Guile module is a collection of named procedures, variables and
macros, altogether called the @dfn{bindings}, since they bind, or
associate, a symbol (the name) to a Scheme object (procedure, variable,
or macro). Within a module, all bindings are visible. Certain bindings
can be declared @dfn{public}, in which case they are added to the
module's so-called @dfn{export list}; this set of public bindings is
called the module's @dfn{public interface} (@pxref{Creating Guile
Modules}).
A client module @dfn{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 @dfn{select} which bindings to access and can also
algorithmically @dfn{rename} bindings. In contrast, when using the
providing module's public interface, the entire export list is available
without renaming (@pxref{Using Guile Modules}).
To use a module, it must be found and loaded. All Guile modules have a
unique @dfn{module name}, which is a list of one or more symbols.
Examples are @code{(ice-9 popen)} or @code{(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
@code{%load-extensions} (REFFIXME). The resulting file name is then
searched in all directories in the variable @code{%load-path}. For
example, the @code{(ice-9 popen)} module would result in the filename
@code{ice-9/popen.scm} and searched in the installation directory of
Guile and in all other directories in the load path.
@c FIXME::martin: Not sure about this, maybe someone knows better?
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
@code{use-syntax} syntactic form or the @code{#:use-syntax} module
definition option (@pxref{Creating Guile Modules}).
Please note that there are some problems with the current module system
you should keep in mind (@pxref{Module System Quirks}). We hope to
address these eventually.
@node Using Guile Modules
@subsection Using Guile Modules
To use a Guile module is to access either its public interface or a
custom interface (@pxref{General Information about Modules}). Both
types of access are handled by the syntactic form @code{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 (REFFIXME %load-path).
An @dfn{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:
@smalllisp
(use-modules (ice-9 popen))
@end smalllisp
Here, the interface specification is @code{(ice-9 popen)}, and the
result is that the current module now has access to @code{open-pipe},
@code{close-pipe}, @code{open-input-pipe}, and so on (@pxref{Included
Guile Modules}).
Note in the previous example that if the current module had already
defined @code{open-pipe}, that definition would be overwritten by the
definition in @code{(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:
@smalllisp
(use-modules ((ice-9 popen)
:select ((open-pipe . pipe-open) close-pipe)
:rename (symbol-prefix-proc 'unixy:)))
@end smalllisp
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:
@c Use `smallexample' since `table' is ugly. --ttn
@smallexample
(ice-9 popen) sees: current module sees:
open-pipe unixy:pipe-open
close-pipe unixy:close-pipe
@end smallexample
This example also shows how to use the convenience procedure
@code{symbol-prefix-proc}.
@c begin (scm-doc-string "boot-9.scm" "symbol-prefix-proc")
@deffn procedure symbol-prefix-proc prefix-sym
Return a procedure that prefixes its arg (a symbol) with
@var{prefix-sym}.
@c Insert gratuitous C++ slam here. --ttn
@end deffn
@c begin (scm-doc-string "boot-9.scm" "use-modules")
@deffn syntax use-modules spec @dots{}
Resolve each interface specification @var{spec} into an interface and
arrange for these to be accessible by the current module. The return
value is unspecified.
@var{spec} can be a list of symbols, in which case it names a module
whose public interface is found and used.
@var{spec} can also be of the form:
@smalllisp
(MODULE-NAME [:select SELECTION] [:rename RENAMER])
@end smalllisp
in which case a custom interface is newly created and used.
@var{module-name} is a list of symbols, as above; @var{selection} is a
list of selection-specs; and @var{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 @code{(ORIG . SEEN)}, where @var{orig} is the name in
the used module and @var{seen} is the name in the using module. Note
that @var{seen} is also passed through @var{renamer}.
The @code{:select} and @code{:rename} clauses are optional. If both are
omitted, the returned interface has no bindings. If the @code{:select}
clause is omitted, @var{renamer} operates on the used module's public
interface.
Signal error if module name is not resolvable.
@end deffn
@c FIXME::martin: Is this correct, and is there more to say?
@c FIXME::martin: Define term and concept `system transformer' somewhere.
@deffn syntax use-syntax module-name
Load the module @code{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.
@end deffn
@node Creating Guile Modules
@subsection Creating Guile Modules
When you want to create your own modules, you have to take the following
steps:
@itemize @bullet
@item
Create a Scheme source file and add all variables and procedures you wish
to export, or which are required by the exported procedures.
@item
Add a @code{define-module} form at the beginning.
@item
Export all bindings which should be in the public interface, either
by using @code{define-public} or @code{export} (both documented below).
@end itemize
@c begin (scm-doc-string "boot-9.scm" "define-module")
@deffn syntax define-module module-name [options @dots{}]
@var{module-name} is of the form @code{(hierarchy file)}. One
example of this is
@smalllisp
(define-module (ice-9 popen))
@end smalllisp
@code{define-module} makes this module available to Guile programs under
the given @var{module-name}.
The @var{options} are keyword/value pairs which specify more about the
defined module. The recognized options and their meaning is shown in
the following table.
@c fixme: Should we use "#:" or ":"?
@table @code
@item #:use-module @var{interface-specification}
Equivalent to a @code{(use-modules @var{interface-specification})}
(@pxref{Using Guile Modules}).
@item #:use-syntax @var{module}
Use @var{module} when loading the currently defined module, and install
it as the syntax transformer.
@item #:autoload @var{module} @var{symbol}
Load @var{module} whenever @var{symbol} is accessed.
@item #:export @var{list}
Export all identifiers in @var{list}, which must be a list of symbols.
This is equivalent to @code{(export @var{list})} in the module body.
@item #:no-backtrace
Tell Guile not to record information for procedure backtraces when
executing the procedures in this module.
@item #:pure
Create a @dfn{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 @dfn{safe} modules, that is modules which
do not know anything about dangerous procedures.
@end table
@end deffn
@c end
@deffn syntax export variable @dots{}
Add all @var{variable}s (which must be symbols) to the list of exported
bindings of the current module.
@end deffn
@c begin (scm-doc-string "boot-9.scm" "define-public")
@deffn syntax define-public @dots{}
Equivalent to @code{(begin (define foo ...) (export foo))}.
@end deffn
@c end
@node More Module Procedures
@subsection More Module Procedures
@c FIXME::martin: Review me!
@c FIXME::martin: Should this procedure be documented and supported
@c at all?
The procedures in this section are useful if you want to dig into the
innards of Guile's module system. If you don't know precisely what you
do, you should probably avoid using any of them.
@deffn primitive standard-eval-closure module
Return an eval closure for the module @var{module}.
@end deffn
@node Module System Quirks
@subsection 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.
@itemize @bullet
@item
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.
@item
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
@dfn{name-clash} situation, use a custom interface specification
(@pxref{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.)
@item
[Add other quirks here.]
@end itemize
@node Included Guile Modules
@subsection Included Guile Modules
@c FIXME::martin: Review me!
Some modules are included in the Guile distribution; here are references
to the entries in this manual which describe them in more detail:
@table @strong
@item boot-9
boot-9 is Guile's initialization module, and it is always loaded when
Guile starts up.
@item (ice-9 debug)
Mikael Djurfeldt's source-level debugging support for Guile
(@pxref{Debugger User Interface}).
@item (ice-9 threads)
Guile's support for multi threaded execution (@pxref{Scheduling}).
@item (ice-9 rdelim)
Line- and character-delimited input (@pxref{Line/Delimited}).
@item (ice-9 rw)
Block string input/output (@pxref{Block Reading and Writing}).
@item (ice-9 documentation)
Online documentation (REFFIXME).
@item (srfi srfi-1)
A library providing a lot of useful list and pair processing
procedures (@pxref{SRFI-1}).
@item (srfi srfi-2)
Support for @code{and-let*} (@pxref{SRFI-2}).
@item (srfi srfi-4)
Support for homogeneous numeric vectors (@pxref{SRFI-4}).
@item (srfi srfi-6)
Support for some additional string port procedures (@pxref{SRFI-6}).
@item (srfi srfi-8)
Multiple-value handling with @code{receive} (@pxref{SRFI-8}).
@item (srfi srfi-9)
Record definition with @code{define-record-type} (@pxref{SRFI-9}).
@item (srfi srfi-10)
Read hash extension @code{#,()} (@pxref{SRFI-10}).
@item (srfi srfi-11)
Multiple-value handling with @code{let-values} and @code{let-values*}
(@pxref{SRFI-11}).
@item (srfi srfi-13)
String library (@pxref{SRFI-13}).
@item (srfi srfi-14)
Character-set library (@pxref{SRFI-14}).
@item (srfi srfi-17)
Getter-with-setter support (@pxref{SRFI-17}).
@item (ice-9 slib)
This module contains hooks for using Aubrey Jaffer's portable Scheme
library SLIB from Guile (@pxref{SLIB}).
@c FIXME::martin: This module is not in the distribution. Remove it
@c from here?
@item (ice-9 jacal)
This module contains hooks for using Aubrey Jaffer's symbolic math
packge Jacal from Guile (@pxref{JACAL}).
@end table
@node Dynamic Libraries
@section Dynamic Libraries
Most modern Unices have something called @dfn{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 @dfn{dynamic linking}@footnote{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 @dfn{dlopening}, as suggested by Gordon Matzigkeit
in his libtool documentation.}
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::
* Compiled Code Modules::
* Dynamic Linking and Compiled Code Modules::
@end menu
@node Low level dynamic linking
@subsection 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 get's done
with it.
@deffn primitive dynamic-link library
Find the shared library denoted by @var{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, @var{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 @file{/usr/lib} and @file{/usr/local/lib}.
@end deffn
@deffn primitive dynamic-object? val
Determine whether @var{val} represents a dynamically linked object file.
@end deffn
@deffn primitive dynamic-unlink dynobj
Unlink the indicated object file from the application. The argument
@var{dynobj} should be one of the values returned by
@code{dynamic-link}. When @code{dynamic-unlink} has been called on
@var{dynobj}, it is no longer usable as an argument to the functions
below and you will get type mismatch errors when you try to.
@end deffn
@deffn primitive dynamic-func function dynobj
Search the C function indicated by @var{function} (a string or symbol)
in @var{dynobj} and return some Scheme object that can later be used
with @code{dynamic-call} to actually call this function. Right now,
these Scheme objects are formed by casting the address of the function
to @code{long} and converting this number to its Scheme representation.
Regardless whether your C compiler prepends an underscore @samp{_} to
the global names in a program, you should @strong{not} include this
underscore in @var{function}. Guile knows whether the underscore is
needed or not and will add it when necessary.
@end deffn
@deffn primitive dynamic-call function dynobj
Call the C function indicated by @var{function} and @var{dynobj}. The
function is passed no arguments and its return value is ignored. When
@var{function} is something returned by @code{dynamic-func}, call that
function and ignore @var{dynobj}. When @var{function} is a string (or
symbol, etc.), look it up in @var{dynobj}; this is equivalent to
@smallexample
(dynamic-call (dynamic-func @var{function} @var{dynobj} #f))
@end smallexample
Interrupts are deferred while the C function is executing (with
@code{SCM_DEFER_INTS}/@code{SCM_ALLOW_INTS}).
@end deffn
@deffn primitive dynamic-args-call function dynobj args
Call the C function indicated by @var{function} and @var{dynobj}, just
like @code{dynamic-call}, but pass it some arguments and return its
return value. The C function is expected to take two arguments and
return an @code{int}, just like @code{main}:
@smallexample
int c_func (int argc, char **argv);
@end smallexample
The parameter @var{args} must be a list of strings and is converted into
an array of @code{char *}. The array is passed in @var{argv} and its
size in @var{argc}. The return value is converted to a Scheme number
and returned from the call to @code{dynamic-args-call}.
@end deffn
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:
@smallexample
(define libc-obj (dynamic-link "libc.so"))
libc-obj
@result{} #<dynamic-object "libc.so">
(dynamic-args-call 'rand libc-obj '())
@result{} 269167349
(dynamic-unlink libc-obj)
libc-obj
@result{} #<dynamic-object "libc.so" (unlinked)>
@end smallexample
As you can see, after calling @code{dynamic-unlink} on a dynamically
linked library, it is marked as @samp{(unlinked)} and you are no longer
able to use it with @code{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, @code{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,
@code{dynamic-call} and @code{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
@file{libX11} with @code{dynamic-link} and then construct a beautiful
graphical user interface just by using @code{dynamic-call} and
@code{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 @file{libffi}, a library that implements a @dfn{foreign
function interface} for a number of different platforms. With it, you
can extend the Spartan functionality of @code{dynamic-call} and
@code{dynamic-args-call} considerably. There is glue code available in
the Guile contrib archive to make @file{libffi} accessible from Guile.
@node Compiled Code Modules
@subsection Putting Compiled Code into Modules
@c FIXME::martin: Change all gh_ references to their scm_ equivalents.
The new primitives that you add to Guile with @code{gh_new_procedure}
or with any of the other mechanisms are normally placed into the same
module as all the other builtin procedures (like @code{display}).
However, it is also possible to put new primitives into their own
module.
The mechanism for doing so is not very well thought out and is likely to
change when the module system of Guile itself is revised, but it is
simple and useful enough to document it as it stands.
What @code{gh_new_procedure} and the functions used by the snarfer
really do is to add the new primitives to whatever module is the
@emph{current module} when they are called. This is analogous to the
way Scheme code is put into modules: the @code{define-module} expression
at the top of a Scheme source file creates a new module and makes it the
current module while the rest of the file is evaluated. The
@code{define} expressions in that file then add their new definitions to
this current module.
Therefore, all we need to do is to make sure that the right module is
current when calling @code{gh_new_procedure} for our new primitives.
Unfortunately, there is not yet an easy way to access the module system
from C, so we are better off with a more indirect approach. Instead of
adding our primitives at initialization time we merely register with
Guile that we are ready to provide the contents of a certain module,
should it ever be needed.
@deftypefun void scm_register_module_xxx (char *@var{name}, void (*@var{initfunc})(void))
Register with Guile that @var{initfunc} will provide the contents of the
module @var{name}.
The function @var{initfunc} should perform the usual initialization
actions for your new primitives, like calling @code{gh_new_procedure} or
including the file produced by the snarfer. When @var{initfunc} is
called, the current module is a newly created module with a name as
indicated by @var{name}. Each definition that is added to it will be
automatically exported.
The string @var{name} indicates the hierachical name of the new module.
It should consist of the individual components of the module name
separated by single spaces. That is, the Scheme module name @code{(foo
bar)}, which is a list, should be written as @code{"foo bar"} for the
@var{name} parameter.
You can call @code{scm_register_module_xxx} at any time, even before
Guile has been initialized. This might be useful when you want to put
the call to it in some initialization code that is magically called
before main, like constructors for global C++ objects.
An example for @code{scm_register_module_xxx} appears in the next section.
@end deftypefun
Now, instead of calling the initialization function at program startup,
you should simply call @code{scm_register_module_xxx} and pass it the
initialization function. When the named module is later requested by
Scheme code with @code{use-modules} for example, Guile will notice that
it knows how to create this module and will call the initialization
function at the right time in the right context.
@node Dynamic Linking and Compiled Code Modules
@subsection Dynamic Linking and Compiled Code Modules
The most interesting application of dynamically linked libraries is
probably to use them for providing @emph{compiled code modules} to
Scheme programs. As much fun as programming in Scheme is, every now and
then comes the need to write some low-level C stuff to make Scheme even
more fun.
Not only can you put these new primitives into their own module (see the
previous section), you can even put them into a shared library that is
only then linked to your running Guile image when it is actually
needed.
An example will hopefully make everything clear. Suppose we want to
make the Bessel functions of the C library available to Scheme in the
module @samp{(math bessel)}. First we need to write the appropriate
glue code to convert the arguments and return values of the functions
from Scheme to C and back. Additionally, we need a function that will
add them to the set of Guile primitives. Because this is just an
example, we will only implement this for the @code{j0} function, tho.
@c FIXME::martin: Change all gh_ references to their scm_ equivalents.
@smallexample
#include <math.h>
#include <guile/gh.h>
SCM
j0_wrapper (SCM x)
@{
return gh_double2scm (j0 (gh_scm2double (x)));
@}
void
init_math_bessel ()
@{
gh_new_procedure1_0 ("j0", j0_wrapper);
@}
@end smallexample
We can already try to bring this into action by manually calling the low
level functions for performing dynamic linking. The C source file needs
to be compiled into a shared library. Here is how to do it on
GNU/Linux, please refer to the @code{libtool} documentation for how to
create dynamically linkable libraries portably.
@smallexample
gcc -shared -o libbessel.so -fPIC bessel.c
@end smallexample
Now fire up Guile:
@smalllisp
(define bessel-lib (dynamic-link "./libbessel.so"))
(dynamic-call "init_math_bessel" bessel-lib)
(j0 2)
@result{} 0.223890779141236
@end smalllisp
The filename @file{./libbessel.so} should be pointing to the shared
library produced with the @code{gcc} command above, of course. The
second line of the Guile interaction will call the
@code{init_math_bessel} function which in turn will register the C
function @code{j0_wrapper} with the Guile interpreter under the name
@code{j0}. This function becomes immediately available and we can call
it from Scheme.
Fun, isn't it? But we are only half way there. This is what
@code{apropos} has to say about @code{j0}:
@smallexample
(apropos 'j0)
@print{} the-root-module: j0 #<primitive-procedure j0>
@end smallexample
As you can see, @code{j0} is contained in the root module, where all
the other Guile primitives like @code{display}, etc live. In general,
a primitive is put into whatever module is the @dfn{current module} at
the time @code{gh_new_procedure} is called. To put @code{j0} into its
own module named @samp{(math bessel)}, we need to make a call to
@code{scm_register_module_xxx}. Additionally, to have Guile perform
the dynamic linking automatically, we need to put @file{libbessel.so}
into a place where Guile can find it. The call to
@code{scm_register_module_xxx} should be contained in a specially
named @dfn{module init function}. Guile knows about this special name
and will call that function automatically after having linked in the
shared library. For our example, we add the following code to
@file{bessel.c}:
@smallexample
void scm_init_math_bessel_module ()
@{
scm_register_module_xxx ("math bessel", init_math_bessel);
@}
@end smallexample
The general pattern for the name of a module init function is:
@samp{scm_init_}, followed by the name of the module where the
individual hierarchical components are concatenated with underscores,
followed by @samp{_module}. It should call
@code{scm_register_module_xxx} with the correct module name and the
appropriate initialization function. When that initialization function
will be called, a newly created module with the right name will be the
@emph{current module} so that all definitions that the initialization
functions makes will end up in the correct module.
After @file{libbessel.so} has been rebuild, we need to place the shared
library into the right place. When Guile tries to autoload the
@samp{(math bessel)} module, it looks not only for a file called
@file{math/bessel.scm} in its @code{%load-path}, but also for
@file{math/libbessel.so}. So all we need to do is to create a directory
called @file{math} somewhere in Guile's @code{%load-path} and place
@file{libbessel.so} there. Normally, the current directory @file{.} is
in the @code{%load-path}, so we just use that for this example.
@smallexample
% mkdir maths
% cd maths
% ln -s ../libbessel.so .
% cd ..
% guile
guile> (use-modules (math bessel))
guile> (j0 2)
0.223890779141236
guile> (apropos 'j0)
@print{} bessel: j0 #<primitive-procedure j0>
@end smallexample
That's it!
Note that we used a symlink to make @file{libbessel.so} appear in the
right spot. This is probably not a bad idea in general. The
directories that the @file{%load-path} normally contains are supposed to
contain only architecture independent files. They are not really the
right place for a shared library. You might want to install the
libraries somewhere below @samp{exec_prefix} and then symlink to them
from the architecture independent directory. This will at least work on
heterogenous systems where the architecture dependent stuff resides in
the same place on all machines (which seems like a good idea to me
anyway).
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

398
doc/ref/scheme-options.texi Normal file
View file

@ -0,0 +1,398 @@
@page
@node Options and Config
@chapter Runtime Options and Configuration
Guile's 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 @emph{reading}, @emph{printing}, @emph{debugging} or
@emph{evaluating}.
@menu
* General option interface::
* Reader options::
* Printing options::
* Debugger options::
* Evaluator options::
* Evaluator trap options::
* Examples of option use::
* Install Config:: Installation and configuration data.
@end menu
@node General option interface
@section General option interface
We will use the expression @code{<group>} to represent @code{read},
@code{print}, @code{debug} or @code{evaluator}.
@subheading Low level
@c NJFIXME
@deffn primitive <group>-options-interface
@deffnx primitive read-options-interface [SOME-INT]
@deffnx primitive print-options-interface [SOME-INT]
@deffnx primitive evaluator-traps-interface [SOME-INT]
@deffnx primitive read-options-interface [SOME-INT]
[FIXME: I have just taken the comments for C routine scm_options that
implements all of these. It needs to be presented better.]
If scm_options is called without arguments, the current option setting
is returned. If the argument is an option setting, options are altered
and the old setting is returned. If the argument isn't a list, a list
of sublists is returned, where each sublist contains option name, value
and documentation string.
@end deffn
@subheading User level
@c @deftp {Data type} scm_option
@c @code{scm_option} is used to represent run time options. It can be a
@c @emph{boolean} type, in which case the option will be set by the strings
@c @code{"yes"} and @code{"no"}. It can be a
@c @end deftp
@c NJFIXME
@deffn procedure <group>-options [arg]
@deffnx procedure read-options [arg]
@deffnx procedure print-options [arg]
@deffnx procedure debug-options [arg]
@deffnx procedure traps [arg]
These functions list the options in their group. The optional argument
@var{arg} is a symbol which modifies the form in which the options are
presented.
With no arguments, @code{<group>-options} returns the values of the
options in that particular group. If @var{arg} is @code{'help}, a
description of each option is given. If @var{arg} is @code{'full},
programmers' options are also shown.
@var{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.
@end deffn
[FIXME: I don't think 'full is ever any different from 'help. What's
up?]
@c NJFIXME
@deffn procedure <group>-enable option-symbol
@deffnx procedure read-enable option-symbol
@deffnx procedure print-enable option-symbol
@deffnx procedure debug-enable option-symbol
@deffnx procedure trap-enable option-symbol
These functions set the specified @var{option-symbol} in their options
group. They only work if the option is boolean, and throw an error
otherwise.
@end deffn
@c NJFIXME
@deffn procedure <group>-disable option-symbol
@deffnx procedure read-disable option-symbol
@deffnx procedure print-disable option-symbol
@deffnx procedure debug-disable option-symbol
@deffnx procedure trap-disable option-symbol
These functions turn off the specified @var{option-symbol} in their
options group. They only work if the option is boolean, and throw an
error otherwise.
@end deffn
@c NJFIXME
@deffn syntax <group>-set! option-symbol value
@deffnx syntax read-set! option-symbol value
@deffnx syntax print-set! option-symbol value
@deffnx syntax debug-set! option-symbol value
@deffnx syntax trap-set! option-symbol value
These functions set a non-boolean @var{option-symbol} to the specified
@var{value}.
@end deffn
@node Reader options
@section Reader options
@cindex options - read
@cindex read options
Here is the list of reader options generated by typing
@code{(read-options 'full)} in Guile. You can also see the default
values.
@smalllisp
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.
@end smalllisp
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
@smalllisp
(read-enable 'case-insensitive)
@end smalllisp
@node Printing options
@section Printing options
Here is the list of print options generated by typing
@code{(print-options 'full)} in Guile. You can also see the default
values.
@smallexample
source no Print closures with source.
closure-hook #f Hook for printing closures.
@end smallexample
@node Evaluator options
@section Evaluator options
These are the evaluator options with their default values, as they are
printed by typing @code{(eval-options 'full)} in Guile.
@smallexample
stack 22000 Size of thread stacks (in machine words).
@end smallexample
@node Evaluator trap options
@section 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
@code{(traps 'full)} in Guile. You can also see the default values.
@smallexample
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.
@end smallexample
@deffn apply-frame-handler key cont tailp
Called when a procedure is being applied.
Called if:
@itemize @bullet
@item
evaluator traps are enabled [traps interface], and
@item
either
@itemize @minus
@item
@code{apply-frame} is enabled [traps interface], or
@item
trace mode is on [debug-options interface], and the procedure being
called has the trace property enabled.
@end itemize
@end itemize
If cheap traps are enabled [debug-options interface], @var{cont} is a
debug object, otherwise it is a restartable continuation.
@var{tailp} is true if this is a tail call
@end deffn
@deffn exit-frame-handler key cont retval
Called when a value is returned from a procedure.
Called if:
@itemize @bullet
@item
evaluator traps are enabled [traps interface], and
@item
either
@itemize @minus
@item
@code{exit-frame} is enabled [traps interface], or
@item
trace mode is on [debug-options interface], and the procedure being
called has the trace property enabled.
@end itemize
@end itemize
If cheap traps are enabled [debug-options interface], @var{cont} is a
debug object, otherwise it is a restartable continuation.
@var{retval} is the return value.
@end deffn
@node Debugger options
@section Debugger options
Here is the list of print options generated by typing
@code{(debug-options 'full)} in Guile. You can also see the default
values.
@smallexample
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.
@end smallexample
@node Examples of option use
@section 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
@enumerate
@item
Notices that the symbols @code{abc} and @code{aBc} are not the same
@item
Examines the @code{read-options}, and sees that @code{case-insensitive}
is set to ``no''.
@item
Enables @code{case-insensitive}
@item
Verifies that now @code{aBc} and @code{abc} are the same
@item
Disables @code{case-insensitive} and enables debugging @code{backtrace}
@item
Reproduces the error of displaying @code{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.]
@end enumerate
@smalllisp
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>
@end smalllisp
@node Install Config
@section Installation and Configuration Data
It is often useful to have site-specific information about the current
Guile installation. This chapter describes how to find out about
Guile's configuration at run time.
@deffn primitive version
@deffnx primitive major-version
@deffnx primitive minor-version
@deffnx primitive micro-version
Return a string describing Guile's version number, or its major or minor
version numbers, respectively.
@lisp
(version) @result{} "1.6.5"
(major-version) @result{} "1"
(minor-version) @result{} "6"
(micro-version) @result{} "5"
@end lisp
@end deffn
@c NJFIXME not in libguile!
@deffn primitive libguile-config-stamp
Return a string describing the date on which @code{libguile} was
configured. This is used to determine whether the Guile core
interpreter and the ice-9 runtime have grown out of date with one
another.
@end deffn
@deffn primitive %package-data-dir
Return the name of the directory where Scheme packages, modules and
libraries are kept. On most Unix systems, this will be
@samp{/usr/local/share/guile}.
@end deffn
@deffn primitive %library-dir
Return the directory where the Guile Scheme library files are installed.
E.g., may return "/usr/share/guile/1.3.5".
@end deffn
@deffn primitive %site-dir
Return the directory where the Guile site files are installed.
E.g., may return "/usr/share/guile/site".
@end deffn
@deffn primitive parse-path path [tail]
Parse @var{path}, which is expected to be a colon-separated
string, into a list and return the resulting list with
@var{tail} appended. If @var{path} is @code{#f}, @var{tail}
is returned.
@end deffn
@deffn primitive search-path path filename [extensions]
Search @var{path} for a directory containing a file named
@var{filename}. The file must be readable, and not a directory.
If we find one, return its full filename; otherwise, return
@code{#f}. If @var{filename} is absolute, return it unchanged.
If given, @var{extensions} is a list of strings; for each
directory in @var{path}, we search for @var{filename}
concatenated with each @var{extension}.
@end deffn
@defvar %load-path
Return the list of directories which should be searched for Scheme
modules and libraries.
@end defvar
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

View file

@ -0,0 +1,778 @@
@page
@node Procedures and Macros
@chapter Procedures and Macros
@menu
* Lambda:: Basic procedure creation using lambda.
* Optional Arguments:: Handling keyword, optional and rest arguments.
* Procedure Properties:: Procedure properties and metainformation.
* Procedures with Setters:: Procedures with setters.
* Macros:: Lisp style macro definitions.
* Syntax Rules:: Support for R5RS @code{syntax-rules}.
* Syntax Case:: Support for the @code{syntax-case} system.
* Internal Macros:: Guile's internal representation.
@end menu
@node Lambda
@section Lambda: Basic Procedure Creation
@c FIXME::martin: Review me!
A @code{lambda} expression evaluates to a procedure. The environment
which is in effect when a @code{lambda} expression is evaluated is
enclosed in the newly created procedure, this is referred to as a
@dfn{closure} (@pxref{About Closure}).
When a procedure created by @code{lambda} is called with some actual
arguments, the environment enclosed in the procedure is extended by
binding the variables named in the formal argument list to new locations
and storing the actual arguments into these locations. Then the body of
the @code{lambda} expression is evaluation sequentially. The result of
the last expression in the procedure body is then the result of the
procedure invocation.
The following examples will show how procedures can be created using
@code{lambda}, and what you can do with these procedures.
@lisp
(lambda (x) (+ x x)) @result{} @r{a procedure}
((lambda (x) (+ x x)) 4) @result{} 8
@end lisp
The fact that the environment in effect when creating a procedure is
enclosed in the procedure is shown with this example:
@lisp
(define add4
(let ((x 4))
(lambda (y) (+ x y))))
(add4 6) @result{} 10
@end lisp
@deffn syntax lambda formals body
@var{formals} should be a formal argument list as described in the
following table.
@table @code
@item (@var{variable1} @dots{})
The procedure takes a fixed number of arguments; when the procedure is
called, the arguments will be stored into the newly created location for
the formal variables.
@item @var{variable}
The procedure takes any number of arguments; when the procedure is
called, the sequence of actual arguments will converted into a list and
stored into the newly created location for the formal variable.
@item (@var{variable1} @dots{} @var{variablen} . @var{variablen+1})
If a space-delimited period precedes the last variable, then the
procedure takes @var{n} or more variablesm where @var{n} is the number
of formal arguments before the period. There must be at least one
argument before the period. The first @var{n} actual arguments will be
stored into the newly allocated locations for the first @var{n} formal
arguments and the sequence of the remaining actual arguments is
converted into a list and the stored into the location for the last
formal argument. If there are exactly @var{n} actual arguments, the
empty list is stored into the location of the last formal argument.
@end table
@var{body} is a sequence of Scheme expressions which are evaluated in
order when the procedure is invoked.
@end deffn
@node Optional Arguments
@section Optional Arguments
@c FIXME::martin: Review me!
Scheme procedures, as defined in R5RS, can wither handle a fixed number
of actual arguments, or a fixed number of actual arguments followed by
arbitrarily many additional arguments. Writing procedures of variable
arity can be useful, but unfortunately, the syntactic means for handling
argument lists of varying length is a bit inconvenient. It is possible
to give names to the fixed number of argument, but the remaining
(optional) arguments can be only referenced as a list of values
(@pxref{Lambda}).
Guile comes with the module @code{(ice-9 optargs)}, which makes using
optional arguments much more convenient. In addition, this module
provides syntax for handling keywords in argument lists
(@pxref{Keywords}).
Before using any of the procedures or macros defined in this section,
you have to load the module @code{(ice-9 optargs)} with the statement:
@lisp
(use-modules (ice-9 optargs))
@end lisp
@menu
* let-optional Reference:: Locally binding optional arguments.
* let-keywords Reference:: Locally binding keywords arguments.
* lambda* Reference:: Creating advanced argument handling procedures.
* define* Reference:: Defining procedures and macros.
@end menu
@node let-optional Reference
@subsection let-optional Reference
@c FIXME::martin: Review me!
The syntax @code{let-optional} and @code{let-optional*} are for
destructuring rest argument lists and giving names to the various list
elements. @code{let-optional} binds all variables simultaneously, while
@code{let-optional*} binds them sequentially, consistent with @code{let}
and @code{let*} (@pxref{Local Bindings}).
@deffn {libary syntax} let-optional rest-arg (binding @dots{}) expr @dots{}
@deffnx {library syntax} let-optional* rest-arg (binding @dots{}) expr @dots{}
These two macros give you an optional argument interface that is very
@dfn{Schemey} and introduces no fancy syntax. They are compatible with
the scsh macros of the same name, but are slightly extended. Each of
@var{binding} may be of one of the forms @var{var} or @code{(@var{var}
@var{default-value})}. @var{rest-arg} should be the rest-argument of the
procedures these are used from. The items in @var{rest-arg} are
sequentially bound to the variable names are given. When @var{rest-arg}
runs out, the remaining vars are bound either to the default values or
left unbound if no default value was specified. @var{rest-arg} remains
bound to whatever may have been left of @var{rest-arg}.
After binding the variables, the expressions @var{expr} @dots{} are
evaluated in order.
@end deffn
@node let-keywords Reference
@subsection let-keywords Reference
@c FIXME::martin: Review me!
@code{let-keywords} and @code{let-keywords*} are used for extracting
values from argument lists which use keywords instead of argument
position for binding local variables to argument values.
@code{let-keywords} binds all variables simultaneously, while
@code{let-keywords*} binds them sequentially, consistent with @code{let}
and @code{let*} (@pxref{Local Bindings}).
@deffn {library syntax} let-keywords rest-arg allow-other-keys? (binding @dots{}) expr @dots{}
@deffnx {library syntax} let-keywords rest-arg allow-other-keys? (binding @dots{}) expr @dots{}
These macros pick out keyword arguments from @var{rest-arg}, but do not
modify it. This is consistent at least with Common Lisp, which
duplicates keyword arguments in the rest argument. More explanation of what
keyword arguments in a lambda list look like can be found below in
the documentation for @code{lambda*}
(@pxref{lambda* Reference}). @var{binding}s can have the same form as
for @code{let-optional}. If @var{allow-other-keys?} is false, an error
will be thrown if anything that looks like a keyword argument but does
not match a known keyword parameter will result in an error.
After binding the variables, the expressions @var{expr} @dots{} are
evaluated in order.
@end deffn
@node lambda* Reference
@subsection lambda* Reference
@c FIXME::martin: Review me!
When using optional and keyword argument lists, using @code{lambda} for
creating procedures and using @code{let-optional} or @code{let-keywords}
is a bit lengthy. Therefore, @code{lambda*} is provided, which combines
the features of those macros into a single convenient syntax.
For quick reference, here is the syntax of the formal argument list for
@code{lambda*} (brackets are used to indicate grouping only):
@example
ext-param-list ::= [identifier]* [#:optional [ext-var-decl]+]?
[#:key [ext-var-decl]+ [#:allow-other-keys]?]?
[[#:rest identifier]|[. identifier]]?
ext-var-decl ::= identifier | ( identifier expression )
@end example
The characters `*', `+' and `?' are not to be taken literally; they mean
respectively, zero or more occurences, one or more occurences, and one
or zero occurences.
@deffn {library syntax} lambda* formals body
@code{lambda*} creates a procedure that takes optional arguments. These
are specified by putting them inside brackets at the end of the
paramater list, but before any dotted rest argument. For example,
@lisp
(lambda* (a b #:optional c d . e) '())
@end lisp
creates a procedure with fixed arguments @var{a} and @var{b}, optional
arguments @var{c} and @var{d}, and rest argument @var{e}. If the
optional arguments are omitted in a call, the variables for them are
unbound in the procedure. This can be checked with the @code{bound?}
macro (documented below).
@code{lambda*} can also take keyword arguments. For example, a procedure
defined like this:
@lisp
(lambda* (#:key xyzzy larch) '())
@end lisp
can be called with any of the argument lists @code{(#:xyzzy 11)}
@code{(#:larch 13)} @code{(#:larch 42 #:xyzzy 19)} @code{()}. Whichever
arguments are given as keywords are bound to values.
Optional and keyword arguments can also be given default values
which they take on when they are not present in a call, by giving a
two-item list in place of an optional argument, for example in:
@lisp
(lambda* (foo #:optional (bar 42) #:key (baz 73))
(list foo bar baz))
@end lisp
@var{foo} is a fixed argument, @var{bar} is an optional argument with
default value 42, and baz is a keyword argument with default value 73.
Default value expressions are not evaluated unless they are needed and
until the procedure is called.
@code{lambda*} also supports two more special parameter list keywords.
@code{lambda*}-defined procedures now throw an error by default if a
keyword other than one of those specified is found in the actual
passed arguments. However, specifying @code{#:allow-other-keys}
immediately after the keyword argument declarations restores the
previous behavior of ignoring unknown keywords. @code{lambda*} also now
guarantees that if the same keyword is passed more than once, the
last one passed is the one that takes effect. For example,
@lisp
((lambda* (#:key (heads 0) (tails 0)) (display (list heads tails)))
#:heads 37 #:tails 42 #:heads 99)
@end lisp
would result in (99 47) being displayed.
@code{#:rest} is also now provided as a synonym for the dotted syntax
rest argument. The argument lists @code{(a . b)} and @code{(a #:rest b)}
are equivalent in all respects to @code{lambda*}. This is provided for
more similarity to DSSSL, MIT-Scheme and Kawa among others, as well as
for refugees from other Lisp dialects.
@end deffn
@deffn {library syntax} bound? variable
Check if a variable is bound in the current environment.
The procedure @code{defined?} doesn't quite cut it as it stands, since
it only checks bindings in the top-level environment, not those in local
scope only.
@end deffn
@node define* Reference
@subsection define* Reference
@c FIXME::martin: Review me!
Just like @code{define} has a shorthand notation for defining procedures
(@pxref{Lambda Alternatives}), @code{define*} is provided as an
abbreviation of the combination of @code{define} and @code{lambda*}.
@code{define*-public} is the @code{lambda*} version of
@code{define-public}; @code{defmacro*} and @code{defmacro*-public} exist
for defining macros with the improved argument list handling
possibilities. The @code{-public} versions not only define the
procedures/macros, but also export them from the current module.
@deffn {library syntax} define* formals body
@deffnx {library syntax} define*-public formals body
@code{define*} and @code{define*-public} support optional arguments with
a similar syntax to @code{lambda*}. They also support arbitrary-depth
currying, just like Guile's define. Some examples:
@lisp
(define* (x y #:optional a (z 3) #:key w . u)
(display (list y z u)))
@end lisp
defines a procedure @code{x} with a fixed argument @var{y}, an optional
agument @var{a}, another optional argument @var{z} with default value 3,
a keyword argument @var{w}, and a rest argument @var{u}.
@lisp
(define-public* ((foo #:optional bar) #:optional baz) '())
@end lisp
This illustrates currying. A procedure @code{foo} is defined, which,
when called with an optional argument @var{bar}, returns a procedure
that takes an optional argument @var{baz}.
Of course, @code{define*[-public]} also supports @code{#:rest} and
@code{#:allow-other-keys} in the same way as @code{lambda*}.
@end deffn
@deffn {library syntax} defmacro* name formals body
@deffnx {library syntax} defmacro*-public name formals body
These are just like @code{defmacro} and @code{defmacro-public} except that they
take @code{lambda*}-style extended paramter lists, where @code{#:optional},
@code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
semantics. Here is an example of a macro with an optional argument:
@lisp
(defmacro* transmorgify (a #:optional b)
(a 1))
@end lisp
@end deffn
@node Procedure Properties
@section Procedure Properties and Metainformation
@c FIXME::martin: Review me!
Procedures always have attached the environment in which they were
created and information about how to apply them to actual arguments. In
addition to that, properties and metainformation can be stored with
procedures. The procedures in this section can be used to test whether
a given procedure satisfies a condition; and to access and set a
procedure's property.
The first group of procedures are predicates to test whether a Scheme
object is a procedure, or a special procedure, respectively.
@code{procedure?} is the most general predicates, it returns @code{#t}
for any kind of procedure. @code{closure?} does not return @code{#t}
for primitive procedures, and @code{thunk?} only returns @code{#t} for
procedures which do not accept any arguments.
@rnindex procedure?
@deffn primitive procedure? obj
Return @code{#t} if @var{obj} is a procedure.
@end deffn
@deffn primitive closure? obj
Return @code{#t} if @var{obj} is a closure.
@end deffn
@deffn primitive thunk? obj
Return @code{#t} if @var{obj} is a thunk.
@end deffn
@c FIXME::martin: Is that true?
@cindex procedure properties
Procedure properties are general properties to be attached to
procedures. These can be the name of a procedure or other relevant
information, such as debug hints.
@deffn primitive procedure-properties proc
Return @var{obj}'s property list.
@end deffn
@deffn primitive procedure-property p k
Return the property of @var{obj} with name @var{key}.
@end deffn
@deffn primitive set-procedure-properties! proc new_val
Set @var{obj}'s property list to @var{alist}.
@end deffn
@deffn primitive set-procedure-property! p k v
In @var{obj}'s property list, set the property named @var{key} to
@var{value}.
@end deffn
@cindex procedure documentation
Documentation for a procedure can be accessed with the procedure
@code{procedure-documentation}.
@deffn primitive procedure-documentation proc
Return the documentation string associated with @code{proc}. By
convention, if a procedure contains more than one expression and the
first expression is a string constant, that string is assumed to contain
documentation for that procedure.
@end deffn
@cindex source properties
@c FIXME::martin: Is the following true?
Source properties are properties which are related to the source code of
a procedure, such as the line and column numbers, the file name etc.
@deffn primitive set-source-properties! obj plist
Install the association list @var{plist} as the source property
list for @var{obj}.
@end deffn
@deffn primitive set-source-property! obj key datum
Set the source property of object @var{obj}, which is specified by
@var{key} to @var{datum}. Normally, the key will be a symbol.
@end deffn
@deffn primitive source-properties obj
Return the source property association list of @var{obj}.
@end deffn
@deffn primitive source-property obj key
Return the source property specified by @var{key} from
@var{obj}'s source property list.
@end deffn
@node Procedures with Setters
@section Procedures with Setters
@c FIXME::martin: Review me!
@c FIXME::martin: Document `operator struct'.
@cindex procedure with setter
@cindex setter
A @dfn{procedure with setter} is a special kind of procedure which
normally behaves like any accesor procedure, that is a procedure which
accesses a data structure. The difference is that this kind of
procedure has a so-called @dfn{setter} attached, which is a procedure
for storing something into a data structure.
Procedures with setters are treated specially when the procedure appears
in the special form @code{set!} (REFFIXME). How it works is best shown
by example.
Suppose we have a procedure called @code{foo-ref}, which accepts two
arguments, a value of type @code{foo} and an integer. The procedure
returns the value stored at the given index in the @code{foo} object.
Let @code{f} be a variable containing such a @code{foo} data
structure.@footnote{Working definitions would be:
@lisp
(define foo-ref vector-ref)
(define foo-set! vector-set!)
(define f (make-vector 2 #f))
@end lisp
}
@lisp
(foo-ref f 0) @result{} bar
(foo-ref f 1) @result{} braz
@end lisp
Also suppose that a corresponding setter procedure called
@code{foo-set!} does exist.
@lisp
(foo-set! f 0 'bla)
(foo-ref f 0) @result{} bla
@end lisp
Now we could create a new procedure called @code{foo}, which is a
procedure with setter, by calling @code{make-procedure-with-setter} with
the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
Let us call this new procedure @code{foo}.
@lisp
(define foo (make-procedure-with-setter foo-ref foo-set!))
@end lisp
@code{foo} can from now an be used to either read from the data
structure stored in @code{f}, or to write into the structure.
@lisp
(set! (foo f 0) 'dum)
(foo f 0) @result{} dum
@end lisp
@deffn primitive make-procedure-with-setter procedure setter
Create a new procedure which behaves like @var{procedure}, but
with the associated setter @var{setter}.
@end deffn
@deffn primitive procedure-with-setter? obj
Return @code{#t} if @var{obj} is a procedure with an
associated setter procedure.
@end deffn
@deffn primitive procedure proc
Return the procedure of @var{proc}, which must be either a
procedure with setter, or an operator struct.
@end deffn
@deffn primitive setter proc
Return the setter of @var{proc}, which must be either a procedure with
setter or an operator struct.
@end deffn
@node Macros
@section Lisp Style Macro Definitions
@cindex macros
@cindex transformation
Macros are objects which cause the expression that they appear in to be
transformed in some way @emph{before} being evaluated. In expressions
that are intended for macro transformation, the identifier that names
the relevant macro must appear as the first element, like this:
@lisp
(@var{macro-name} @var{macro-args} @dots{})
@end lisp
In Lisp-like languages, the traditional way to define macros is very
similar to procedure definitions. The key differences are that the
macro definition body should return a list that describes the
transformed expression, and that the definition is marked as a macro
definition (rather than a procedure definition) by the use of a
different definition keyword: in Lisp, @code{defmacro} rather than
@code{defun}, and in Scheme, @code{define-macro} rather than
@code{define}.
@fnindex defmacro
@fnindex define-macro
Guile supports this style of macro definition using both @code{defmacro}
and @code{define-macro}. The only difference between them is how the
macro name and arguments are grouped together in the definition:
@lisp
(defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
@end lisp
@noindent
is the same as
@lisp
(define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
@end lisp
@noindent
The difference is analogous to the corresponding difference between
Lisp's @code{defun} and Scheme's @code{define}.
@code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
distribution, is a good example of macro definition using
@code{defmacro}:
@lisp
(defmacro false-if-exception (expr)
`(catch #t
(lambda () ,expr)
(lambda args #f)))
@end lisp
@noindent
The effect of this definition is that expressions beginning with the
identifier @code{false-if-exception} are automatically transformed into
a @code{catch} expression following the macro definition specification.
For example:
@lisp
(false-if-exception (open-input-file "may-not-exist"))
@equiv{}
(catch #t
(lambda () (open-input-file "may-not-exist"))
(lambda args #f))
@end lisp
@node Syntax Rules
@section The R5RS @code{syntax-rules} System
R5RS defines an alternative system for macro and syntax transformations
using the keywords @code{define-syntax}, @code{let-syntax},
@code{letrec-syntax} and @code{syntax-rules}.
The main difference between the R5RS system and the traditional macros
of the previous section is how the transformation is specified. In
R5RS, rather than permitting a macro definition to return an arbitrary
expression, the transformation is specified in a pattern language that
@itemize @bullet
@item
does not require complicated quoting and extraction of components of the
source expression using @code{caddr} etc.
@item
is designed such that the bindings associated with identifiers in the
transformed expression are well defined, and such that it is impossible
for the transformed expression to construct new identifiers.
@end itemize
@noindent
The last point is commonly referred to as being @dfn{hygienic}: the R5RS
@code{syntax-case} system provides @dfn{hygienic macros}.
For example, the R5RS pattern language for the @code{false-if-exception}
example of the previous section looks like this:
@lisp
(syntax-rules ()
((_ expr)
(catch #t
(lambda () expr)
(lambda args #f))))
@end lisp
In Guile, the @code{syntax-rules} system is provided by the @code{(ice-9
syncase)} module. To make these facilities available in your code,
include the expression @code{(use-modules (ice-9 syncase))} or
@code{(use-syntax (ice-9 syncase))} (@pxref{Using Guile Modules})
before the first usage of @code{define-syntax} etc. If you are writing
a Scheme module, you can alternatively use one of the keywords
@code{#:use-module} and @code{#:use-syntax} in your @code{define-module}
declaration (@pxref{Creating Guile Modules}).
@menu
* Pattern Language:: The @code{syntax-rules} pattern language.
* Define-Syntax:: Top level syntax definitions.
* Let-Syntax:: Local syntax definitions.
@end menu
@node Pattern Language
@subsection The @code{syntax-rules} Pattern Language
@node Define-Syntax
@subsection Top Level Syntax Definitions
define-syntax: The gist is
(define-syntax <keyword> <transformer-spec>)
makes the <keyword> into a macro so that
(<keyword> ...)
expands at _compile_ or _read_ time (i.e. before any
evaluation begins) into some expression that is
given by the <transformer-spec>.
@node Let-Syntax
@subsection Local Syntax Definitions
@node Syntax Case
@section Support for the @code{syntax-case} System
@node Internal Macros
@section Internal Representation of Macros and Syntax
Internally, Guile uses three different flavours of macros. The three
flavours are called @dfn{acro} (or @dfn{syntax}), @dfn{macro} and
@dfn{mmacro}.
Given the expression
@lisp
(foo @dots{})
@end lisp
@noindent
with @code{foo} being some flavour of macro, one of the following things
will happen when the expression is evaluated.
@itemize @bullet
@item
When @code{foo} has been defined to be an @dfn{acro}, the procedure used
in the acro definition of @code{foo} is passed the whole expression and
the current lexical environment, and whatever that procedure returns is
the value of evaluating the expression. You can think of this a
procedure that receives its argument as an unevaluated expression.
@item
When @code{foo} has been defined to be a @dfn{macro}, the procedure used
in the macro definition of @code{foo} is passed the whole expression and
the current lexical environment, and whatever that procedure returns is
evaluated again. That is, the procedure should return a valid Scheme
expression.
@item
When @code{foo} has been defined to be a @dfn{mmacro}, the procedure
used in the mmacro definition of `foo' is passed the whole expression
and the current lexical environment, and whatever that procedure returns
replaces the original expression. Evaluation then starts over from the
new expression that has just been returned.
@end itemize
The key difference between a @dfn{macro} and a @dfn{mmacro} is that the
expression returned by a @dfn{mmacro} procedure is remembered (or
@dfn{memoized}) so that the expansion does not need to be done again
next time the containing code is evaluated.
The primitives @code{procedure->syntax}, @code{procedure->macro} and
@code{procedure->memoizing-macro} are used to construct acros, macros
and mmacros respectively. However, if you do not have a very special
reason to use one of these primitives, you should avoid them: they are
very specific to Guile's current implementation and therefore likely to
change. Use @code{defmacro}, @code{define-macro} (@pxref{Macros}) or
@code{define-syntax} (@pxref{Syntax Rules}) instead. (In low level
terms, @code{defmacro}, @code{define-macro} and @code{define-syntax} are
all implemented as mmacros.)
@deffn primitive procedure->syntax code
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, returns the result of applying @var{code}
to the expression and the environment.
@end deffn
@deffn primitive procedure->macro code
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, evaluates the result of applying
@var{code} to the expression and the environment. For example:
@lisp
(define trace
(procedure->macro
(lambda (x env)
`(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))
(trace @i{foo})
@equiv{}
(set! @i{foo} (tracef @i{foo} '@i{foo})).
@end lisp
@end deffn
@deffn primitive procedure->memoizing-macro code
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, evaluates the result of applying
@var{code} to the expression and the environment.
@code{procedure->memoizing-macro} is the same as
@code{procedure->macro}, except that the expression returned by
@var{code} replaces the original macro expression in the memoized form
of the containing code.
@end deffn
In the following primitives, @dfn{acro} flavour macros are referred to
as @dfn{syntax transformers}.
@deffn primitive macro? obj
Return @code{#t} if @var{obj} is a regular macro, a memoizing macro or a
syntax transformer.
@end deffn
@deffn primitive macro-type m
Return one of the symbols @code{syntax}, @code{macro} or
@code{macro!}, depending on whether @var{m} is a syntax
transformer, a regular macro, or a memoizing macro,
respectively. If @var{m} is not a macro, @code{#f} is
returned.
@end deffn
@deffn primitive macro-name m
Return the name of the macro @var{m}.
@end deffn
@deffn primitive macro-transformer m
Return the transformer of the macro @var{m}.
@end deffn
@deffn primitive cons-source xorig x y
Create and return a new pair whose car and cdr are @var{x} and @var{y}.
Any source properties associated with @var{xorig} are also associated
with the new pair.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

View file

@ -0,0 +1,27 @@
@page
@node Further Reading
@chapter Further Reading
@itemize @bullet
@item
Dorai Sitaram's online Scheme tutorial, @dfn{Teach Yourself Scheme in
Fixnum Days}, at
@url{http://www.cs.rice.edu/~dorai/t-y-scheme/t-y-scheme.html}.
Includes a nice explanation of continuations.
@item
@url{http://wombat.doc.ic.ac.uk/foldoc/}.
@item
The complete text of @dfn{Structure and Interpretation of Computer
Programs}, the classic introduction to computer science and Scheme by
Hal Abelson, Jerry Sussman and Julie Sussman, is now available online at
@url{http://mitpress.mit.edu/sicp/sicp.html}. This site also provides
teaching materials related to the book, and all the source code used in
the book, in a form suitable for loading and running.
@end itemize
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

View file

@ -0,0 +1,435 @@
@page
@node Scheduling
@chapter 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.
@end menu
@node Arbiters
@section Arbiters
@cindex arbiters
@c FIXME::martin: Review me!
Arbiters are synchronization objects. They are created with
@code{make-arbiter}. Two or more threads can synchronize on an arbiter
by trying to lock it using @code{try-arbiter}. This call will succeed
if no other thread has called @code{try-arbiter} on the arbiter yet,
otherwise it will fail and return @code{#f}. Once an arbiter is
successfully locked, it cannot be locked by another thread until the
thread holding the arbiter calls @code{release-arbiter} to unlock it.
@deffn primitive make-arbiter name
Return an object of type arbiter and name @var{name}. Its
state is initially unlocked. Arbiters are a way to achieve
process synchronization.
@end deffn
@deffn primitive try-arbiter arb
Return @code{#t} and lock the arbiter @var{arb} if the arbiter
was unlocked. Otherwise, return @code{#f}.
@end deffn
@deffn primitive release-arbiter arb
Return @code{#t} and unlock the arbiter @var{arb} if the
arbiter was locked. Otherwise, return @code{#f}.
@end deffn
@node Asyncs
@section Asyncs
@cindex asyncs
@cindex system asyncs
@c FIXME::martin: Review me!
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 (@dfn{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 @code{async}, system asyncs with
@code{system-async}. They are marked with @code{async-mark} or
@code{system-async-mark}, respectively.
@deffn primitive async thunk
Create a new async for the procedure @var{thunk}.
@end deffn
@deffn primitive system-async thunk
Create a new async for the procedure @var{thunk}. Also
add it to the system's list of active async objects.
@end deffn
@deffn primitive async-mark a
Mark the async @var{a} for future execution.
@end deffn
@deffn primitive system-async-mark a
Mark the async @var{a} for future execution.
@end deffn
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 @code{run-asyncs}.
@deffn primitive run-asyncs list_of_a
Execute all thunks from the asyncs of the list @var{list_of_a}.
@end deffn
Automatic invocation of system asyncs can be temporarily disabled by
calling @code{mask-signals} and @code{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
@code{mask-signals} is allowed if another one is still active.
@deffn primitive mask-signals
Mask signals. The returned value is not specified.
@end deffn
@deffn primitive unmask-signals
Unmask signals. The returned value is not specified.
@end deffn
@c FIXME::martin: Find an example for usage of `noop'. What is that
@c procedure for anyway?
@deffn primitive noop . args
Do nothing. When called without arguments, return @code{#f},
otherwise return the first argument.
@end deffn
@node Dynamic Roots
@section Dynamic Roots
@cindex dynamic roots
A @dfn{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.
@deffn primitive call-with-dynamic-root thunk handler
Evaluate @code{(thunk)} in a new dynamic context, returning its value.
If an error occurs during evaluation, apply @var{handler} to the
arguments to the throw, just as @code{throw} would. If this happens,
@var{handler} is called outside the scope of the new root -- it is
called in the same dynamic context in which
@code{call-with-dynamic-root} was evaluated.
If @var{thunk} captures a continuation, the continuation is rooted at
the call to @var{thunk}. In particular, the call to
@code{call-with-dynamic-root} is not captured. Therefore,
@code{call-with-dynamic-root} always returns at most one time.
Before calling @var{thunk}, the dynamic-wind chain is un-wound back to
the root and a new chain started for @var{thunk}. Therefore, this call
may not do what you expect:
@lisp
;; Almost certainly a bug:
(with-output-to-port
some-port
(lambda ()
(call-with-dynamic-root
(lambda ()
(display 'fnord)
(newline))
(lambda (errcode) errcode))))
@end lisp
The problem is, on what port will @samp{fnord} be displayed? You
might expect that because of the @code{with-output-to-port} that
it will be displayed on the port bound to @code{some-port}. But it
probably won't -- before evaluating the thunk, dynamic winds are
unwound, including those created by @code{with-output-to-port}.
So, the standard output port will have been re-set to its default value
before @code{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.)
@end deffn
@deffn primitive dynamic-root
Return an object representing the current dynamic root.
These objects are only useful for comparison using @code{eq?}.
They are currently represented as numbers, but your code should
in no way depend on this.
@end deffn
@c begin (scm-doc-string "boot-9.scm" "quit")
@deffn procedure quit [exit_val]
Throw back to the error handler of the current dynamic root.
If integer @var{exit_val} is specified and if Guile is being used
stand-alone and if quit is called from the initial dynamic-root,
@var{exit_val} becomes the exit status of the Guile process and the
process exits.
@end deffn
When Guile is run interactively, errors are caught from within the
read-eval-print loop. An error message will be printed and @code{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.
@c begin (scm-doc-string "boot-9.scm" "batch-mode?")
@deffn procedure batch-mode?
Returns a boolean indicating whether the interpreter is in batch mode.
@end deffn
@c begin (scm-doc-string "boot-9.scm" "set-batch-mode?!")
@deffn procedure set-batch-mode?! arg
If @var{arg} is true, switches the interpreter to batch mode.
The @code{#f} case has not been implemented.
@end deffn
@node Threads
@section Threads
@cindex threads
@cindex Guile threads
@strong{[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.
@cindex posix threads
@cindex Lord, Tom
@cindex Green, Anthony
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::
@end menu
@node Low level thread primitives
@subsection Low level thread primitives
@c NJFIXME no current mechanism for making sure that these docstrings
@c are in sync.
@c begin (texi-doc-string "guile" "call-with-new-thread")
@deffn primitive call-with-new-thread thunk error-handler
Evaluate @code{(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.
@end deffn
@c begin (texi-doc-string "guile" "join-thread")
@deffn primitive join-thread thread
Suspend execution of the calling thread until the target @var{thread}
terminates, unless the target @var{thread} has already terminated.
@end deffn
@c begin (texi-doc-string "guile" "yield")
@deffn primitive 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.
@end deffn
@c begin (texi-doc-string "guile" "make-mutex")
@deffn primitive make-mutex
Create a new mutex object.
@end deffn
@c begin (texi-doc-string "guile" "lock-mutex")
@deffn primitive lock-mutex mutex
Lock @var{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 @var{mutex}.
@end deffn
@c begin (texi-doc-string "guile" "unlock-mutex")
@deffn primitive unlock-mutex mutex
Unlocks @var{mutex} if the calling thread owns the lock on @var{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 @var{mutex} is awakened and grabs the mutex lock.
@end deffn
@c begin (texi-doc-string "guile" "make-condition-variable")
@deffn primitive make-condition-variable
@end deffn
@c begin (texi-doc-string "guile" "wait-condition-variable")
@deffn primitive wait-condition-variable cond-var mutex
@end deffn
@c begin (texi-doc-string "guile" "signal-condition-variable")
@deffn primitive signal-condition-variable cond-var
@end deffn
@node Higher level thread procedures
@subsection Higher level thread procedures
@c new by ttn, needs review
Higher level thread procedures are available by loading the
@code{(ice-9 threads)} module. These provide standardized
thread creation and mutex interaction.
@deffn primitive %thread-handler tag args@dots{}
This procedure is specified as the standard error-handler for
@code{make-thread} and @code{begin-thread}. If the number of @var{args}
is three or more, use @code{display-error}, otherwise display a message
"uncaught throw to @var{tag}". All output is sent to the port specified
by @code{current-error-port}.
Before display, global var @code{the-last-stack} is set to @code{#f}
and signals are unmasked with @code{unmask-signals}.
[FIXME: Why distinguish based on number of args?! Cue voodoo music here.]
@end deffn
@deffn macro make-thread proc [args@dots{}]
Apply @var{proc} to @var{args} in a new thread formed by
@code{call-with-new-thread} using @code{%thread-handler} as the error
handler.
@end deffn
@deffn macro begin-thread first [rest@dots{}]
Evaluate forms @var{first} and @var{rest} in a new thread formed by
@code{call-with-new-thread} using @code{%thread-handler} as the error
handler.
@end deffn
@deffn macro with-mutex m [body@dots{}]
Lock mutex @var{m}, evaluate @var{body}, and then unlock @var{m}.
These sub-operations form the branches of a @code{dynamic-wind}.
@end deffn
@deffn macro monitor first [rest@dots{}]
Evaluate forms @var{first} and @var{rest} under a newly created
anonymous mutex, using @code{with-mutex}.
[FIXME: Is there any way to access the mutex?]
@end deffn
@node Fluids
@section Fluids
@cindex fluids
@c FIXME::martin: Review me!
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 (@pxref{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 (@pxref{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
@code{with-fluids*} below for details.
New fluids are created with @code{make-fluid} and @code{fluid?} is used
for testing whether an object is actually a fluid.
@deffn primitive 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.
@end deffn
@deffn primitive fluid? obj
Return @code{#t} iff @var{obj} is a fluid; otherwise, return
@code{#f}.
@end deffn
The values stored in a fluid can be accessed with @code{fluid-ref} and
@code{fluid-set!}.
@deffn primitive fluid-ref fluid
Return the value associated with @var{fluid} in the current
dynamic root. If @var{fluid} has not been set, then return
@code{#f}.
@end deffn
@deffn primitive fluid-set! fluid value
Set the value associated with @var{fluid} in the current dynamic root.
@end deffn
@code{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.
@deffn primitive with-fluids* fluids values thunk
Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
@var{fluids} must be a list of fluids and @var{values} must be the same
number of their values to be applied. Each substitution is done
one after another. @var{thunk} must be a procedure with no argument.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

View file

@ -0,0 +1,44 @@
@page
@node Translation
@chapter Support for Translating Other Languages
[Describe translation framework.]
@menu
* Emacs Lisp Support:: Helper primitives for Emacs Lisp.
@end menu
@node Emacs Lisp Support
@section Emacs Lisp Support
@deffn primitive nil-car x
Return the car of @var{x}, but convert it to LISP nil if it
is Scheme's end-of-list.
@end deffn
@deffn primitive nil-cdr x
Return the cdr of @var{x}, but convert it to LISP nil if it
is Scheme's end-of-list.
@end deffn
@deffn primitive nil-cons x y
Create a new cons cell with @var{x} as the car and @var{y} as
the cdr, but convert @var{y} to Scheme's end-of-list if it is
a LISP nil.
@end deffn
@deffn primitive nil-eq x y
Compare @var{x} and @var{y} and return LISP's t if they are
@code{eq?}, return LISP's nil otherwise.
@end deffn
@deffn primitive null x
Return LISP's @code{t} if @var{x} is nil in the LISP sense,
return LISP's nil otherwise.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

295
doc/ref/scheme-utility.texi Normal file
View file

@ -0,0 +1,295 @@
@page
@node Utility Functions
@chapter General Utility Functions
@c FIXME::martin: Review me!
This chapter contains information about procedures which are not cleanly
tied to a specific data type. Because of their wide range of
applications, they are collected in a @dfn{utlity} chapter.
@menu
* Equality:: When are two values `the same'?
* Property Lists:: Managing metainformation about Scheme objects.
* Primitive Properties:: A modern low-level interface to object properties.
* Sorting:: Sort utility procedures.
* Copying:: Copying deep structures.
* General Conversion:: Converting objects to strings.
@end menu
@node Equality
@section Equality
@c FIXME::martin: Review me!
@cindex sameness
@cindex equality
Three different kinds of @dfn{sameness} are defined in Scheme.
@itemize @bullet
@item
Two values can refer to exactly the same object.
@item
Two objects can have the same @dfn{value}.
@item
Two objects can be structurally equivalent.
@end itemize
The differentiation between these three kinds is important, because
determining whether two values are the same objects is very efficient,
while determining structural equivalence can be quite expensive
(consider comparing two very long lists). Therefore, three different
procedures for testing for equality are provided, which correspond to
the three kinds of @dfn{sameness} defined above.
@rnindex eq?
@deffn primitive eq? x y
Return @code{#t} iff @var{x} references the same object as @var{y}.
@code{eq?} is similar to @code{eqv?} except that in some cases it is
capable of discerning distinctions finer than those detectable by
@code{eqv?}.
@end deffn
@rnindex eqv?
@deffn primitive eqv? x y
The @code{eqv?} procedure defines a useful equivalence relation on objects.
Briefly, it returns @code{#t} if @var{x} and @var{y} should normally be
regarded as the same object. This relation is left slightly open to
interpretation, but works for comparing immediate integers, characters,
and inexact numbers.
@end deffn
@rnindex equal?
@deffn primitive equal? x y
Return @code{#t} iff @var{x} and @var{y} are recursively @code{eqv?} equivalent.
@code{equal?} recursively compares the contents of pairs,
vectors, and strings, applying @code{eqv?} on other objects such as
numbers and symbols. A rule of thumb is that objects are generally
@code{equal?} if they print the same. @code{equal?} may fail to
terminate if its arguments are circular data structures.
@end deffn
@node Property Lists
@section Property Lists
Every object in the system can have a @dfn{property list} that may
be used for information about that object. For example, a
function may have a property list that includes information about
the source file in which it is defined.
Property lists are implemented as assq lists (@pxref{Association Lists}).
Currently, property lists are implemented differently for procedures and
closures than for other kinds of objects. Therefore, when manipulating
a property list associated with a procedure object, use the
@code{procedure} functions; otherwise, use the @code{object} functions.
@deffn primitive object-properties obj
@deffnx primitive procedure-properties obj
Return @var{obj}'s property list.
@end deffn
@deffn primitive set-object-properties! obj alist
@deffnx primitive set-procedure-properties! obj alist
Set @var{obj}'s property list to @var{alist}.
@end deffn
@deffn primitive object-property obj key
@deffnx primitive procedure-property obj key
Return the property of @var{obj} with name @var{key}.
@end deffn
@deffn primitive set-object-property! obj key value
@deffnx primitive set-procedure-property! obj key value
In @var{obj}'s property list, set the property named @var{key}
to @var{value}.
@end deffn
[Interface bug: there should be a second level of interface in which
the user provides a "property table" that is possibly private.]
@node Primitive Properties
@section Primitive Properties
@deffn primitive primitive-make-property not_found_proc
Create a @dfn{property token} that can be used with
@code{primitive-property-ref} and @code{primitive-property-set!}.
See @code{primitive-property-ref} for the significance of
@var{not_found_proc}.
@end deffn
@deffn primitive primitive-property-ref prop obj
Return the property @var{prop} of @var{obj}. When no value
has yet been associated with @var{prop} and @var{obj}, call
@var{not-found-proc} instead (see @code{primitive-make-property})
and use its return value. That value is also associated with
@var{obj} via @code{primitive-property-set!}. When
@var{not-found-proc} is @code{#f}, use @code{#f} as the
default value of @var{prop}.
@end deffn
@deffn primitive primitive-property-set! prop obj val
Associate @var{code} with @var{prop} and @var{obj}.
@end deffn
@deffn primitive primitive-property-del! prop obj
Remove any value associated with @var{prop} and @var{obj}.
@end deffn
@node Sorting
@section Sorting
@c FIXME::martin: Review me!
@cindex sorting
@cindex sorting lists
@cindex sorting vectors
Sorting is very important in computer programs. Therefore, Guile comes
with several sorting procedures built-in. As always, procedures with
names ending in @code{!} are side-effecting, that means that they may
modify their parameters in order to produce their results.
The first group of procedures can be used to merge two lists (which must
be already sorted on their own) and produce sorted lists containing
all elements of the input lists.
@deffn primitive merge alist blist less
Take two lists @var{alist} and @var{blist} such that
@code{(sorted? alist less?)} and @code{(sorted? blist less?)} and
returns a new list in which the elements of @var{alist} and
@var{blist} have been stably interleaved so that
@code{(sorted? (merge alist blist less?) less?)}.
@end deffn
@deffn primitive merge! alist blist less
Takes two lists @var{alist} and @var{blist} such that
@code{(sorted? alist less?)} and @code{(sorted? blist less?)} and
returns a new list in which the elements of @var{alist} and
@var{blist} have been stably interleaved so that
@code{(sorted? (merge alist blist less?) less?)}.
This is the destructive variant of @code{merge}
Note: this does _not_ accept vectors.
@end deffn
The following procedures can operate on sequences which are either
vectors or list. According to the given arguments, they return sorted
vectors or lists, respectively. The first of the following procedures
determines whether a sequence is already sorted, the other sort a given
sequence. The variants with names starting with @code{stable-} are
special in that they maintain a special property of the input sequences:
If two or more elements are the same according to the comparison
predicate, they are left in the same order as they appeared in the
input.
@deffn primitive sorted? items less
Return @code{#t} iff @var{items} is a list or a vector such that
for all 1 <= i <= m, the predicate @var{less} returns true when
applied to all elements i - 1 and i
@end deffn
@deffn primitive sort items less
Sort the sequence @var{items}, which may be a list or a
vector. @var{less} is used for comparing the sequence
elements. This is not a stable sort.
@end deffn
@deffn primitive sort! items less
Sort the sequence @var{items}, which may be a list or a
vector. @var{less} is used for comparing the sequence
elements. The sorting is destructive, that means that the
input sequence is modified to produce the sorted result.
This is not a stable sort.
@end deffn
@deffn primitive stable-sort items less
Sort the sequence @var{items}, which may be a list or a
vector. @var{less} is used for comparing the sequence elements.
This is a stable sort.
@end deffn
@deffn primitive stable-sort! items less
Sort the sequence @var{items}, which may be a list or a
vector. @var{less} is used for comparing the sequence elements.
The sorting is destructive, that means that the input sequence
is modified to produce the sorted result.
This is a stable sort.
@end deffn
The procedures in the last group only accept lists or vectors as input,
as their names indicate.
@deffn primitive sort-list items less
Sort the list @var{items}, using @var{less} for comparing the
list elements. This is a stable sort.
@end deffn
@deffn primitive sort-list! items less
Sort the list @var{items}, using @var{less} for comparing the
list elements. The sorting is destructive, that means that the
input list is modified to produce the sorted result.
This is a stable sort.
@end deffn
@deffn primitive restricted-vector-sort! vec less startpos endpos
Sort the vector @var{vec}, using @var{less} for comparing
the vector elements. @var{startpos} and @var{endpos} delimit
the range of the vector which gets sorted. The return value
is not specified.
@end deffn
@node Copying
@section Copying Deep Structures
@c FIXME::martin: Review me!
The procedures for copying lists (@pxref{Lists}) only produce a flat
copy of the input list, and currently Guile does not even contain
procedures for copying vectors. @code{copy-tree} can be used for these
application, as it does not only copy the spine of a list, but also
copies any pairs in the cars of the input lists.
@deffn primitive copy-tree obj
Recursively copy the data tree that is bound to @var{obj}, and return a
pointer to the new data structure. @code{copy-tree} recurses down the
contents of both pairs and vectors (since both cons cells and vector
cells may point to arbitrary objects), and stops recursing when it hits
any other object.
@end deffn
@node General Conversion
@section General String Conversion
@c FIXME::martin: Review me!
When debugging Scheme programs, but also for providing a human-friendly
interface, a procedure for converting any Scheme object into string
format is very useful. Conversion from/to strings can of course be done
with specialized procedures when the data type of the object to convert
is known, but with this procedure, it is often more comfortable.
@code{object->string} converts an object by using a print procedure for
writing to a string port, and then returning the resulting string.
Converting an object back from the string is only possible if the object
type has a read syntax and the read syntax is preserved by the printing
procedure.
@deffn primitive object->string obj [printer]
Return a Scheme string obtained by printing @var{obj}.
Printing function can be specified by the optional second
argument @var{printer} (default: @code{write}).
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

458
doc/ref/scm.texi Normal file
View file

@ -0,0 +1,458 @@
@page
@node Scheme Primitives
@c @chapter Writing Scheme primitives in C
@c - according to the menu in guile.texi - NJ 2001/1/26
@chapter Relationship between Scheme and C functions
@c Chapter contents contributed by Thien-Thi Nguyen <ttn@gnu.org>.
Scheme procedures marked "primitive functions" have a regular interface
when calling from C, reflected in two areas: the name of a C function, and
the convention for passing non-required arguments to this function.
@c Although the vast majority of functions support these relationships,
@c there are some exceptions.
@menu
* Transforming Scheme name to C name::
* Structuring argument lists for C functions::
@c * Exceptions to the regularity::
@end menu
@node Transforming Scheme name to C name
@section Transforming Scheme name to C name
Normally, the name of a C function can be derived given its Scheme name,
using some simple textual transformations:
@itemize @bullet
@item
Replace @code{-} (hyphen) with @code{_} (underscore).
@item
Replace @code{?} (question mark) with "_p".
@item
Replace @code{!} (exclamation point) with "_x".
@item
Replace internal @code{->} with "_to_".
@item
Replace @code{<=} (less than or equal) with "_leq".
@item
Replace @code{>=} (greater than or equal) with "_geq".
@item
Replace @code{<} (less than) with "_less".
@item
Replace @code{>} (greater than) with "_gr".
@item
Replace @code{@@} with "at". [Omit?]
@item
Prefix with "gh_" (or "scm_" if you are ignoring the gh interface).
@item
[Anything else? --ttn, 2000/01/16 15:17:28]
@end itemize
Here is an Emacs Lisp command that prompts for a Scheme function name and
inserts the corresponding C function name into the buffer.
@example
(defun insert-scheme-to-C (name &optional use-gh)
"Transforms Scheme NAME, a string, to its C counterpart, and inserts it.
Prefix arg non-nil means use \"gh_\" prefix, otherwise use \"scm_\" prefix."
(interactive "sScheme name: \nP")
(let ((transforms '(("-" . "_")
("?" . "_p")
("!" . "_x")
("->" . "_to_")
("<=" . "_leq")
(">=" . "_geq")
("<" . "_less")
(">" . "_gr")
("@" . "at"))))
(while transforms
(let ((trigger (concat "\\(.*\\)"
(regexp-quote (caar transforms))
"\\(.*\\)"))
(sub (cdar transforms))
(m nil))
(while (setq m (string-match trigger name))
(setq name (concat (match-string 1 name)
sub
(match-string 2 name)))))
(setq transforms (cdr transforms))))
(insert (if use-gh "gh_" "scm_") name))
@end example
@node Structuring argument lists for C functions
@section Structuring argument lists for C functions
The C function's arguments will be all of the Scheme procedure's
argumements, both required and optional; if the Scheme procedure takes a
``rest'' argument, that will be a final argument to the C function. The
C function's arguments, as well as its return type, will be @code{SCM}.
@c @node Exceptions to the regularity
@c @section Exceptions to the regularity
@c
@c There are some exceptions to the regular structure described above.
@page
@node I/O Extensions
@chapter 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.
@end menu
@node C Port Interface
@section C Port Interface
This section describes how to use Scheme ports from C.
@subsection Port basics
There are two main data structures. A port type object (ptob) is of
type @code{scm_ptob_descriptor}. A port instance is of type
@code{scm_port}. Given an @code{SCM} variable which points to a port,
the corresponding C port object can be obtained using the
@code{SCM_PTAB_ENTRY} macro. The ptob can be obtained by using
@code{SCM_PTOBNUM} to give an index into the @code{scm_ptobs}
global array.
@subsection 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 @code{shortbuf} field in @code{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.
@subsection The @code{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
implemention must be given a chance to update its state. The write
buffer is updated by calling the @code{flush} ptob procedure and the
input buffer is updated by calling the @code{end_input} ptob procedure.
In the case of an fport, @code{flush} causes buffered output to be
written to the file descriptor, while @code{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 @code{rw_random} flag in
the port is non-zero.
@subsection The @code{rw_active} variable
The @code{rw_active} variable in the port is only used if
@code{rw_random} is set. It's defined as an enum with the following
values:
@table @code
@item SCM_PORT_READ
the read buffer may have unread data.
@item SCM_PORT_WRITE
the write buffer may have unwritten data.
@item SCM_PORT_NEITHER
neither the write nor the read buffer has data.
@end table
@subsection Reading from a port.
To read from a port, it's possible to either call existing libguile
procedures such as @code{scm_getc} and @code{scm_read_line} or to read
data from the read buffer directly. Reading from the buffer involves
the following steps:
@enumerate
@item
Flush output on the port, if @code{rw_active} is @code{SCM_PORT_WRITE}.
@item
Fill the read buffer, if it's empty, using @code{scm_fill_input}.
@item 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.
@item Set rw_active to @code{SCM_PORT_READ} if @code{rw_random} is set.
@item update the port's line and column counts.
@end enumerate
@subsection Writing to a port.
To write data to a port, calling @code{scm_lfwrite} should be sufficient for
most purposes. This takes care of the following steps:
@enumerate
@item
End input on the port, if @code{rw_active} is @code{SCM_PORT_READ}.
@item
Pass the data to the ptob implementation using the @code{write} ptob
procedure. The advantage of using the ptob @code{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
@code{shortbuf}.
@item
Set @code{rw_active} to @code{SCM_PORT_WRITE} if @code{rw_random}
is set.
@end enumerate
@node Port Implementation
@section 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 @code{scm_ptob_descriptor}. A ptob is created by
calling @code{scm_make_port_type}.
All of the elements of the ptob, apart from @code{name}, are procedures
which collectively implement the port behaviour. Creating a new port
type mostly involves writing these procedures.
@code{scm_make_port_type} initialises three elements of the structure
(@code{name}, @code{fill_input} and @code{write}) from its arguments.
The remaining elements are initialised with default values and can be
set later if required.
@table @code
@item name
A pointer to a NUL terminated string: the name of the port type. This
is the only element of @code{scm_ptob_descriptor} which is not
a procedure. Set via the first argument to @code{scm_make_port_type}.
@item 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
@code{SCM} components. Set using @code{scm_set_port_mark}.
@item free
Called when the port is collected during gc. It
should free any resources used by the port.
Set using @code{scm_set_port_free}.
@item print
Called when @code{write} is called on the port object, to print a
port description. e.g., for an fport it may produce something like:
@code{#<input: /etc/passwd 3>}. Set using @code{scm_set_port_print}.
@item equalp
Not used at present. Set using @code{scm_set_port_equalp}.
@item close
Called when the port is closed, unless it was collected during gc. It
should free any resources used by the port.
Set using @code{scm_set_port_close}.
@item 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 @code{scm_make_port_type}.
@item flush
Complete the processing of buffered output data. Reset the value of
@code{rw_active} to @code{SCM_PORT_NEITHER}.
Set using @code{scm_set_port_flush}.
@item end_input
Perform any synchronisation required when switching from input to output
on the port. Reset the value of @code{rw_active} to @code{SCM_PORT_NEITHER}.
Set using @code{scm_set_port_end_input}.
@item 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 @code{scm_make_port_type}.
@item 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
@code{rw_active} is @code{SCM_PORT_NEITHER}.
Set using @code{scm_set_port_input_waiting}.
@item seek
Set the current position of the port. The procedure can not make
any assumptions about the value of @code{rw_active} when it's
called. It can reset the buffers first if desired by using something
like:
@example
if (pt->rw_active == SCM_PORT_READ)
scm_end_input (object);
else if (pt->rw_active == SCM_PORT_WRITE)
ptob->flush (object);
@end example
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
@code{end_input} and @code{flush} ptob procedures. This is undesirable
when seek is called to measure the current position of the port, i.e.,
@code{(seek p 0 SEEK_CUR)}. The libguile fport and string port
implementations take care to avoid this problem.
The procedure is set using @code{scm_set_port_seek}.
@item truncate
Truncate the port data to be specified length. It can be assumed that the
current state of @code{rw_active} is @code{SCM_PORT_NEITHER}.
Set using @code{scm_set_port_truncate}.
@end table
@node Handling Errors
@chapter How to Handle Errors in C Code
Error handling is based on @code{catch} and @code{throw}. Errors are
always thrown with a @var{key} and four arguments:
@itemize @bullet
@item
@var{key}: a symbol which indicates the type of error. The symbols used
by libguile are listed below.
@item
@var{subr}: the name of the procedure from which the error is thrown, or
@code{#f}.
@item
@var{message}: a string (possibly language and system dependent)
describing the error. The tokens @code{~A} and @code{~S} can be
embedded within the message: they will be replaced with members of the
@var{args} list when the message is printed. @code{~A} indicates an
argument printed using @code{display}, while @code{~S} indicates an
argument printed using @code{write}. @var{message} can also be
@code{#f}, to allow it to be derived from the @var{key} by the error
handler (may be useful if the @var{key} is to be thrown from both C and
Scheme).
@item
@var{args}: a list of arguments to be used to expand @code{~A} and
@code{~S} tokens in @var{message}. Can also be @code{#f} if no
arguments are required.
@item
@var{rest}: a list of any additional objects required. e.g., when the
key is @code{'system-error}, this contains the C errno value. Can also
be @code{#f} if no additional objects are required.
@end itemize
In addition to @code{catch} and @code{throw}, the following Scheme
facilities are available:
@deffn primitive scm-error key subr message args rest
Throw an error, with arguments
as described above.
@end deffn
@deffn procedure error msg arg @dots{}
Throw an error using the key @code{'misc-error}. The error
message is created by displaying @var{msg} and writing the @var{args}.
@end deffn
The following are the error keys defined by libguile and the situations
in which they are used:
@itemize @bullet
@item
@code{error-signal}: thrown after receiving an unhandled fatal signal
such as SIGSEV, SIGBUS, SIGFPE etc. The @var{rest} argument in the throw
contains the coded signal number (at present this is not the same as the
usual Unix signal number).
@item
@code{system-error}: thrown after the operating system indicates an
error condition. The @var{rest} argument in the throw contains the
errno value.
@item
@code{numerical-overflow}: numerical overflow.
@item
@code{out-of-range}: the arguments to a procedure do not fall within the
accepted domain.
@item
@code{wrong-type-arg}: an argument to a procedure has the wrong thpe.
@item
@code{wrong-number-of-args}: a procedure was called with the wrong number
of arguments.
@item
@code{memory-allocation-error}: memory allocation error.
@item
@code{stack-overflow}: stack overflow error.
@item
@code{regex-error}: errors generated by the regular expression library.
@item
@code{misc-error}: other errors.
@end itemize
@section C Support
SCM scm_error (SCM key, char *subr, char *message, SCM args, SCM rest)
Throws an error, after converting the char * arguments to Scheme strings.
subr is the Scheme name of the procedure, NULL is converted to #f.
Likewise a NULL message is converted to #f.
The following procedures invoke scm_error with various error keys and
arguments. The first three call scm_error with the system-error key
and automatically supply errno in the "rest" argument: scm_syserror
generates messages using strerror, scm_sysmissing is used when
facilities are not available. Care should be taken that the errno
value is not reset (e.g. due to an interrupt).
@itemize @bullet
@item
void scm_syserror (char *subr);
@item
void scm_syserror_msg (char *subr, char *message, SCM args);
@item
void scm_sysmissing (char *subr);
@item
void scm_num_overflow (char *subr);
@item
void scm_out_of_range (char *subr, SCM bad_value);
@item
void scm_wrong_num_args (SCM proc);
@item
void scm_wrong_type_arg (char *subr, int pos, SCM bad_value);
@item
void scm_memory_error (char *subr);
@item
static void scm_regex_error (char *subr, int code); (only used in rgx.c).
@end itemize
Exception handlers can also be installed from C, using
scm_internal_catch, scm_lazy_catch, or scm_stack_catch from
libguile/throw.c. These have not yet been documented, however the
source contains some useful comments.

435
doc/ref/script-getopt.texi Normal file
View file

@ -0,0 +1,435 @@
@page
@node Command Line Handling
@chapter Handling Command Line Options and Arguments
@c This chapter was written and contributed by Martin Grabmueller.
The ability to accept and handle command line arguments is very
important when writing Guile scripts to solve particular problems, such
as extracting information from text files or interfacing with existing
command line applications. This chapter describes how Guile makes
command line arguments available to a Guile script, and the utilities
that Guile provides to help with the processing of command line
arguments.
@menu
* Command Line Args:: Using command line arguments.
* getopt-long:: The (ice-9 getopt-long) module.
@end menu
@node Command Line Args
@section Using Command Line Arguments
When a Guile script is invoked, Guile makes the command line arguments
accessible via the procedure @code{command-line}, which returns the
arguments as a list of strings.
For example, if the script
@example
#! /usr/local/bin/guile -s
!#
(write (command-line))
(newline)
@end example
@noindent
is saved in a file @file{cmdline-test.scm} and invoked using the command
line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}, the output
is
@example
("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")
@end example
If the script invocation includes a @code{-e} option, specifying a
procedure to call after loading the script, Guile will call that
procedure with @code{(command-line)} as its argument. So a script that
uses @code{-e} doesn't need to refer explicitly to @code{command-line}
in its code. For example, the script above would have identical
behaviour if it was written instead like this:
@example
#! /usr/local/bin/guile \
-e main -s
!#
(define (main args)
(write args)
(newline))
@end example
(Note the use of the meta switch @code{\} so that the script invocation
can include more than one Guile option: @xref{The Meta Switch}.)
These scripts use the @code{#!} POSIX convention so that they can be
executed using their own file names directly, as in the example command
line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}. But they
can also be executed by typing out the implied Guile command line in
full, as in:
@example
$ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob
@end example
@noindent
or
@example
$ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob
@end example
Even when a script is invoked using this longer form, the arguments that
the script receives are the same as if it had been invoked using the
short form. Guile ensures that the @code{(command-line)} or @code{-e}
arguments are independent of how the script is invoked, by stripping off
the arguments that Guile itself processes.
@node getopt-long
@section The (ice-9 getopt-long) Module
A script is free to parse and handle its command line arguments in any
way that it chooses. Where the set of possible options and arguments is
complex, however, it can get tricky to extract all the options, check
the validity of given arguments, and so on. This task can be greatly
simplified by taking advantage of the module @code{(ice-9 getopt-long)},
which is distributed with Guile.
The @code{(ice-9 getopt-long)} module exports two procedures:
@code{getopt-long} and @code{option-ref}.
@itemize @bullet
@item
@code{getopt-long} takes a list of strings --- the command line
arguments --- and an @dfn{option specification}. It parses the command
line arguments according to the option specification and returns a data
structure that encapsulates the results of the parsing.
@item
@code{option-ref} then takes the parsed data structure and a specific
option's name, and returns information about that option in particular.
@end itemize
To make these procedures available to your Guile script, include the
expression @code{(use-modules (ice-9 getopt-long))} somewhere near the
top, before the first usage of @code{getopt-long} or @code{option-ref}.
@menu
* getopt-long Example:: A short getopt-long example.
* Option Specification:: How to write an option specification.
* Command Line Format:: The expected command line format.
* getopt-long Reference:: Full documentation for @code{getopt-long}.
* option-ref Reference:: Full documentation for @code{option-ref}.
@end menu
@node getopt-long Example
@subsection A Short getopt-long Example
This subsection illustrates how @code{getopt-long} is used by presenting
and dissecting a simple example. The first thing that we need is an
@dfn{option specification} that tells @code{getopt-long} how to parse
the command line. This specification is an association list with the
long option name as the key. Here is how such a specification might
look:
@lisp
(define option-spec
'((version (single-char #\v) (value #f))
(help (single-char #\h) (value #f))))
@end lisp
This alist tells @code{getopt-long} that it should accept two long
options, called @emph{version} and @emph{help}, and that these options
can also be selected by the single-letter abbreviations @emph{v} and
@emph{h}, respectively. The @code{(value #f)} clauses indicate that
neither of the options accepts a value.
With this specification we can use @code{getopt-long} to parse a given
command line:
@lisp
(define options (getopt-long (command-line) option-spec))
@end lisp
After this call, @code{options} contains the parsed command line and is
ready to be examined by @code{option-ref}. @code{option-ref} is called
like this:
@lisp
(option-ref options 'help #f)
@end lisp
@noindent
It expects the parsed command line, a symbol indicating the option to
examine, and a default value. The default value is returned if the
option was not present in the command line, or if the option was present
but without a value; otherwise the value from the command line is
returned. Usually @code{option-ref} is called once for each possible
option that a script supports.
The following example shows a main program which puts all this together
to parse its command line and figure out what the user wanted.
@lisp
(define (main args)
(let* ((option-spec '((version (single-char #\v) (value #f))
(help (single-char #\h) (value #f))))
(options (getopt-long args option-spec))
(help-wanted (option-ref options 'help #f))
(version-wanted (option-ref options 'version #f)))
(if (or version-wanted help-wanted)
(begin
(if version-wanted
(display "getopt-long-example version 0.3\n"))
(if help-wanted
(display "\
getopt-long-example [options]
-v, --version Display version
-h, --help Display this help
")))
(begin
(display "Hello, World!") (newline)))))
@end lisp
@node Option Specification
@subsection How to Write an Option Specification
An option specification is an association list (@pxref{Association
Lists}) with one list element for each supported option. The key of each
list element is a symbol that names the option, while the value is a
list of option properties:
@lisp
OPTION-SPEC ::= '( (OPT-NAME1 (PROP-NAME PROP-VALUE) @dots{})
(OPT-NAME2 (PROP-NAME PROP-VALUE) @dots{})
(OPT-NAME3 (PROP-NAME PROP-VALUE) @dots{})
@dots{}
)
@end lisp
Each @var{opt-name} specifies the long option name for that option. For
example, a list element with @var{opt-name} @code{background} specifies
an option that can be specified on the command line using the long
option @code{--background}. Further information about the option ---
whether it takes a value, whether it is required to be present in the
command line, and so on --- is specified by the option properties.
In the example of the preceding subsection, we already saw that a long
option name can have a equivalent @dfn{short option} character. The
equivalent short option character can be set for an option by specifying
a @code{single-char} property in that option's property list. For
example, a list element like @code{'(output (single-char #\o) @dots{})}
specifies an option with long name @code{--output} that can also be
specified by the equivalent short name @code{-o}.
The @code{value} property specifies whether an option requires or
accepts a value. If the @code{value} property is set to @code{#t}, the
option requires a value: @code{getopt-long} will signal an error if the
option name is present without a corresponding value. If set to
@code{#f}, the option does not take a value; in this case, a non-option
word that follows the option name in the command line will be treated as
a non-option argument. If set to the symbol @code{optional}, the option
accepts a value but does not require one: a non-option word that follows
the option name in the command line will be interpreted as that option's
value. If the option name for an option with @code{'(value optional)}
is immediately followed in the command line by @emph{another} option
name, the value for the first option is implicitly @code{#t}.
The @code{required?} property indicates whether an option is required to
be present in the command line. If the @code{required?} property is
set to @code{#t}, @code{getopt-long} will signal an error if the option
is not specified.
Finally, the @code{predicate} property can be used to constrain the
possible values of an option. If used, the @code{predicate} property
should be set to a procedure that takes one argument --- the proposed
option value as a string --- and returns either @code{#t} or @code{#f}
according as the proposed value is or is not acceptable. If the
predicate procedure returns @code{#f}, @code{getopt-long} will signal an
error.
By default, options do not have single-character equivalents, are not
required, and do not take values. Where the list element for an option
includes a @code{value} property but no @code{predicate} property, the
option values are unconstrained.
@node Command Line Format
@subsection Expected Command Line Format
In order for @code{getopt-long} to correctly parse a command line, that
command line must conform to a standard set of rules for how command
line options are specified. This subsection explains what those rules
are.
@code{getopt-long} splits a given command line into several pieces. All
elements of the argument list are classified to be either options or
normal arguments. Options consist of two dashes and an option name
(so-called @dfn{long} options), or of one dash followed by a single
letter (@dfn{short} options).
Options can behave as switches, when they are given without a value, or
they can be used to pass a value to the program. The value for an
option may be specified using an equals sign, or else is simply the next
word in the command line, so the following two invocations are
equivalent:
@example
$ ./foo.scm --output=bar.txt
$ ./foo.scm --output bar.txt
@end example
Short options can be used instead of their long equivalents and can be
grouped together after a single dash. For example, the following
commands are equivalent.
@example
$ ./foo.scm --version --help
$ ./foo.scm -v --help
$ ./foo.scm -vh
@end example
If an option requires a value, it can only be grouped together with other
short options if it is the last option in the group; the value is the
next argument. So, for example, with the following option
specification ---
@lisp
((apples (single-char #\a))
(blimps (single-char #\b) (value #t))
(catalexis (single-char #\c) (value #t)))
@end lisp
@noindent
--- the following command lines would all be acceptable:
@example
$ ./foo.scm -a -b bang -c couth
$ ./foo.scm -ab bang -c couth
$ ./foo.scm -ac couth -b bang
@end example
But the next command line is an error, because @code{-b} is not the last
option in its combination, and because a group of short options cannot
include two options that both require values:
@example
$ ./foo.scm -abc couth bang
@end example
If an option's value is optional, @code{getopt-long} decides whether the
option has a value by looking at what follows it in the argument list.
If the next element is a string, and it does not appear to be an option
itself, then that string is the option's value.
If the option @code{--} appears in the argument list, argument parsing
stops there and subsequent arguments are returned as ordinary arguments,
even if they resemble options. So, with the command line
@example
$ ./foo.scm --apples "Granny Smith" -- --blimp Goodyear
@end example
@noindent
@code{getopt-long} will recognize the @code{--apples} option as having
the value "Granny Smith", but will not treat @code{--blimp} as an
option. The strings @code{--blimp} and @code{Goodyear} will be returned
as ordinary argument strings.
@node getopt-long Reference
@subsection Reference Documentation for @code{getopt-long}
@deffn procedure getopt-long args grammar
Parse the command line given in @var{args} (which must be a list of
strings) according to the option specification @var{grammar}.
The @var{grammar} argument is expected to be a list of this form:
@code{((@var{option} (@var{property} @var{value}) @dots{}) @dots{})}
where each @var{option} is a symbol denoting the long option, but
without the two leading dashes (e.g. @code{version} if the option is
called @code{--version}).
For each option, there may be list of arbitrarily many property/value
pairs. The order of the pairs is not important, but every property may
only appear once in the property list. The following table lists the
possible properties:
@table @asis
@item @code{(single-char @var{char})}
Accept @code{-@var{char}} as a single-character equivalent to
@code{--@var{option}}. This is how to specify traditional Unix-style
flags.
@item @code{(required? @var{bool})}
If @var{bool} is true, the option is required. @code{getopt-long} will
raise an error if it is not found in @var{args}.
@item @code{(value @var{bool})}
If @var{bool} is @code{#t}, the option accepts a value; if it is
@code{#f}, it does not; and if it is the symbol @code{optional}, the
option may appear in @var{args} with or without a value.
@item @code{(predicate @var{func})}
If the option accepts a value (i.e. you specified @code{(value #t)} for
this option), then @code{getopt-long} will apply @var{func} to the
value, and throw an exception if it returns @code{#f}. @var{func}
should be a procedure which accepts a string and returns a boolean
value; you may need to use quasiquotes to get it into @var{grammar}.
@end table
@end deffn
@code{getopt-long}'s @var{args} parameter is expected to be a list of
strings like the one returned by @code{command-line}, with the first
element being the name of the command. Therefore @code{getopt-long}
ignores the first element in @var{args} and starts argument
interpretation with the second element.
@code{getopt-long} signals an error if any of the following conditions
hold.
@itemize @bullet
@item
The option grammar has an invalid syntax.
@item
One of the options in the argument list was not specified by the
grammar.
@item
A required option is omitted.
@item
An option which requires an argument did not get one.
@item
An option that doesn't accept an argument does get one (this can only
happen using the long option @code{--opt=@var{value}} syntax).
@item
An option predicate fails.
@end itemize
@node option-ref Reference
@subsection Reference Documentation for @code{option-ref}
@deffn procedure option-ref options key default
Search @var{options} for a command line option named @var{key} and
return its value, if found. If the option has no value, but was given,
return @code{#t}. If the option was not given, return @var{default}.
@var{options} must be the result of a call to @code{getopt-long}.
@end deffn
@code{option-ref} always succeeds, either by returning the requested
option value from the command line, or the default value.
The special key @code{'()} can be used to get a list of all
non-option arguments.
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

213
doc/ref/scripts.texi Normal file
View file

@ -0,0 +1,213 @@
@page
@node Guile Scripting
@chapter Guile Scripting
Like AWK, Perl, or any shell, Guile can interpret script files. A Guile
script is simply a file of Scheme code with some extra information at
the beginning which tells the operating system how to invoke Guile, and
then tells Guile how to handle the Scheme code.
@menu
* Invoking Guile:: How to start a Guile script.
* The Meta Switch:: Passing complex argument lists to Guile
from shell scripts.
@end menu
@node Invoking Guile
@section Invoking Guile
Here we describe Guile's command-line processing in detail. Guile
processes its arguments from left to right, recognizing the switches
described below. For examples, see @ref{Scripting Examples}.
@table @code
@item -s @var{script} @var{arg...}
Read and evaluate Scheme source code from the file @var{script}, as the
@code{load} function would. After loading @var{script}, exit. Any
command-line arguments @var{arg...} following @var{script} become the
script's arguments; the @code{command-line} function returns a list of
strings of the form @code{(@var{script} @var{arg...})}.
@item -c @var{expr} @var{arg...}
Evaluate @var{expr} as Scheme code, and then exit. Any command-line
arguments @var{arg...} following @var{expr} become command-line arguments; the
@code{command-line} function returns a list of strings of the form
@code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
Guile executable.
@item -- @var{arg...}
Run interactively, prompting the user for expressions and evaluating
them. Any command-line arguments @var{arg...} following the @code{--}
become command-line arguments for the interactive session; the
@code{command-line} function returns a list of strings of the form
@code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
Guile executable.
@item -l @var{file}
Load Scheme source code from @var{file}, and continue processing the
command line.
@item -e @var{function}
Make @var{function} the @dfn{entry point} of the script. After loading
the script file (with @code{-s}) or evaluating the expression (with
@code{-c}), apply @var{function} to a list containing the program name
and the command-line arguments --- the list provided by the
@code{command-line} function.
A @code{-e} switch can appear anywhere in the argument list, but Guile
always invokes the @var{function} as the @emph{last} action it performs.
This is weird, but because of the way script invocation works under
POSIX, the @code{-s} option must always come last in the list.
@xref{Scripting Examples}.
@item -ds
Treat a final @code{-s} option as if it occurred at this point in the
command line; load the script here.
This switch is necessary because, although the POSIX script invocation
mechanism effectively requires the @code{-s} option to appear last, the
programmer may well want to run the script before other actions
requested on the command line. For examples, see @ref{Scripting
Examples}.
@item \
Read more command-line arguments, starting from the second line of the
script file. @xref{The Meta Switch}.
@item --emacs
Assume Guile is running as an inferior process of Emacs, and use a
special protocol to communicate with Emacs's Guile interaction mode.
This switch sets the global variable use-emacs-interface to @code{#t}.
This switch is still experimental.
@item --use-srfi=@var{list}
The option @code{--use-srfi} expects a comma-separated list of numbers,
each representing a SRFI number to be loaded into the interpreter
before starting evaluating a script file or the REPL. Additionally,
the feature identifier for the loaded SRFIs is recognized by
`cond-expand' when using this option.
@example
guile --use-srfi=8,13
@end example
@item -h@r{, }--help
Display help on invoking Guile, and then exit.
@item -v@r{, }--version
Display the current version of Guile, and then exit.
@end table
@node The Meta Switch
@section The Meta Switch
Guile's command-line switches allow the programmer to describe
reasonably complicated actions in scripts. Unfortunately, the POSIX
script invocation mechanism only allows one argument to appear on the
@samp{#!} line after the path to the Guile executable, and imposes
arbitrary limits on that argument's length. Suppose you wrote a script
starting like this:
@example
#!/usr/local/bin/guile -e main -s
!#
(define (main args)
(map (lambda (arg) (display arg) (display " "))
(cdr args))
(newline))
@end example
The intended meaning is clear: load the file, and then call @code{main}
on the command-line arguments. However, the system will treat
everything after the Guile path as a single argument --- the string
@code{"-e main -s"} --- which is not what we want.
As a workaround, the meta switch @code{\} allows the Guile programmer to
specify an arbitrary number of options without patching the kernel. If
the first argument to Guile is @code{\}, Guile will open the script file
whose name follows the @code{\}, parse arguments starting from the
file's second line (according to rules described below), and substitute
them for the @code{\} switch.
Working in concert with the meta switch, Guile treats the characters
@samp{#!} as the beginning of a comment which extends through the next
line containing only the characters @samp{!#}. This sort of comment may
appear anywhere in a Guile program, but it is most useful at the top of
a file, meshing magically with the POSIX script invocation mechanism.
Thus, consider a script named @file{/u/jimb/ekko} which starts like this:
@example
#!/usr/local/bin/guile \
-e main -s
!#
(define (main args)
(map (lambda (arg) (display arg) (display " "))
(cdr args))
(newline))
@end example
Suppose a user invokes this script as follows:
@example
$ /u/jimb/ekko a b c
@end example
Here's what happens:
@itemize @bullet
@item
the operating system recognizes the @samp{#!} token at the top of the
file, and rewrites the command line to:
@example
/usr/local/bin/guile \ /u/jimb/ekko a b c
@end example
This is the usual behavior, prescribed by POSIX.
@item
When Guile sees the first two arguments, @code{\ /u/jimb/ekko}, it opens
@file{/u/jimb/ekko}, parses the three arguments @code{-e}, @code{main},
and @code{-s} from it, and substitutes them for the @code{\} switch.
Thus, Guile's command line now reads:
@example
/usr/local/bin/guile -e main -s /u/jimb/ekko a b c
@end example
@item
Guile then processes these switches: it loads @file{/u/jimb/ekko} as a
file of Scheme code (treating the first three lines as a comment), and
then performs the application @code{(main "/u/jimb/ekko" "a" "b" "c")}.
@end itemize
When Guile sees the meta switch @code{\}, it parses command-line
argument from the script file according to the following rules:
@itemize @bullet
@item
Each space character terminates an argument. This means that two
spaces in a row introduce an argument @code{""}.
@item
The tab character is not permitted (unless you quote it with the
backslash character, as described below), to avoid confusion.
@item
The newline character terminates the sequence of arguments, and will
also terminate a final non-empty argument. (However, a newline
following a space will not introduce a final empty-string argument;
it only terminates the argument list.)
@item
The backslash character is the escape character. It escapes backslash,
space, tab, and newline. The ANSI C escape sequences like @code{\n} and
@code{\t} are also supported. These produce argument constituents; the
two-character combination @code{\n} doesn't act like a terminating
newline. The escape sequence @code{\@var{NNN}} for exactly three octal
digits reads as the character whose ASCII code is @var{NNN}. As above,
characters produced this way are argument constituents. Backslash
followed by other characters is not allowed.
@end itemize

25
doc/ref/scsh.texi Normal file
View file

@ -0,0 +1,25 @@
@page
@node The Scheme shell (scsh)
@chapter The Scheme shell (scsh)
An incomplete port of the Scheme shell (scsh) 0.5.1 is available for
Guile. The idea is to allow Scheme code using scsh interfaces to be run
inside the Guile interpreter.
For information about scsh on the Web see
@url{http://www-swiss.ai.mit.edu/scsh/scsh.html}.
The original scsh is available by ftp from
@url{ftp://swiss-ftp.ai.mit.edu:/pub/su}.
The scsh code is distributed as a separate module, guile-scsh,
which must be installed somewhere in Guile's load path before
it can be used. This is similar to the installation
of slib (you may want to install that first, since it's needed before
scsh can run in Guile: see @ref{SLIB} for details).
This port of scsh does not currently use the Guile module system, but
can be initialized with:
@smalllisp
(load-from-path "scsh/init")
@end smalllisp

105
doc/ref/slib.texi Normal file
View file

@ -0,0 +1,105 @@
@page
@node SLIB
@chapter SLIB
Before the the SLIB facilities can be used, the following Scheme
expression must be executed:
@smalllisp
(use-modules (ice-9 slib))
@end smalllisp
@code{require} can then be used as described in
@ref{Top, , SLIB, slib, The SLIB Manual}.
For example:
@smalllisp
guile> (use-modules (ice-9 slib))
guile> (require 'primes)
guile> (probably-prime? 13)
@end smalllisp
@menu
* SLIB installation::
* JACAL::
@end menu
@node SLIB installation
@section SLIB installation
The following seems to work, at least with slib 2c7:
@enumerate
@item
Unpack slib somewhere, e.g., /usr/local/lib/slib.
@item
Create a symlink in the Guile site directory to slib, e.g.,:
@example
ln -s /usr/local/lib/slib /usr/local/share/guile/site/slib
@end example
@item
Use Guile to create the catalogue file, e.g.,:
@example
# guile
guile> (use-modules (ice-9 slib))
guile> (load "/usr/local/lib/slib/mklibcat.scm")
guile> (quit)
@end example
The catalogue data should now be in
@code{/usr/local/share/guile/site/slibcat}.
If instead you get an error such as:
@example
Unbound variable: scheme-implementation-type
@end example
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.
@item
Install the documentation:
@example
cd /usr/local/lib/slib
rm /usr/local/info/slib.info*
cp slib.info /usr/local/info
install-info slib.info /usr/local/info/dir
@end example
@end enumerate
@node JACAL
@section JACAL
@cindex Jaffer, Aubrey
@cindex symbolic math
@cindex math -- symbolic
Jacal is a symbolic math package written in Scheme by Aubrey Jaffer. It
is usually installed as an extra package in SLIB (@pxref{Packages not
shipped with Guile}).
You can use Guile's interface to SLIB to invoke Jacal:
@smalllisp
(use-modules (ice-9 slib))
(slib:load "math")
(math)
@end smalllisp
@noindent
For complete documentation on Jacal, please read the Jacal manual. If
it has been installed on line, you can look at @ref{Top, , Jacal, jacal,
The SLIB Manual}. Otherwise you can find it on the web at
@url{http://www-swiss.ai.mit.edu/~jaffer/JACAL.html}
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

2241
doc/ref/srfi-modules.texi Normal file

File diff suppressed because it is too large Load diff

3
doc/ref/tcltk.texi Normal file
View file

@ -0,0 +1,3 @@
@page
@node Tcl/Tk Interface
@chapter Tcl/Tk Interface

View file

View file

View file

View file

View file

View file

View file

View file

View file

View file

View file

View file

View file

@ -47,7 +47,7 @@ Copyright @copyright{} 1999 Free Software Foundation, Inc.
@chapter Motivation
@example
$Id: env.texi,v 1.2 2001-04-22 14:56:52 ossau Exp $
$Id: env.texi,v 1.1 2001-08-24 09:40:29 ossau Exp $
@end example
This is a draft proposal for a new datatype for representing top-level

434
doc/sources/format.texi Normal file
View file

@ -0,0 +1,434 @@
@menu
* Format Interface::
* Format Specification::
@end menu
@node Format Interface, Format Specification, Format, Format
@subsection Format Interface
@defun format destination format-string . arguments
An almost complete implementation of Common LISP format description
according to the CL reference book @cite{Common LISP} from Guy L.
Steele, Digital Press. Backward compatible to most of the available
Scheme format implementations.
Returns @code{#t}, @code{#f} or a string; has side effect of printing
according to @var{format-string}. If @var{destination} is @code{#t},
the output is to the current output port and @code{#t} is returned. If
@var{destination} is @code{#f}, a formatted string is returned as the
result of the call. NEW: If @var{destination} is a string,
@var{destination} is regarded as the format string; @var{format-string} is
then the first argument and the output is returned as a string. If
@var{destination} is a number, the output is to the current error port
if available by the implementation. Otherwise @var{destination} must be
an output port and @code{#t} is returned.@refill
@var{format-string} must be a string. In case of a formatting error
format returns @code{#f} and prints a message on the current output or
error port. Characters are output as if the string were output by the
@code{display} function with the exception of those prefixed by a tilde
(~). For a detailed description of the @var{format-string} syntax
please consult a Common LISP format reference manual. For a test suite
to verify this format implementation load @file{formatst.scm}. Please
send bug reports to @code{lutzeb@@cs.tu-berlin.de}.
Note: @code{format} is not reentrant, i.e. only one @code{format}-call
may be executed at a time.
@end defun
@node Format Specification, , Format Interface, Format
@subsection Format Specification (Format version 3.0)
Please consult a Common LISP format reference manual for a detailed
description of the format string syntax. For a demonstration of the
implemented directives see @file{formatst.scm}.@refill
This implementation supports directive parameters and modifiers
(@code{:} and @code{@@} characters). Multiple parameters must be
separated by a comma (@code{,}). Parameters can be numerical parameters
(positive or negative), character parameters (prefixed by a quote
character (@code{'}), variable parameters (@code{v}), number of rest
arguments parameter (@code{#}), empty and default parameters. Directive
characters are case independent. The general form of a directive
is:@refill
@noindent
@var{directive} ::= ~@{@var{directive-parameter},@}[:][@@]@var{directive-character}
@noindent
@var{directive-parameter} ::= [ [-|+]@{0-9@}+ | '@var{character} | v | # ]
@subsubsection Implemented CL Format Control Directives
Documentation syntax: Uppercase characters represent the corresponding
control directive characters. Lowercase characters represent control
directive parameter descriptions.
@table @asis
@item @code{~A}
Any (print as @code{display} does).
@table @asis
@item @code{~@@A}
left pad.
@item @code{~@var{mincol},@var{colinc},@var{minpad},@var{padchar}A}
full padding.
@end table
@item @code{~S}
S-expression (print as @code{write} does).
@table @asis
@item @code{~@@S}
left pad.
@item @code{~@var{mincol},@var{colinc},@var{minpad},@var{padchar}S}
full padding.
@end table
@item @code{~D}
Decimal.
@table @asis
@item @code{~@@D}
print number sign always.
@item @code{~:D}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar}D}
padding.
@end table
@item @code{~X}
Hexadecimal.
@table @asis
@item @code{~@@X}
print number sign always.
@item @code{~:X}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar}X}
padding.
@end table
@item @code{~O}
Octal.
@table @asis
@item @code{~@@O}
print number sign always.
@item @code{~:O}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar}O}
padding.
@end table
@item @code{~B}
Binary.
@table @asis
@item @code{~@@B}
print number sign always.
@item @code{~:B}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar}B}
padding.
@end table
@item @code{~@var{n}R}
Radix @var{n}.
@table @asis
@item @code{~@var{n},@var{mincol},@var{padchar},@var{commachar}R}
padding.
@end table
@item @code{~@@R}
print a number as a Roman numeral.
@item @code{~:@@R}
print a number as an ``old fashioned'' Roman numeral.
@item @code{~:R}
print a number as an ordinal English number.
@item @code{~:@@R}
print a number as a cardinal English number.
@item @code{~P}
Plural.
@table @asis
@item @code{~@@P}
prints @code{y} and @code{ies}.
@item @code{~:P}
as @code{~P but jumps 1 argument backward.}
@item @code{~:@@P}
as @code{~@@P but jumps 1 argument backward.}
@end table
@item @code{~C}
Character.
@table @asis
@item @code{~@@C}
prints a character as the reader can understand it (i.e. @code{#\} prefixing).
@item @code{~:C}
prints a character as emacs does (eg. @code{^C} for ASCII 03).
@end table
@item @code{~F}
Fixed-format floating-point (prints a flonum like @var{mmm.nnn}).
@table @asis
@item @code{~@var{width},@var{digits},@var{scale},@var{overflowchar},@var{padchar}F}
@item @code{~@@F}
If the number is positive a plus sign is printed.
@end table
@item @code{~E}
Exponential floating-point (prints a flonum like @var{mmm.nnn}@code{E}@var{ee}).
@table @asis
@item @code{~@var{width},@var{digits},@var{exponentdigits},@var{scale},@var{overflowchar},@var{padchar},@var{exponentchar}E}
@item @code{~@@E}
If the number is positive a plus sign is printed.
@end table
@item @code{~G}
General floating-point (prints a flonum either fixed or exponential).
@table @asis
@item @code{~@var{width},@var{digits},@var{exponentdigits},@var{scale},@var{overflowchar},@var{padchar},@var{exponentchar}G}
@item @code{~@@G}
If the number is positive a plus sign is printed.
@end table
@item @code{~$}
Dollars floating-point (prints a flonum in fixed with signs separated).
@table @asis
@item @code{~@var{digits},@var{scale},@var{width},@var{padchar}$}
@item @code{~@@$}
If the number is positive a plus sign is printed.
@item @code{~:@@$}
A sign is always printed and appears before the padding.
@item @code{~:$}
The sign appears before the padding.
@end table
@item @code{~%}
Newline.
@table @asis
@item @code{~@var{n}%}
print @var{n} newlines.
@end table
@item @code{~&}
print newline if not at the beginning of the output line.
@table @asis
@item @code{~@var{n}&}
prints @code{~&} and then @var{n-1} newlines.
@end table
@item @code{~|}
Page Separator.
@table @asis
@item @code{~@var{n}|}
print @var{n} page separators.
@end table
@item @code{~~}
Tilde.
@table @asis
@item @code{~@var{n}~}
print @var{n} tildes.
@end table
@item @code{~}<newline>
Continuation Line.
@table @asis
@item @code{~:}<newline>
newline is ignored, white space left.
@item @code{~@@}<newline>
newline is left, white space ignored.
@end table
@item @code{~T}
Tabulation.
@table @asis
@item @code{~@@T}
relative tabulation.
@item @code{~@var{colnum,colinc}T}
full tabulation.
@end table
@item @code{~?}
Indirection (expects indirect arguments as a list).
@table @asis
@item @code{~@@?}
extracts indirect arguments from format arguments.
@end table
@item @code{~(@var{str}~)}
Case conversion (converts by @code{string-downcase}).
@table @asis
@item @code{~:(@var{str}~)}
converts by @code{string-capitalize}.
@item @code{~@@(@var{str}~)}
converts by @code{string-capitalize-first}.
@item @code{~:@@(@var{str}~)}
converts by @code{string-upcase}.
@end table
@item @code{~*}
Argument Jumping (jumps 1 argument forward).
@table @asis
@item @code{~@var{n}*}
jumps @var{n} arguments forward.
@item @code{~:*}
jumps 1 argument backward.
@item @code{~@var{n}:*}
jumps @var{n} arguments backward.
@item @code{~@@*}
jumps to the 0th argument.
@item @code{~@var{n}@@*}
jumps to the @var{n}th argument (beginning from 0)
@end table
@item @code{~[@var{str0}~;@var{str1}~;...~;@var{strn}~]}
Conditional Expression (numerical clause conditional).
@table @asis
@item @code{~@var{n}[}
take argument from @var{n}.
@item @code{~@@[}
true test conditional.
@item @code{~:[}
if-else-then conditional.
@item @code{~;}
clause separator.
@item @code{~:;}
default clause follows.
@end table
@item @code{~@{@var{str}~@}}
Iteration (args come from the next argument (a list)).
@table @asis
@item @code{~@var{n}@{}
at most @var{n} iterations.
@item @code{~:@{}
args from next arg (a list of lists).
@item @code{~@@@{}
args from the rest of arguments.
@item @code{~:@@@{}
args from the rest args (lists).
@end table
@item @code{~^}
Up and out.
@table @asis
@item @code{~@var{n}^}
aborts if @var{n} = 0
@item @code{~@var{n},@var{m}^}
aborts if @var{n} = @var{m}
@item @code{~@var{n},@var{m},@var{k}^}
aborts if @var{n} <= @var{m} <= @var{k}
@end table
@end table
@subsubsection Not Implemented CL Format Control Directives
@table @asis
@item @code{~:A}
print @code{#f} as an empty list (see below).
@item @code{~:S}
print @code{#f} as an empty list (see below).
@item @code{~<~>}
Justification.
@item @code{~:^}
(sorry I don't understand its semantics completely)
@end table
@subsubsection Extended, Replaced and Additional Control Directives
@table @asis
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}D}
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}X}
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}O}
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}B}
@item @code{~@var{n},@var{mincol},@var{padchar},@var{commachar},@var{commawidth}R}
@var{commawidth} is the number of characters between two comma characters.
@end table
@table @asis
@item @code{~I}
print an R5RS complex number as @code{~F~@@Fi} with passed parameters for
@code{~F}.
@item @code{~Y}
Pretty print formatting of an argument for scheme code lists.
@item @code{~K}
Same as @code{~?.}
@item @code{~!}
Flushes the output if format @var{destination} is a port.
@item @code{~_}
Print a @code{#\space} character
@table @asis
@item @code{~@var{n}_}
print @var{n} @code{#\space} characters.
@end table
@item @code{~/}
Print a @code{#\tab} character
@table @asis
@item @code{~@var{n}/}
print @var{n} @code{#\tab} characters.
@end table
@item @code{~@var{n}C}
Takes @var{n} as an integer representation for a character. No arguments
are consumed. @var{n} is converted to a character by
@code{integer->char}. @var{n} must be a positive decimal number.@refill
@item @code{~:S}
Print out readproof. Prints out internal objects represented as
@code{#<...>} as strings @code{"#<...>"} so that the format output can always
be processed by @code{read}.
@refill
@item @code{~:A}
Print out readproof. Prints out internal objects represented as
@code{#<...>} as strings @code{"#<...>"} so that the format output can always
be processed by @code{read}.
@item @code{~Q}
Prints information and a copyright notice on the format implementation.
@table @asis
@item @code{~:Q}
prints format version.
@end table
@refill
@item @code{~F, ~E, ~G, ~$}
may also print number strings, i.e. passing a number as a string and
format it accordingly.
@end table
@subsubsection Configuration Variables
Format has some configuration variables at the beginning of
@file{format.scm} to suit the systems and users needs. There should be
no modification necessary for the configuration that comes with SLIB.
If modification is desired the variable should be set after the format
code is loaded. Format detects automatically if the running scheme
system implements floating point numbers and complex numbers.
@table @asis
@item @var{format:symbol-case-conv}
Symbols are converted by @code{symbol->string} so the case type of the
printed symbols is implementation dependent.
@code{format:symbol-case-conv} is a one arg closure which is either
@code{#f} (no conversion), @code{string-upcase}, @code{string-downcase}
or @code{string-capitalize}. (default @code{#f})
@item @var{format:iobj-case-conv}
As @var{format:symbol-case-conv} but applies for the representation of
implementation internal objects. (default @code{#f})
@item @var{format:expch}
The character prefixing the exponent value in @code{~E} printing. (default
@code{#\E})
@end table
@subsubsection Compatibility With Other Format Implementations
@table @asis
@item SLIB format 2.x:
See @file{format.doc}.
@item SLIB format 1.4:
Downward compatible except for padding support and @code{~A}, @code{~S},
@code{~P}, @code{~X} uppercase printing. SLIB format 1.4 uses C-style
@code{printf} padding support which is completely replaced by the CL
@code{format} padding style.
@item MIT C-Scheme 7.1:
Downward compatible except for @code{~}, which is not documented
(ignores all characters inside the format string up to a newline
character). (7.1 implements @code{~a}, @code{~s},
~@var{newline}, @code{~~}, @code{~%}, numerical and variable
parameters and @code{:/@@} modifiers in the CL sense).@refill
@item Elk 1.5/2.0:
Downward compatible except for @code{~A} and @code{~S} which print in
uppercase. (Elk implements @code{~a}, @code{~s}, @code{~~}, and
@code{~%} (no directive parameters or modifiers)).@refill
@item Scheme->C 01nov91:
Downward compatible except for an optional destination parameter: S2C
accepts a format call without a destination which returns a formatted
string. This is equivalent to a #f destination in S2C. (S2C implements
@code{~a}, @code{~s}, @code{~c}, @code{~%}, and @code{~~} (no directive
parameters or modifiers)).@refill
@end table
This implementation of format is solely useful in the SLIB context
because it requires other components provided by SLIB.@refill

View file

View file

23
doc/tutorial/.cvsignore Normal file
View file

@ -0,0 +1,23 @@
Makefile
Makefile.in
stamp-vti
stamp-vti.1
*.log
*.dvi
*.aux
*.toc
*.cp
*.fn
*.vr
*.tp
*.ky
*.pg
*.cps
*.fns
*.tps
*.vrs
*.ps
*.info*
*.html
version.texi
version-tutorial.texi

View file

@ -0,0 +1,16 @@
2001-01-27 Neil Jerram <neil@ossau.uklinux.net>
* texinfo.tex: Replaced by latest version from ftp.gnu.org.
1999-12-06 Gary Houston <ghouston@freewire.co.uk>
* guile-tut.texi: tweaked the dircategory.
1998-01-28 Mark Galassi <rosalia@nis.lanl.gov>
* guile-tut.texi: set @dircategory to "Scheme Programming".
Mon Aug 18 16:11:43 1997 Jim Blandy <jimb@totoro.red-bean.com>
* texinfo.tex: Installed from texinfo release 3.11.

1334
doc/tutorial/guile-tut.texi Normal file

File diff suppressed because it is too large Load diff