diff options
48 files changed, 2731 insertions, 13010 deletions
diff --git a/doc/ref/ChangeLog b/doc/ref/ChangeLog index 2d6b2d84d..97262f805 100644 --- a/doc/ref/ChangeLog +++ b/doc/ref/ChangeLog @@ -1,3 +1,8 @@ +2004-04-21 Marius Vollmer <marius.vollmer@uni-dortmund.de> + + * Big reorganization of the whole manual to give it a simpler + structure. + 2004-03-25 Kevin Ryde <user42@zip.com.au> * slib.texi (SLIB): Amend `require' cross reference node name, is diff --git a/doc/ref/Makefile.am b/doc/ref/Makefile.am index ccadaa389..2663a3413 100644 --- a/doc/ref/Makefile.am +++ b/doc/ref/Makefile.am @@ -23,18 +23,28 @@ AUTOMAKE_OPTIONS = gnu info_TEXINFOS = guile.texi -guile_TEXINFOS = preface.texi intro.texi program.texi scheme-intro.texi \ - scheme-ideas.texi scheme-data.texi scheme-procedures.texi \ - scheme-utility.texi scheme-binding.texi scheme-control.texi \ - scheme-io.texi scheme-evaluation.texi scheme-memory.texi \ - scheme-modules.texi scheme-scheduling.texi scheme-options.texi \ - scheme-translation.texi scheme-debug.texi deprecated.texi \ - scheme-reading.texi scheme-indices.texi slib.texi posix.texi \ - expect.texi scsh.texi tcltk.texi scripts.texi gh.texi scm.texi \ - debugging.texi indices.texi script-getopt.texi data-rep.texi \ - extend.texi repl-modules.texi srfi-modules.texi misc-modules.texi \ +guile_TEXINFOS = preface.texi intro.texi program.texi \ + scheme-intro.texi scheme-scm.texi scheme-snarf.texi \ + scheme-smobs.texi \ + scheme-ideas.texi scheme-data.texi scheme-procedures.texi \ + scheme-utility.texi scheme-binding.texi scheme-control.texi \ + scheme-io.texi scheme-evaluation.texi scheme-memory.texi \ + scheme-modules.texi scheme-scheduling.texi scheme-options.texi \ + scheme-translation.texi scheme-debug.texi deprecated.texi \ + scheme-reading.texi scheme-indices.texi slib.texi posix.texi \ + expect.texi scsh.texi tcltk.texi scripts.texi gh.texi scm.texi \ + debugging.texi indices.texi script-getopt.texi data-rep.texi \ + repl-modules.texi srfi-modules.texi \ + misc-modules.texi \ scheme-compound.texi autoconf.texi autoconf-macros.texi tools.texi \ - fdl.texi + fdl.texi \ + libguile-concepts.texi \ + libguile-smobs.texi \ + libguile-snarf.texi \ + libguile-linking.texi \ + libguile-extensions.texi \ + ref-init.texi \ + mod-getopt-long.texi ETAGS_ARGS = $(info_TEXINFOS) $(guile_TEXINFOS) diff --git a/doc/ref/data-rep.texi b/doc/ref/data-rep.texi index 5095044fd..3dc3fd70c 100644 --- a/doc/ref/data-rep.texi +++ b/doc/ref/data-rep.texi @@ -52,7 +52,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.16 2004-01-21 22:40:39 mvo Exp $ +@c essay @subtitle $Id: data-rep.texi,v 1.17 2004-04-21 14:32:08 mvo Exp $ @c essay @subtitle For use with Guile @value{VERSION} @c essay @author Jim Blandy @c essay @author Free Software Foundation @@ -103,9 +103,8 @@ @c essay @end ifinfo -@page @node Data Representation -@chapter Data Representation in Guile +@appendix Data Representation in Guile @strong{by Jim Blandy} @@ -132,8 +131,6 @@ familiar with Guile's implementation. * How Guile does it:: How to write C code that manipulates Guile values, with an explanation of Guile's garbage collector. -* Defining New Types (Smobs):: How to extend Guile with your own - application-specific datatypes. @end menu @node Data Representation in Scheme @@ -1058,25 +1055,8 @@ and further information about the object in question is stored in that cell. This section describes how the @code{SCM} type is actually represented and used at the C level. -In fact, there are two basic C data types to represent objects in Guile: - -@deftp {Data type} SCM -@code{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 @code{SCM}, so you should only use macros and functions to work -with @code{SCM} values. Values are converted between C data types and -the @code{SCM} type with utility functions and macros. -@end deftp -@cindex SCM data type - -@deftp {Data type} scm_t_bits -@code{scm_t_bits} is 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 mostly used to implement Guile's -internals, the use of this type is also necessary to write certain kinds -of extensions to Guile. -@end deftp +In fact, there are two basic C data types to represent objects in +Guile: @code{SCM} and @code{scm_t_bits}. @menu * Relationship between SCM and scm_t_bits:: @@ -1110,18 +1090,6 @@ chapter (@pxref{Cheaper Pairs}). Conversely, a valid bit encoding of a Scheme value as a @code{scm_t_bits} variable can be transformed into the corresponding @code{SCM} value using the @code{SCM_PACK} macro. -@deftypefn Macro scm_t_bits SCM_UNPACK (SCM @var{x}) -Transforms the @code{SCM} value @var{x} into its representation as an -integral type. Only after applying @code{SCM_UNPACK} it is possible to -access the bits and contents of the @code{SCM} value. -@end deftypefn - -@deftypefn Macro SCM SCM_PACK (scm_t_bits @var{x}) -Takes a valid integral representation of a Scheme object and transforms -it into its representation as a @code{SCM} value. -@end deftypefn - - @node Immediate objects @subsubsection Immediate objects @@ -1378,742 +1346,3 @@ Scheme value and thus the first cell entry must be accessed using the @end deftypefn -@node Defining New Types (Smobs) -@section Defining New Types (Smobs) - -@dfn{Smobs} are Guile's mechanism for adding new non-immediate types to -the system.@footnote{The term ``smob'' was coined by Aubrey Jaffer, who -says it comes from ``small object'', referring to the fact that only the -@sc{cdr} and part of the @sc{car} of a smob's cell are available for -use.} To define a new smob type, the programmer provides Guile with -some essential information about the type --- how to print it, how to -garbage collect it, and so on --- and Guile returns a fresh type tag for -use in the first word of new cells. The programmer can then use -@code{scm_c_define_gsubr} to make a set of C functions that create and -operate on these objects visible to Scheme code. - -(You can find a complete version of the example code used in this -section in the Guile distribution, in @file{doc/example-smob}. That -directory includes a makefile and a suitable @code{main} function, so -you can build a complete interactive Guile shell, extended with the -datatypes described here.) - -@menu -* Describing a New Type:: -* Creating Instances:: -* Type checking:: -* Garbage Collecting Smobs:: -* A Common Mistake In Allocating Smobs:: -* Garbage Collecting Simple Smobs:: -* Remembering During Operations:: -* A Complete Example:: -@end menu - -@node Describing a New Type -@subsection Describing a New Type - -To define a new type, the programmer must write four functions to -manage instances of the type: - -@table @code -@item mark -Guile will apply this function to each instance of the new type it -encounters during garbage collection. This function is responsible for -telling the collector about any other non-immediate objects the object -refers to. The default smob mark function is to not mark any data. -@xref{Garbage Collecting Smobs}, for more details. - -@item free -Guile will apply this function to each instance of the new type it could -not find any live pointers to. The function should release all -resources held by the object and return the number of bytes released. -This is analogous to the Java finalization method-- it is invoked at -an unspecified time (when garbage collection occurs) after the object -is dead. The default free function frees the smob data (if the size -of the struct passed to @code{scm_make_smob_type} is non-zero) using -@code{scm_gc_free}. @xref{Garbage Collecting Smobs}, for more -details. - -@item print -@c GJB:FIXME:: @var{exp} and @var{port} need to refer to a prototype of -@c the print function.... where is that, or where should it go? -Guile will apply this function to each instance of the new type to print -the value, as for @code{display} or @code{write}. The function should -write a printed representation of @var{exp} on @var{port}, in accordance -with the parameters in @var{pstate}. (For more information on print -states, see @ref{Port Data}.) The default print function prints -@code{#<NAME ADDRESS>} where @code{NAME} is the first argument passed to -@code{scm_make_smob_type}. - -@item equalp -If Scheme code asks the @code{equal?} function to compare two instances -of the same smob type, Guile calls this function. It should return -@code{SCM_BOOL_T} if @var{a} and @var{b} should be considered -@code{equal?}, or @code{SCM_BOOL_F} otherwise. If @code{equalp} is -@code{NULL}, @code{equal?} will assume that two instances of this type are -never @code{equal?} unless they are @code{eq?}. - -@end table - -To actually register the new smob type, call @code{scm_make_smob_type}: - -@deftypefun scm_t_bits scm_make_smob_type (const char *name, size_t size) -This function implements the standard way of adding a new smob type, -named @var{name}, with instance size @var{size}, to the system. The -return value is a tag that is used in creating instances of the type. -If @var{size} is 0, then no memory will be allocated when instances of -the smob are created, and nothing will be freed by the default free -function. Default values are provided for mark, free, print, and, -equalp, as described above. If you want to customize any of these -functions, the call to @code{scm_make_smob_type} should be immediately -followed by calls to one or several of @code{scm_set_smob_mark}, -@code{scm_set_smob_free}, @code{scm_set_smob_print}, and/or -@code{scm_set_smob_equalp}. -@end deftypefun - -Each of the below @code{scm_set_smob_XXX} functions registers a smob -special function for a given type. Each function is intended to be used -only zero or one time per type, and the call should be placed -immediately following the call to @code{scm_make_smob_type}. - -@deftypefun void scm_set_smob_mark (scm_t_bits tc, SCM (*mark) (SCM)) -This function sets the smob marking procedure for the smob type specified by -the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}. -@end deftypefun - -@deftypefun void scm_set_smob_free (scm_t_bits tc, size_t (*free) (SCM)) -This function sets the smob freeing procedure for the smob type specified by -the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}. -@end deftypefun - -@deftypefun void scm_set_smob_print (scm_t_bits tc, int (*print) (SCM, SCM, scm_print_state*)) -This function sets the smob printing procedure for the smob type specified by -the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}. -@end deftypefun - -@deftypefun void scm_set_smob_equalp (scm_t_bits tc, SCM (*equalp) (SCM, SCM)) -This function sets the smob equality-testing predicate for the smob type specified by -the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}. -@end deftypefun - -In versions 1.4 and earlier, there was another way of creating smob -types, using @code{scm_make_smob_type_mfpe}. This function is now -deprecated and will be removed in a future version of Guile. You should -use the mechanism described above for new code, and change old code not -to use deprecated features. - -@deftypefun long scm_make_smob_type_mfpe (const char *name, size_t size, SCM (*mark) (SCM), size_t (*free) (SCM), int (*print) (SCM, SCM, scm_print_state*), SCM (*equalp) (SCM, SCM)) -This function invokes @code{scm_make_smob_type} on its first two arguments -to add a new smob type named @var{name}, with instance size @var{size} to the system. -It also registers the @var{mark}, @var{free}, @var{print}, @var{equalp} smob -special functions for that new type. Any of these parameters can be @code{NULL} -to have that special function use the default behavior for guile. -The return value is a tag that is used in creating instances of the type. If @var{size} -is 0, then no memory will be allocated when instances of the smob are created, and -nothing will be freed by the default free function. - -@emph{This function is deprecated} -@end deftypefun - -For example, here is how one might declare and register a new type -representing eight-bit gray-scale images: - -@example -#include <libguile.h> - -static scm_t_bits image_tag; - -void -init_image_type (void) -@{ - image_tag = scm_make_smob_type ("image", sizeof (struct image)); - scm_set_smob_mark (image_tag, mark_image); - scm_set_smob_free (image_tag, free_image); - scm_set_smob_print (image_tag, print_image); -@} -@end example - - -@node Creating Instances -@subsection Creating Instances - -Like other non-immediate types, smobs start with a cell whose first word -contains typing information, and whose remaining words are free for any -use. - -After the header word containing the type code, smobs can have either -one, two or three additional words of data. These words store either a -pointer to the internal C structure holding the smob-specific data, or -the smob data itself. To create an instance of a smob type following -these standards, you should use @code{SCM_NEWSMOB}, @code{SCM_NEWSMOB2} -or @code{SCM_NEWSMOB3}:@footnote{The @code{SCM_NEWSMOB2} and -@code{SCM_NEWSMOB3} variants will allocate double cells and thus use -twice as much memory as smobs created by @code{SCM_NEWSMOB}.} - -@deftypefn Macro void SCM_NEWSMOB (SCM value, scm_t_bits tag, void *data) -@deftypefnx Macro void SCM_NEWSMOB2 (SCM value, scm_t_bits tag, void *data1, void *data2) -@deftypefnx Macro void SCM_NEWSMOB3 (SCM value, scm_t_bits tag, void *data1, void *data2, void *data3) -Make @var{value} contain a smob instance of the type with tag @var{tag} -and smob data @var{data} (or @var{data1}, @var{data2}, and @var{data3}). -@var{value} must be previously declared as C type @code{SCM}. -@end deftypefn - -Since it is often the case (e.g., in smob constructors) that you will -create a smob instance and return it, there is also a slightly specialized -macro for this situation: - -@deftypefn Macro fn_returns SCM_RETURN_NEWSMOB (scm_t_bits tag, void *data) -@deftypefnx Macro fn_returns SCM_RETURN_NEWSMOB2 (scm_t_bits tag, void *data1, void *data2) -@deftypefnx Macro fn_returns SCM_RETURN_NEWSMOB3 (scm_t_bits tag, void *data1, void *data2, void *data3) -This macro expands to a block of code that creates a smob instance of -the type with tag @var{tag} and smob data @var{data} (or @var{data1}, -@var{data2}, and @var{data3}), and causes the surrounding function to -return that @code{SCM} value. It should be the last piece of code in -a block. -@end deftypefn - -Guile provides some functions for managing memory, which are often -helpful when implementing smobs. @xref{Memory Blocks}. - - -Continuing the above example, if the global variable @code{image_tag} -contains a tag returned by @code{scm_make_smob_type}, here is how we -could construct a smob whose @sc{cdr} contains a pointer to a freshly -allocated @code{struct image}: - -@example -struct image @{ - int width, height; - char *pixels; - - /* The name of this image */ - SCM name; - - /* A function to call when this image is - modified, e.g., to update the screen, - or SCM_BOOL_F if no action necessary */ - SCM update_func; -@}; - -SCM -make_image (SCM name, SCM s_width, SCM s_height) -@{ - struct image *image; - int width, height; - - SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image"); - SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image"); - SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image"); - - width = SCM_INUM (s_width); - height = SCM_INUM (s_height); - - image = (struct image *) scm_gc_malloc (sizeof (struct image), "image"); - image->width = width; - image->height = height; - image->pixels = scm_gc_malloc (width * height, "image pixels"); - image->name = name; - image->update_func = SCM_BOOL_F; - - SCM_RETURN_NEWSMOB (image_tag, image); -@} -@end example - - -@node Type checking -@subsection Type checking - -Functions that operate on smobs should aggressively check the types of -their arguments, to avoid misinterpreting some other datatype as a smob, -and perhaps causing a segmentation fault. Fortunately, this is pretty -simple to do. The function need only verify that its argument is a -non-immediate, whose first word is the type tag returned by -@code{scm_make_smob_type}. - -For example, here is a simple function that operates on an image smob, -and checks the type of its argument. We also present an expanded -version of the @code{init_image_type} function, to make -@code{clear_image} and the image constructor function @code{make_image} -visible to Scheme code. - -@example -SCM -clear_image (SCM image_smob) -@{ - int area; - struct image *image; - - SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob), - image_smob, SCM_ARG1, "clear-image"); - - image = (struct image *) SCM_SMOB_DATA (image_smob); - area = image->width * image->height; - memset (image->pixels, 0, area); - - /* Invoke the image's update function. */ - if (image->update_func != SCM_BOOL_F) - scm_apply (image->update_func, SCM_EOL, SCM_EOL); - - return SCM_UNSPECIFIED; -@} - - -void -init_image_type (void) -@{ - image_tag = scm_make_smob_type ("image", sizeof (struct image)); - scm_set_smob_mark (image_tag, mark_image); - scm_set_smob_free (image_tag, free_image); - scm_set_smob_print (image_tag, print_image); - - scm_c_define_gsubr ("clear-image", 1, 0, 0, clear_image); - scm_c_define_gsubr ("make-image", 3, 0, 0, make_image); -@} -@end example - -@c GJB:FIXME:: should talk about guile-snarf somewhere! - - -@node Garbage Collecting Smobs -@subsection Garbage Collecting Smobs - -Once a smob has been released to the tender mercies of the Scheme -system, it must be prepared to survive garbage collection. Guile calls -the @code{mark} and @code{free} functions of the @code{scm_smobfuns} -structure to manage this. - -As described before (@pxref{Conservative GC}), every object in the -Scheme system has a @dfn{mark bit}, which the garbage collector uses to -tell live objects from dead ones. When collection starts, every -object's mark bit is clear. The collector traces pointers through the -heap, starting from objects known to be live, and sets the mark bit on -each object it encounters. When it can find no more unmarked objects, -the collector walks all objects, live and dead, frees those whose mark -bits are still clear, and clears the mark bit on the others. - -The two main portions of the collection are called the @dfn{mark phase}, -during which the collector marks live objects, and the @dfn{sweep -phase}, during which the collector frees all unmarked objects. - -The mark bit of a smob lives in a special memory region. When the -collector encounters a smob, it sets the smob's mark bit, and uses the -smob's type tag to find the appropriate @code{mark} function for that -smob: the one listed in that smob's @code{scm_smobfuns} structure. It -then calls the @code{mark} function, passing it the smob as its only -argument. - -The @code{mark} function is responsible for marking any other Scheme -objects the smob refers to. If it does not do so, the objects' mark -bits will still be clear when the collector begins to sweep, and the -collector will free them. If this occurs, it will probably break, or at -least confuse, any code operating on the smob; the smob's @code{SCM} -values will have become dangling references. - -To mark an arbitrary Scheme object, the @code{mark} function may call -this function: - -@deftypefun void scm_gc_mark (SCM @var{x}) -Mark the object @var{x}, and recurse on any objects @var{x} refers to. -If @var{x}'s mark bit is already set, return immediately. -@end deftypefun - -Thus, here is how we might write the @code{mark} function for the image -smob type discussed above: - -@example -@group -SCM -mark_image (SCM image_smob) -@{ - /* Mark the image's name and update function. */ - struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); - - scm_gc_mark (image->name); - scm_gc_mark (image->update_func); - - return SCM_BOOL_F; -@} -@end group -@end example - -Note that, even though the image's @code{update_func} could be an -arbitrarily complex structure (representing a procedure and any values -enclosed in its environment), @code{scm_gc_mark} will recurse as -necessary to mark all its components. Because @code{scm_gc_mark} sets -an object's mark bit before it recurses, it is not confused by -circular structures. - -As an optimization, the collector will mark whatever value is returned -by the @code{mark} function; this helps limit depth of recursion during -the mark phase. Thus, the code above could also be written as: -@example -@group -SCM -mark_image (SCM image_smob) -@{ - /* Mark the image's name and update function. */ - struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); - - scm_gc_mark (image->name); - return image->update_func; -@} -@end group -@end example - - -Finally, when the collector encounters an unmarked smob during the sweep -phase, it uses the smob's tag to find the appropriate @code{free} -function for the smob. It then calls the function, passing it the smob -as its only argument. - -The @code{free} function must release any resources used by the smob. -However, it need not free objects managed by the collector; the -collector will take care of them. For historical reasons, the return -type of the @code{free} function should be @code{size_t}, an unsigned -integral type; the @code{free} function should always return zero. - -Here is how we might write the @code{free} function for the image smob -type: -@example -size_t -free_image (SCM image_smob) -@{ - struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); - - scm_gc_free (image->pixels, image->width * image->height, "image pixels"); - scm_gc_free (image, sizeof (struct image), "image"); - - return 0; -@} -@end example - -During the sweep phase, the garbage collector will clear the mark bits -on all live objects. The code which implements a smob need not do this -itself. - -There is no way for smob code to be notified when collection is -complete. - -It is usually a good idea to minimize the amount of processing done -during garbage collection; keep @code{mark} and @code{free} functions -very simple. Since collections occur at unpredictable times, it is easy -for any unusual activity to interfere with normal code. - - -@node A Common Mistake In Allocating Smobs, Garbage Collecting Simple Smobs, Garbage Collecting Smobs, Defining New Types (Smobs) -@subsection A Common Mistake In Allocating Smobs - -When constructing new objects, you must be careful that the garbage -collector can always find any new objects you allocate. For example, -suppose we wrote the @code{make_image} function this way: - -@example -SCM -make_image (SCM name, SCM s_width, SCM s_height) -@{ - struct image *image; - SCM image_smob; - int width, height; - - SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image"); - SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image"); - SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image"); - - width = SCM_INUM (s_width); - height = SCM_INUM (s_height); - - image = (struct image *) scm_gc_malloc (sizeof (struct image), "image"); - image->width = width; - image->height = height; - image->pixels = scm_gc_malloc (width * height, "image pixels"); - - /* THESE TWO LINES HAVE CHANGED: */ - image->name = scm_string_copy (name); - image->update_func = scm_c_define_gsubr (@dots{}); - - SCM_NEWCELL (image_smob); - SCM_SET_CELL_WORD_1 (image_smob, image); - SCM_SET_CELL_TYPE (image_smob, image_tag); - - return image_smob; -@} -@end example - -This code is incorrect. The calls to @code{scm_string_copy} and -@code{scm_c_define_gsubr} allocate fresh objects. Allocating any new object -may cause the garbage collector to run. If @code{scm_c_define_gsubr} -invokes a collection, the garbage collector has no way to discover that -@code{image->name} points to the new string object; the @code{image} -structure is not yet part of any Scheme object, so the garbage collector -will not traverse it. Since the garbage collector cannot find any -references to the new string object, it will free it, leaving -@code{image} pointing to a dead object. - -A correct implementation might say, instead: - -@example - image->name = SCM_BOOL_F; - image->update_func = SCM_BOOL_F; - - SCM_NEWCELL (image_smob); - SCM_SET_CELL_WORD_1 (image_smob, image); - SCM_SET_CELL_TYPE (image_smob, image_tag); - - image->name = scm_string_copy (name); - image->update_func = scm_c_define_gsubr (@dots{}); - - return image_smob; -@end example - -Now, by the time we allocate the new string and function objects, -@code{image_smob} points to @code{image}. If the garbage collector -scans the stack, it will find a reference to @code{image_smob} and -traverse @code{image}, so any objects @code{image} points to will be -preserved. - - -@node Garbage Collecting Simple Smobs -@subsection Garbage Collecting Simple Smobs - -It is often useful to define very simple smob types --- smobs which have -no data to mark, other than the cell itself, or smobs whose first data -word is simply an ordinary Scheme object, to be marked recursively. -Guile provides some functions to handle these common cases; you can use -this function as your smob type's @code{mark} function, if your smob's -structure is simple enough. - -If the smob refers to no other Scheme objects, then no action is -necessary; the garbage collector has already marked the smob cell -itself. In that case, you can use zero as your mark function. - -@deftypefun SCM scm_markcdr (SCM @var{x}) -Mark the references in the smob @var{x}, assuming that @var{x}'s first -data word contains an ordinary Scheme object, and @var{x} refers to no -other objects. This function simply returns @var{x}'s first data word. - -This is only useful for simple smobs created by @code{SCM_NEWSMOB} or -@code{SCM_RETURN_NEWSMOB}, not for smobs allocated as double cells. -@end deftypefun - -@deftypefun size_t scm_free0 (SCM @var{x}) -Do nothing; return zero. This function is appropriate for smobs that -use either zero or @code{scm_markcdr} as their marking functions, and -refer to no heap storage, including memory managed by @code{malloc}, -other than the smob's header cell. - -This function should not be needed anymore, because simply passing -@code{NULL} as the free function does the same. -@end deftypefun - - -@node Remembering During Operations -@subsection Remembering During Operations -@cindex Remembering - -It's important that a smob is visible to the garbage collector -whenever its contents are being accessed. Otherwise it could be freed -while code is still using it. - -For example, consider a procedure to convert image data to a list of -pixel values. - -@example -SCM -image_to_list (SCM image_smob) -@{ - struct image *image; - SCM lst; - int i; - SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob), - image_smob, SCM_ARG1, "image->list"); - - image = (struct image *) SCM_SMOB_DATA (image_smob); - lst = SCM_EOL; - for (i = image->width * image->height - 1; i >= 0; i--) - lst = scm_cons (SCM_MAKINUM (image->pixels[i]), lst); - - scm_remember_upto_here_1 (image_smob); - return lst; -@} -@end example - -In the loop, only the @code{image} pointer is used and the C compiler -has no reason to keep the @code{image_smob} value anywhere. If -@code{scm_cons} results in a garbage collect, @code{image_smob} might -not be on the stack or anywhere else and could be freed, leaving the -loop accessing freed data. The use of @code{scm_remember_upto_here_1} -prevents this, by creating a reference to @code{image_smob} after all -data accesses. - -There's no need to do the same for @code{lst}, since that's the return -value and the compiler will certainly keep it in a register or -somewhere throughout the routine. - -The @code{clear_image} example previously shown (@pxref{Type -checking}) didn't use @code{scm_remember_upto_here_1}. This is -because it didn't do anything that could result in a garbage collect. - -It's only in quite rare circumstances that a missing -@code{scm_remember_upto_here_1} will bite, but when it happens the -consequences are serious. Fortunately the rule is simple: whenever -calling a Guile library function or doing something that might, ensure -the @code{SCM} of a smob is referenced past all accesses to its -insides. Do this by adding an @code{scm_remember_upto_here_1} if -there are no other references. - -In a multi-threaded program, the rule is the same. As far as a given -thread is concerned, a garbage collect still only occurs within a -Guile library function, not at an arbitrary time. (Guile waits for -all threads to reach one of its library functions, and holds them -there while the collector runs.) - - -@node A Complete Example -@subsection A Complete Example - -Here is the complete text of the implementation of the image datatype, -as presented in the sections above. We also provide a definition for -the smob's @code{print} function, and make some objects and functions -static, to clarify exactly what the surrounding code is using. - -As mentioned above, you can find this code in the Guile distribution, in -@file{doc/example-smob}. That directory includes a makefile and a -suitable @code{main} function, so you can build a complete interactive -Guile shell, extended with the datatypes described here.) - -@example -/* file "image-type.c" */ - -#include <stdlib.h> -#include <libguile.h> - -static scm_t_bits image_tag; - -struct image @{ - int width, height; - char *pixels; - - /* The name of this image */ - SCM name; - - /* A function to call when this image is - modified, e.g., to update the screen, - or SCM_BOOL_F if no action necessary */ - SCM update_func; -@}; - -static SCM -make_image (SCM name, SCM s_width, SCM s_height) -@{ - struct image *image; - int width, height; - - SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image"); - SCM_ASSERT (SCM_INUMP (s_width), s_width, SCM_ARG2, "make-image"); - SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image"); - - width = SCM_INUM (s_width); - height = SCM_INUM (s_height); - - image = (struct image *) scm_gc_malloc (sizeof (struct image), "image"); - image->width = width; - image->height = height; - image->pixels = scm_gc_malloc (width * height, "image pixels"); - image->name = name; - image->update_func = SCM_BOOL_F; - - SCM_RETURN_NEWSMOB (image_tag, image); -@} - -static SCM -clear_image (SCM image_smob) -@{ - int area; - struct image *image; - - SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob), - image_smob, SCM_ARG1, "clear-image"); - - image = (struct image *) SCM_SMOB_DATA (image_smob); - area = image->width * image->height; - memset (image->pixels, 0, area); - - /* Invoke the image's update function. */ - if (image->update_func != SCM_BOOL_F) - scm_apply (image->update_func, SCM_EOL, SCM_EOL); - - return SCM_UNSPECIFIED; -@} - -static SCM -mark_image (SCM image_smob) -@{ - /* Mark the image's name and update function. */ - struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); - - scm_gc_mark (image->name); - return image->update_func; -@} - -static size_t -free_image (SCM image_smob) -@{ - struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); - - scm_gc_free (image->pixels, image->width * image->height, "image pixels"); - scm_gc_free (image, sizeof (struct image), "image"); - - return 0; -@} - -static int -print_image (SCM image_smob, SCM port, scm_print_state *pstate) -@{ - struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); - - scm_puts ("#<image ", port); - scm_display (image->name, port); - scm_puts (">", port); - - /* non-zero means success */ - return 1; -@} - -void -init_image_type (void) -@{ - image_tag = scm_make_smob_type ("image", sizeof (struct image)); - scm_set_smob_mark (image_tag, mark_image); - scm_set_smob_free (image_tag, free_image); - scm_set_smob_print (image_tag, print_image); - - scm_c_define_gsubr ("clear-image", 1, 0, 0, clear_image); - scm_c_define_gsubr ("make-image", 3, 0, 0, make_image); -@} -@end example - -Here is a sample build and interaction with the code from the -@file{example-smob} directory, on the author's machine: - -@example -zwingli:example-smob$ make CC=gcc -gcc `guile-config compile` -c image-type.c -o image-type.o -gcc `guile-config compile` -c myguile.c -o myguile.o -gcc image-type.o myguile.o `guile-config link` -o myguile -zwingli:example-smob$ ./myguile -guile> make-image -#<primitive-procedure make-image> -guile> (define i (make-image "Whistler's Mother" 100 100)) -guile> i -#<image Whistler's Mother> -guile> (clear-image i) -guile> (clear-image 4) -ERROR: In procedure clear-image in expression (clear-image 4): -ERROR: Wrong type argument in position 1: 4 -ABORT: (wrong-type-arg) - -Type "(backtrace)" to get more information. -guile> -@end example - -@c essay @bye diff --git a/doc/ref/debugging.texi b/doc/ref/debugging.texi index b88a852c2..e69de29bb 100644 --- a/doc/ref/debugging.texi +++ b/doc/ref/debugging.texi @@ -1,1114 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@page -@node Debugging Features -@chapter Debugging Features - -Guile includes debugging tools to help you work out what is going wrong -when a program signals an error or behaves differently to how you would -expect. This chapter describes how to use these tools. - -Broadly speaking, Guile's debugging support allows you to do two things: - -@itemize @bullet -@item -specify @dfn{breakpoints} --- points in the execution of a program where -execution should pause so you can see what is going on - -@item -examine in detail the ``scene of the crime'' --- in other words, the -execution context at a breakpoint, or when the last error occurred. -@end itemize - -@noindent -The details are more complex and more powerful @dots{} - -@menu -* Debug Last Error:: Debugging the most recent error. -* Breakpoints:: Setting and manipulating breakpoints. -* Interactive Debugger:: Using the interactive debugger. -* Tracing:: Tracing program execution. -@end menu - - -@node Debug Last Error -@section Debugging the Most Recent Error - -When an error is signalled, Guile remembers the execution context where -the error occurred. By default, Guile then displays only the most -immediate information about where and why the error occurred, for -example: - -@lisp -(make-string (* 4 (+ 3 #\s)) #\space) -@print{} -standard input:2:19: In procedure + in expression (+ 3 #\s): -standard input:2:19: Wrong type argument: #\s -ABORT: (wrong-type-arg) - -Type "(backtrace)" to get more information or "(debug)" to enter the debugger. -@end lisp - -@noindent -However, as the message above says, you can obtain much more information -about the context of the error by typing @code{(backtrace)} or -@code{(debug)}: - -@deffn {Scheme Procedure} backtrace -@deffnx {C Function} scm_backtrace () -Display a backtrace of the stack saved by the last error -to the current output port. -@end deffn - -@deffn {Scheme Procedure} debug -Invoke the Guile debugger to explore the context of the last error. -@end deffn - -@code{(backtrace)} displays the Scheme call stack at the point where the -error occurred: - -@lisp -(backtrace) -@print{} -Backtrace: -In standard input: - 2: 0* [make-string ... - 2: 1* [* 4 ... - 2: 2* [+ 3 #\s] - -Type "(debug-enable 'backtrace)" if you would like a backtrace -automatically if an error occurs in the future. -@end lisp - -@noindent -In a more complex scenario than this one, this can be extremely useful -for understanding where and why the error occurred. For more on the -format of the displayed backtrace, see the subsection below. - -@code{(debug)} takes you into Guile's interactive debugger, which -provides commands that allow you to - -@itemize @bullet -@item -display the Scheme call stack at the point where the error occurred -(the @code{backtrace} command --- see @ref{Display Backtrace}) - -@item -move up and down the call stack, to see in detail the expression being -evaluated, or the procedure being applied, in each @dfn{frame} (the -@code{up}, @code{down}, @code{frame}, @code{position}, @code{info args} -and @code{info frame} commands --- see @ref{Frame Selection} and -@ref{Frame Information}) - -@item -examine the values of variables and expressions in the context of each -frame (the @code{evaluate} command --- see @ref{Frame Evaluation}). -@end itemize - -Use of the interactive debugger, including these commands, is described -in @ref{Interactive Debugger}. - -@menu -* Backtrace Format:: How to interpret a backtrace. -@end menu - - -@node Backtrace Format -@subsection How to Interpret a Backtrace - - -@node Breakpoints -@section Breakpoints - -If you are not already familiar with the concept of breakpoints, the -first subsection below explains how they work are why they are useful. - -Broadly speaking, Guile's breakpoint support consists of - -@itemize @bullet -@item -type-specific features for @emph{creating} breakpoints of various types - -@item -relatively generic features for @emph{manipulating} the behaviour of -breakpoints once they've been created. -@end itemize - -Different breakpoint types are implemented as different classes in a -GOOPS hierarchy with common base class @code{<breakpoint>}. The magic -of generic functions then allows most of the manipulation functions to -be generic by default but specializable (by breakpoint class) if the -need arises. - -Generic breakpoint support is provided by the @code{(ice-9 debugger -breakpoints)} module, so you will almost always need to use this module -in order to access the functionality described here: - -@smalllisp -(use-modules (ice-9 debugger breakpoints)) -@end smalllisp - -@noindent -You may like to add this to your @file{.guile} file. - -@menu -* Breakpoints Overview:: -* Source Breakpoints:: -* Procedural Breakpoints:: -* Setting Breakpoints:: -* break! trace! trace-subtree!:: -* Accessing Breakpoints:: -* Breakpoint Behaviours:: -* Enabling and Disabling:: -* Deleting Breakpoints:: -* Breakpoint Information:: -* Other Breakpoint Types:: -@end menu - - -@node Breakpoints Overview -@subsection How Breakpoints Work and Why They Are Useful - -Often, debugging the last error is not enough to tell you what went -wrong. For example, the root cause of the error may have arisen a long -time before the error was signalled, in which case the execution context -of the error is too late to be useful. Or your program might not signal -an error at all, just return an unexpected result or have some incorrect -side effect. - -In many such cases, it's useful to pause the program at or before the -point where you suspect the problem arises. Then you can explore the -stack, display the values of key variables, and generally check that the -state of the program is as you expect. If all is well, you can let the -program continue running normally, or step more slowly through each -expression that the Scheme interpreter evaluates. Single-stepping may -reveal that the program is going through blocks of code that you didn't -intend --- a useful data point for understanding what the underlying -problem is. - -Telling Guile where or when to pause a program is called @dfn{setting a -breakpoint}. When a breakpoint is hit, Guile's default behaviour is to -enter the interactive debugger, where there are now two sets of commands -available: - -@itemize @bullet -@item -all the commands as described for last error debugging (@pxref{Debug -Last Error}), which allow you to explore the stack and so on - -@item -additional commands for continuing program execution in various ways: -@code{next}, @code{step}, @code{finish}, @code{trace-finish} and -@code{continue}. -@end itemize - -Use of the interactive debugger is described in @ref{Interactive -Debugger}. - - -@node Source Breakpoints -@subsection Source Breakpoints - -A source breakpoint is a breakpoint that triggers whenever program -execution hits a particular source location. A source breakpoint can be -conveniently set simply by evaluating code that has @code{##} inserted -into it at the position where you want the breakpoint to be. - -For example, to set a breakpoint immediately before evaluation of -@code{(= n 0)} in the following procedure definition, evaluate: - -@smalllisp -(define (fact1 n) - (if ##(= n 0) - 1 - (* n (fact1 (- n 1))))) -@print{} -Set breakpoint 1: standard input:4:9: (= n 0) -@end smalllisp - -@noindent -Note the message confirming that you have set a breakpoint. If you -don't see this, something isn't working. - -@code{##} is provided by the @code{(ice-9 debugger breakpoints source)} module, -so you must use this module before trying to set breakpoints in this -way: - -@smalllisp -(use-modules (ice-9 debugger breakpoints source)) -@end smalllisp - -@noindent -You may like to add this to your @file{.guile} file. - -The default behaviour for source breakpoints is @code{debug-here} -(@pxref{Breakpoint Behaviours}), which means to enter the command line -debugger when the breakpoint is hit. So, if you now use @code{fact1}, -that is what happens. - -@smalllisp -guile> (fact1 3) -Hit breakpoint 1: standard input:4:9: (= n 0) -Frame 3 at standard input:4:9 - (= n 0) -debug> -@end smalllisp - - -@node Procedural Breakpoints -@subsection Procedural Breakpoints - -A procedural breakpoint is a breakpoint that triggers whenever Guile is -about to apply a specified procedure to its (already evaluated) -arguments. To set a procedural breakpoint, call @code{break!} with the -target procedure as a single argument. For example: - -@smalllisp -(define (fact1 n) - (if (= n 0) - 1 - (* n (fact1 (- n 1))))) - -(break! fact1) -@print{} -Set breakpoint 1: [fact1] -@result{} -#<<procedure-breakpoint> 808b0b0> -@end smalllisp - -Alternatives to @code{break!} are @code{trace!} and -@code{trace-subtree!}. The difference is that these three calls create -a breakpoint in the same place but with three different behaviours, -respectively @code{debug-here}, @code{trace-here} and -@code{trace-subtree}. Breakpoint behaviours are documented fully later -(@pxref{Breakpoint Behaviours}), but to give a quick taste, here's an -example of running code that includes a procedural breakpoint with the -@code{trace-here} behaviour. - -@smalllisp -(trace! fact1) -@print{} -Set breakpoint 1: [fact1] -@result{} -#<<procedure-breakpoint> 808b0b0> - -(fact1 4) -@print{} -| [fact1 4] -| | [fact1 3] -| | | [fact1 2] -| | | | [fact1 1] -| | | | | [fact1 0] -| | | | | 1 -| | | | 2 -| | | 6 -| | 24 -| 24 -@result{} -24 -@end smalllisp - -To set and use procedural breakpoints, you will need to use the -@code{(ice-9 debugger breakpoints procedural)} module: - -@smalllisp -(use-modules (ice-9 debugger breakpoints procedural)) -@end smalllisp - -@noindent -You may like to add this to your @file{.guile} file. - - -@node Setting Breakpoints -@subsection Setting Breakpoints - -In general, that is. We've already seen how to set source and -procedural breakpoints conveniently in practice. This section explains -how those conveniences map onto a more general mechanism. - -The general mechanism for setting breakpoints is the generic function -@code{set-breakpoint!}: - -@deffn {Generic Function} set-breakpoint! behaviour . location-args -Set a breakpoint with behaviour @var{behaviour} at the location -specified by @var{location-args}. - -The form of the @var{location-args} depends upon what methods for -@code{set-breakpoint!} have been provided by the implementations of -subclasses of the @code{<breakpoint>} base class. -@end deffn - -So, for example, @code{(ice-9 debugger breakpoints procedural)} implements the -@code{<procedure-breakpoint>} subclass and provides a -@code{set-breakpoint!} method that takes a procedure argument: - -@deffn {Method} set-breakpoint! behaviour (proc <procedure>) -Set a breakpoint with behaviour @var{behaviour} before applications of -the procedure @var{proc}. -@end deffn - -@code{(ice-9 debugger breakpoints source)} implements the -@code{<source-breakpoint>} subclass and provides a -@code{set-breakpoint!} method that takes two arguments describing the -source expression on which the breakpoint should be set: - -@deffn {Method} set-breakpoint! behaviour x-as-read (x-pairified <pair>) -Set a breakpoint with behaviour @var{behaviour} on the source expression -@var{x-pairified}, storing @var{x-as-read} for use in messages -describing the breakpoint. -@end deffn - -A non-type-specific @code{set-breakpoint!} method is provided by the -generic module @code{(ice-9 debugger breakpoints)}. It allows you to change the -behaviour of an existing breakpoint that is identified by its breakpoint -number: - -@deffn {Method} set-breakpoint! behaviour (number <integer>) -Change the behaviour of existing breakpoint number @var{number} to -@var{behaviour}. -@end deffn - - -@node break! trace! trace-subtree! -@subsection break! trace! trace-subtree! - -We have already talked above about the use of @code{break!}, -@code{trace!} and @code{trace-subtree!} for setting procedural -breakpoints. Now that @code{set-breakpoint!} has been introduced, we -can reveal that @code{break!}, @code{trace!} and @code{trace-subtree!} -are in fact just wrappers for @code{set-breakpoint!} that specify -particular breakpoint behaviours, respectively @code{debug-here}, -@code{trace-here} and @code{trace-subtree}. - -@smalllisp -(break! . @var{args}) - @equiv{} (set-breakpoint! debug-here . @var{args}) -(trace! . @var{args}) - @equiv{} (set-breakpoint! trace-here . @var{args}) -(trace-subtree! . @var{args}) - @equiv{} (set-breakpoint! trace-subtree . @var{args}) -@end smalllisp - -This means that these three procedures can be used to set the -corresponding behaviours for any type of breakpoint for which a -@code{set-breakpoint!} method exists, not just procedural ones. - - -@node Accessing Breakpoints -@subsection Accessing Breakpoints - -Information about the state and behaviour of a breakpoint is stored in -an instance of the appropriate breakpoint class. To access and change -that information, therefore, you need to get hold of the desired -breakpoint instance. - -The generic function @code{get-breakpoint} meets this need: - -@deffn {Generic Function} get-breakpoint . location-args -Find and return the breakpoint instance at the location specified by -@var{location-args}. - -The form of the @var{location-args} depends upon what methods for -@code{get-breakpoint} have been provided by the implementations of -subclasses of the @code{<breakpoint>} base class. -@end deffn - -For every @code{set-breakpoint!} method there is a corresponding -@code{get-breakpoint} method which interprets the @var{location-args} in -the same way. Since those interpretations are described above -(@pxref{Setting Breakpoints}), we won't repeat them here, except to note -again the useful type-independent case: - -@smalllisp -(get-breakpoint @var{number}) -@end smalllisp - -@noindent -returns the breakpoint instance for the existing breakpoint numbered -@var{number}. - - -@node Breakpoint Behaviours -@subsection Breakpoint Behaviours - -A breakpoint's @dfn{behaviour} determines what happens when that -breakpoint is hit. Several kinds of behaviour are generally useful. - -@table @code -@item debug-here -Enter the command line debugger. This gives the opportunity to explore -the stack, evaluate expressions in any of the pending stack frames, -change breakpoint properties or set new breakpoints, and continue -program execution when you are done. - -@item trace-here -Trace the current stack frame. For expressions being evaluated, this -shows the expression. For procedure applications, it shows the -procedure name and its arguments @emph{post-evaluation}. For both -expressions and applications, the indentation of the tracing indicates -whether the traced items are mutually tail recursive. - -@item trace-subtree -Trace the current stack frame, and enable tracing for all future -evaluations and applications until the current stack frame is exited. -@code{trace-subtree} is a great preliminary exploration tool when all -you know is that there is a bug ``somewhere in XXX or in something that -XXX calls''. - -@item (at-exit @var{thunk}) -Don't do anything now, but arrange for @var{thunk} to be executed when -the current stack frame is exited. For example, the operation that most -debugging tools call ``finish'' is @code{(at-exit debug-here)}. - -@item (at-next @var{count} @var{thunk}) -@dots{} arrange for @var{thunk} to be executed when beginning the -@var{count}th next evaluation or application with source location in the -current file. - -@item (at-entry @var{count} @var{thunk}) -@dots{} arrange for @var{thunk} to be executed when beginning the -@var{count}th next evaluation (regardless of source location). - -@item (at-apply @var{count} @var{thunk}) -@dots{} arrange for @var{thunk} to be executed just before performing -the @var{count}th next application (regardless of source location). - -@item (at-step @var{count} @var{thunk}) -Synthesis of @code{at-entry} and @code{at-apply}; counts both -evaluations and applications. -@end table - -Every breakpoint instance has a slot in which its behaviour is stored. -If you have a breakpoint instance in hand, you can change its behaviour -using the @code{bp-behaviour} accessor. - -@deffn {Accessor} bp-behaviour breakpoint -Get or set the behaviour of the breakpoint instance @var{breakpoint}. -@end deffn - -@noindent -(An @dfn{accessor} supports the setting of a property like this: - -@smalllisp -(set! (bp-behaviour @var{breakpoint}) @var{new-behaviour}) -@end smalllisp - -@noindent -See the GOOPS manual for further information on accessors.) - -Alternatively, if you know how to specify the @var{location-args} for -the breakpoint in question, you can change its behaviour using -@code{set-breakpoint!}. For example: - -@smalllisp -;; Change behaviour of breakpoint number 2. -(set-breakpoint! @var{new-behaviour} 2) - -;; Change behaviour of procedural breakpoint on [fact1]. -(set-breakpoint! @var{new-behaviour} fact1) -@end smalllisp - -In all cases, the behaviour that you specify should be either a single -thunk, or a list of thunks, to be called when the breakpoint is hit. - -The most common behaviours above are exported as thunks from the -@code{(ice-9 debugger behaviour)} module. So, if you use this module, you can -use those behaviours directly like this: - -@smalllisp -(use-modules (ice-9 debugger behaviour)) -(set-breakpoint! trace-subtree 2) -(set! (bp-behaviour (get-breakpoint 3)) debug-here) -@end smalllisp - -@noindent -You can also use the list option to combine common behaviours: - -@smalllisp -(set-breakpoint! (list trace-here debug-here) 2) -@end smalllisp - -@noindent -Or, for more customized behaviour, you could build and use your own -thunk like this: - -@smalllisp -(define (my-behaviour) - (trace-here) - (at-exit (lambda () - (display "Exiting frame of my-behaviour bp\n") - ... do something unusual ...))) - -(set-breakpoint my-behaviour 2) -@end smalllisp - - -@node Enabling and Disabling -@subsection Enabling and Disabling - -Independently of its behaviour, each breakpoint also keeps track of -whether it is currently enabled. This is a straightforward convenience -to allow breakpoints to be temporarily switched off without losing all -their carefully constructed properties. - -If you have a breakpoint instance in hand, you can enable or disable it -using the @code{bp-enabled?} accessor: - -@deffn {Accessor} bp-enabled? breakpoint -Get or set the enabled state of the specified @var{breakpoint}. -@end deffn - -Alternatively, you can enable or disable a breakpoint by its location -args: - -@deffn {Procedure} enable-breakpoint! . location-args -@deffnx {Procedure} disable-breakpoint! . location-args -Enable or disable the breakpoint at the location specified by -@var{location-args}. -@end deffn - -@code{enable-breakpoint!} and @code{disable-breakpoint!} are implemented -using @code{get-breakpoint} and @code{bp-enabled?}, so any -@var{location-args} that are valid for @code{get-breakpoint} will work -also for these procedures. - - -@node Deleting Breakpoints -@subsection Deleting Breakpoints - -Given a breakpoint instance in hand, you can deactivate it and remove it -from the global list of current breakpoints by calling -@code{bp-delete!}: - -@deffn {Generic Function} bp-delete! breakpoint -Delete breakpoint @var{breakpoint}. This means (1) doing whatever is -needed to prevent the breakpoint from triggering again, and (2) removing -it from the global list of current breakpoints. -@end deffn - -Alternatively, you can delete a breakpoint by its location args: - -@deffn {Procedure} delete-breakpoint! . location-args -Delete the breakpoint at the location specified by @var{location-args}. -@end deffn - -@code{delete-breakpoint!} is implemented using @code{get-breakpoint} and -@code{bp-delete!}, so any @var{location-args} that are valid for -@code{get-breakpoint} will work also for @code{delete-breakpoint!}. - -There is no way to reinstate a deleted breakpoint. Final destruction of -the breakpoint instance is determined by the usual garbage collection -rules. - - -@node Breakpoint Information -@subsection Breakpoint Information - -To get Guile to print a description of a breakpoint instance, use -@code{bp-describe}: - -@smalllisp -(bp-describe (get-breakpoint 1) #t) -@print{} -Breakpoint 1: [fact1] - enabled? = #t - behaviour = #<procedure trace-here ()> -@end smalllisp - -@deffn {Generic Function} bp-describe breakpoint port -Print a description of @var{breakpoint} to the specified @var{port}. -@var{port} can be @code{#t} for standard output, or else any output -port. -@end deffn - -Following the usual model, @code{describe-breakpoint} is also provided: - -@deffn {Procedure} describe-breakpoint . location-args -Print (to standard output) a description of the breakpoint at location -specified by @var{location-args}. -@end deffn - -Finally, two stragglers. @code{all-breakpoints} returns a list of all -current breakpoints. @code{describe-all-breakpoints} combines -@code{bp-describe} and @code{all-breakpoints} by printing a description -of all current breakpoints to standard output. - -@deffn {Procedure} all-breakpoints -Return a list of all current breakpoints, ordered by breakpoint number. -@end deffn - -@deffn {Procedure} describe-all-breakpoints -Print a description of all current breakpoints to standard output. -@end deffn - - -@node Other Breakpoint Types -@subsection Other Breakpoint Types - -Besides source and procedural breakpoints, Guile includes an early -implementation of a third class of breakpoints: @dfn{range} breakpoints. -These are breakpoints that trigger when program execution enters (or -perhaps exits) a defined range of source locations. - -Sadly, these don't yet work well. The apparent problem is that the -extra methods for @code{set-breakpoint!} and @code{get-breakpoint} cause -some kind of explosion in the time taken by GOOPS to construct its -method cache and to dispatch calls involving these generic functions. -But we haven't really investigated enough to be sure that this is the -real issue. - -If you're interested in looking and/or investigating anyway, please feel -free to check out and play with the @code{(ice-9 debugger breakpoints -range)} module. - -The other kind of breakpoint that we'd like to have is watchpoints, but -this hasn't been implemented at all yet. Watchpoints may turn out to be -impractical for performance reasons. - - -@node Interactive Debugger -@section Using the Interactive Debugger - -Guile's interactive debugger is a command line application that accepts -commands from you for examining the stack and, if at a breakpoint, for -continuing program execution in various ways. Unlike in the normal -Guile REPL, commands are typed mostly without parentheses. - -When you first enter the debugger, it introduces itself with a message -like this: - -@lisp -This is the Guile debugger -- for help, type `help'. -There are 3 frames on the stack. - -Frame 2 at standard input:36:19 - [+ 3 #\s] -debug> -@end lisp - -@noindent -``debug>'' is the debugger's prompt, and a useful reminder that you are -not in the normal Guile REPL. The available commands are described in -detail in the following subsections. - -@menu -* Display Backtrace:: backtrace. -* Frame Selection:: up, down, frame. -* Frame Information:: info args, info frame, position. -* Frame Evaluation:: evaluate. -* Single Stepping:: step, next. -* Run To Frame Exit:: finish, trace-finish. -* Continue Execution:: continue. -* Leave Debugger:: quit. -@end menu - - -@node Display Backtrace -@subsection Display Backtrace - -The @code{backtrace} command, which can also be invoked as @code{bt} or -@code{where}, displays the call stack (aka backtrace) at the point where -the debugger was entered: - -@lisp -debug> bt -In standard input: - 36: 0* [make-string ... - 36: 1* [* 4 ... - 36: 2* [+ 3 #\s] -@end lisp - -@deffn {Debugger Command} backtrace [count] -@deffnx {Debugger Command} bt [count] -@deffnx {Debugger Command} where [count] -Print backtrace of all stack frames, or of the innermost @var{count} -frames. With a negative argument, print the outermost -@var{count} -frames. If the number of frames isn't explicitly given, the debug -option @code{depth} determines the maximum number of frames printed. -@end deffn - -The format of the displayed backtrace is the same as for the -@code{backtrace} procedure --- see @ref{Backtrace Format} for details. - - -@node Frame Selection -@subsection Frame Selection - -A call stack consists of a sequence of stack @dfn{frames}, with each -frame describing one level of the nested evaluations and applications -that the program was executing when it hit a breakpoint or an error. -Frames are numbered such that frame 0 is the outermost --- i.e. the -operation on the call stack that began least recently --- and frame N-1 -the innermost (where N is the total number of frames on the stack). - -When you enter the debugger, the innermost frame is selected, which -means that the commands for getting information about the ``current'' -frame, or for evaluating expressions in the context of the current -frame, will do so by default with respect to the innermost frame. To -select a different frame, so that these operations will apply to it -instead, use the @code{up}, @code{down} and @code{frame} commands like -this: - -@lisp -debug> up -Frame 1 at standard input:36:14 - [* 4 ... -debug> frame 0 -Frame 0 at standard input:36:1 - [make-string ... -debug> down -Frame 1 at standard input:36:14 - [* 4 ... -@end lisp - -@deffn {Debugger Command} up [n] -Move @var{n} frames up the stack. For positive @var{n}, this -advances toward the outermost frame, to higher frame numbers, to -frames that have existed longer. @var{n} defaults to one. -@end deffn - -@deffn {Debugger Command} down [n] -Move @var{n} frames down the stack. For positive @var{n}, this -advances toward the innermost frame, to lower frame numbers, to frames -that were created more recently. @var{n} defaults to one. -@end deffn - -@deffn {Debugger Command} frame [n] -Select and print a stack frame. With no argument, print the selected -stack frame. (See also ``info frame''.) An argument specifies the -frame to select; it must be a stack-frame number. -@end deffn - - -@node Frame Information -@subsection Frame Information - -[to be completed] - -@deffn {Debugger Command} {info frame} -All about selected stack frame. -@end deffn - -@deffn {Debugger Command} {info args} -Argument variables of current stack frame. -@end deffn - -@deffn {Debugger Command} position -Display the position of the current expression. -@end deffn - - -@node Frame Evaluation -@subsection Frame Evaluation - -[to be completed] - -@deffn {Debugger Command} evaluate expression -Evaluate an expression. -The expression must appear on the same line as the command, -however it may be continued over multiple lines. -@end deffn - - -@node Single Stepping -@subsection Single Stepping - -[to be completed] - -@deffn {Debugger Command} step [n] -Continue until entry to @var{n}th next frame. -@end deffn - -@deffn {Debugger Command} next [n] -Continue until entry to @var{n}th next frame in same file. -@end deffn - - -@node Run To Frame Exit -@subsection Run To Frame Exit - -[to be completed] - -@deffn {Debugger Command} finish -Continue until evaluation of the current frame is complete, and -print the result obtained. -@end deffn - -@deffn {Debugger Command} trace-finish -Trace until evaluation of the current frame is complete. -@end deffn - - -@node Continue Execution -@subsection Continue Execution - -[to be completed] - -@deffn {Debugger Command} continue -Continue program execution. -@end deffn - - -@node Leave Debugger -@subsection Leave Debugger - -[to be completed] - -@deffn {Debugger Command} quit -Exit the debugger. -@end deffn - - -@node Tracing -@section Tracing - -Tracing has already been described as a breakpoint behaviour -(@pxref{Breakpoint Behaviours}), but we mention it again here because it -is so useful, and because Guile actually now has @emph{two} mechanisms -for tracing, and its worth clarifying the differences between them. - -@menu -* Old Tracing:: Tracing provided by (ice-9 debug). -* New Tracing:: Breakpoint-based tracing. -* Tracing Compared:: Differences between old and new. -@end menu - - -@node Old Tracing -@subsection Tracing Provided by @code{(ice-9 debug)} - -The @code{(ice-9 debug)} module implements tracing of procedure -applications. When a procedure is @dfn{traced}, it means that every -call to that procedure is reported to the user during a program run. -The idea is that you can mark a collection of procedures for tracing, -and Guile will subsequently print out a line of the form - -@smalllisp -| | [@var{procedure} @var{args} @dots{}] -@end smalllisp - -whenever a marked procedure is about to be applied to its arguments. -This can help a programmer determine whether a function is being called -at the wrong time or with the wrong set of arguments. - -In addition, the indentation of the output is useful for demonstrating -how the traced applications are or are not tail recursive with respect -to each other. Thus, a trace of a non-tail recursive factorial -implementation looks like this: - -@smalllisp -[fact1 4] -| [fact1 3] -| | [fact1 2] -| | | [fact1 1] -| | | | [fact1 0] -| | | | 1 -| | | 1 -| | 2 -| 6 -24 -@end smalllisp - -While a typical tail recursive implementation would look more like this: - -@smalllisp -[fact2 4] -[facti 1 4] -[facti 4 3] -[facti 12 2] -[facti 24 1] -[facti 24 0] -24 -@end smalllisp - -@deffn {Scheme Procedure} trace procedure -Enable tracing for @code{procedure}. While a program is being run, -Guile will print a brief report at each call to a traced procedure, -advising the user which procedure was called and the arguments that were -passed to it. -@end deffn - -@deffn {Scheme Procedure} untrace procedure -Disable tracing for @code{procedure}. -@end deffn - -Here is another example: - -@lisp -(define (rev ls) - (if (null? ls) - '() - (append (rev (cdr ls)) - (cons (car ls) '())))) @result{} rev - -(trace rev) @result{} (rev) - -(rev '(a b c d e)) -@result{} [rev (a b c d e)] - | [rev (b c d e)] - | | [rev (c d e)] - | | | [rev (d e)] - | | | | [rev (e)] - | | | | | [rev ()] - | | | | | () - | | | | (e) - | | | (e d) - | | (e d c) - | (e d c b) - (e d c b a) - (e d c b a) -@end lisp - -Note the way Guile indents the output, illustrating the depth of -execution at each procedure call. This can be used to demonstrate, for -example, that Guile implements self-tail-recursion properly: - -@lisp -(define (rev ls sl) - (if (null? ls) - sl - (rev (cdr ls) - (cons (car ls) sl)))) @result{} rev - -(trace rev) @result{} (rev) - -(rev '(a b c d e) '()) -@result{} [rev (a b c d e) ()] - [rev (b c d e) (a)] - [rev (c d e) (b a)] - [rev (d e) (c b a)] - [rev (e) (d c b a)] - [rev () (e d c b a)] - (e d c b a) - (e d c b a) -@end lisp - -Since the tail call is effectively optimized to a @code{goto} statement, -there is no need for Guile to create a new stack frame for each -iteration. Tracing reveals this optimization in operation. - - -@node New Tracing -@subsection Breakpoint-based Tracing - -Guile's newer mechanism implements tracing as an optional behaviour for -any kind of breakpoint. - -To trace a procedure (in the same kind of way as the older tracing), use -the @code{trace!} procedure to set a procedure breakpoint with -@code{trace-here} behaviour: - -@lisp -(trace! fact1) -@print{} -Set breakpoint 1: [fact1] -@result{} -#<<procedure-breakpoint> 40337bf0> - -(fact1 4) -@print{} -| [fact1 4] -| | [fact1 3] -| | | [fact1 2] -| | | | [fact1 1] -| | | | | [fact1 0] -| | | | | 1 -| | | | 2 -| | | 6 -| | 24 -| 24 -@result{} -24 -@end lisp - -To trace evaluation of a source expression, evaluate code containing a -breakpoint marker @code{##} in the appropriate place, then use -@code{set-breakpoint} to change the behaviour of the new breakpoint to -@code{trace-here}: - -@lisp -(define (fact1 n) - (if ##(= n 0) - 1 - (* n (fact1 (- n 1))))) -@print{} -Set breakpoint 4: standard input:13:9: (= n 0) - -(use-modules (ice-9 debugger behaviour)) -(set-breakpoint! trace-here 4) -@print{} -Breakpoint 4: standard input:13:9: (= n 0) - enabled? = #t - behaviour = #<procedure trace-here ()> - -(fact1 4) -@print{} -| (= n 0) -| #f -| (= n 0) -| #f -| (= n 0) -| #f -| (= n 0) -| #f -| (= n 0) -| #t -@result{} -24 -@end lisp - -@noindent -(Note --- this example reveals a bug: each occurrence of @code{(= n 0)} -should be shown indented with respect to the one before it, as -@code{fact1} does not call itself tail-recursively.) - -You can also give a breakpoint the @code{trace-subtree} behaviour, which -means to trace the breakpoint location itself plus any evaluations and -applications that occur below it in the call stack. In the following -example, this allows us to see the evaluated arguments that are being -compared by the @code{=} procedure: - -@lisp -(set-breakpoint! trace-subtree 4) -@print{} -Breakpoint 4: standard input:13:9: (= n 0) - enabled? = #t - behaviour = #<procedure trace-subtree ()> - -(fact1 4) -@print{} -| (= n 0) -| [= 4 0] -| #f -| (= n 0) -| [= 3 0] -| #f -| (= n 0) -| [= 2 0] -| #f -| (= n 0) -| [= 1 0] -| #f -| (= n 0) -| [= 0 0] -| #t -@result{} -24 -@end lisp - - -@node Tracing Compared -@subsection Differences Between Old and New Tracing Mechanisms - -The newer tracing mechanism is more general and so more powerful than -the older one: it works for expressions as well as procedure -applications, and it implements the useful @code{trace-subtree} -behaviour as well as the more traditional @code{trace-here}. - -The older mechanism will probably become obsolete eventually, but it's -worth keeping it around for a while until we are sure that the new -mechanism is correct and does what programmers need. diff --git a/doc/ref/deprecated.texi b/doc/ref/deprecated.texi index 9cc464295..e69de29bb 100644 --- a/doc/ref/deprecated.texi +++ b/doc/ref/deprecated.texi @@ -1,39 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@page -@node Deprecated -@chapter Deprecated - -The features and functions described in this chapter are considered -obsolete and should not be used by new programs. They're retained for -compatibility with past versions of Guile. - -@deffn {Scheme Procedure} substring-move-left! str1 start1 end1 str2 start2 -@deffnx {Scheme Procedure} substring-move-right! str1 start1 end1 str2 start2 -These functions are aliases for @code{substring-move!} and calls to -them can simply be replaced by @code{substring-move!} (@pxref{String -Modification}.) - -In the past, if @var{str1} and @var{str2} were the same string, it was -necessary to call @code{substring-move-left!} if the move was to the -left (@math{@var{start2} < @var{start1}}), or call -@code{substring-move-right!} if the move was to the right -(@math{@var{start2} > @var{start1}}). @code{substring-move!} is now -able to do both. -@end deffn - -@deftypefn {C Function} void scm_remember (SCM *ptr) -Create a reference to the object at @var{ptr}, so it's certain to be -present on the stack and hence won't be freed by the garbage -collector. - -This function has been superceded by @code{scm_remember_upto_here_1} -(which takes an object, not a pointer to one), @xref{Remembering -During Operations}. -@end deftypefn - - diff --git a/doc/ref/expect.texi b/doc/ref/expect.texi index 472c30e26..54f779632 100644 --- a/doc/ref/expect.texi +++ b/doc/ref/expect.texi @@ -6,7 +6,7 @@ @page @node Expect -@chapter Expect +@section Expect The macros in this section are made available with: diff --git a/doc/ref/gh.texi b/doc/ref/gh.texi index 184c507cc..03cf997f4 100644 --- a/doc/ref/gh.texi +++ b/doc/ref/gh.texi @@ -6,7 +6,7 @@ @page @node GH -@chapter GH: A Portable C to Scheme Interface +@section GH: A Portable C to Scheme Interface @cindex libguile - gh @cindex gh @cindex gh - reference manual @@ -39,7 +39,7 @@ the same result using the scm interface. @node GH deprecation -@section Why the GH Interface is Now Deprecated +@subsection Why the GH Interface is Now Deprecated Historically, the GH interface was the product of a practical problem and a neat idea. The practical problem was that the interface of the @@ -82,7 +82,7 @@ this as part of the core Guile project. @node gh preliminaries -@section gh preliminaries +@subsection gh preliminaries To use gh, you must have the following toward the beginning of your C source: @@ -98,7 +98,7 @@ interpreter, you will have to add more libraries. @node Data types and constants defined by gh -@section Data types and constants defined by gh +@subsection Data types and constants defined by gh @cindex libguile - data types The following C constants and data types are defined in gh: @@ -136,7 +136,7 @@ numbers of arguments, such as @code{gh_list()}. @node Starting and controlling the interpreter -@section Starting and controlling the interpreter +@subsection Starting and controlling the interpreter @cindex libguile - start interpreter In almost every case, your first @code{gh_} call will be: @@ -247,7 +247,7 @@ procedures @code{gsl-ran-random}, @code{gsl-ran-gaussian} and so forth. @node Error messages -@section Error messages +@subsection Error messages @cindex libguile - error messages @cindex error messages in libguile @@ -255,7 +255,7 @@ procedures @code{gsl-ran-random}, @code{gsl-ran-gaussian} and so forth. @node Executing Scheme code -@section Executing Scheme code +@subsection Executing Scheme code @cindex libguile - executing Scheme @cindex executing Scheme @@ -286,7 +286,7 @@ closely. @node Defining new Scheme procedures in C -@section Defining new Scheme procedures in C +@subsection Defining new Scheme procedures in C @cindex libguile - new procedures @cindex new procedures @cindex procedures, new @@ -357,7 +357,7 @@ These macros disable and re-enable Scheme's flow control. They @node Converting data between C and Scheme -@section Converting data between C and Scheme +@subsection Converting data between C and Scheme @cindex libguile - converting data @cindex data conversion @cindex converting data @@ -373,7 +373,7 @@ of type @code{SCM}) and return values of type @code{SCM}. @end menu @node C to Scheme -@subsection C to Scheme +@subsubsection C to Scheme @deftypefun SCM gh_bool2scm (int @var{x}) Returns @code{#f} if @var{x} is zero, @code{#t} otherwise. @@ -429,7 +429,7 @@ longs, unsigned longs, floats or doubles at memory location @var{dptr}. @node Scheme to C -@subsection Scheme to C +@subsubsection Scheme to C @deftypefun int gh_scm2bool (SCM @var{obj}) @deftypefunx {unsigned long} gh_scm2ulong (SCM @var{obj}) @@ -495,7 +495,7 @@ that is, data will be copied as if the destination array was unsigned. @node Type predicates -@section Type predicates +@subsection Type predicates These C functions mirror Scheme's type predicate procedures with one important difference. The C routines return C boolean values (0 and 1) @@ -544,7 +544,7 @@ Returns 1 if @var{val} is an exact number, 0 otherwise. @node Equality predicates -@section Equality predicates +@subsection Equality predicates These C functions mirror Scheme's equality predicate procedures with one important difference. The C routines return C boolean values (0 and 1) @@ -580,7 +580,7 @@ Returns 1 if @var{l} is an empty list or pair; 0 otherwise. @node Memory allocation and garbage collection -@section Memory allocation and garbage collection +@subsection Memory allocation and garbage collection @c [FIXME: flesh this out with some description of garbage collection in @c scm/guile] @@ -592,7 +592,7 @@ Returns 1 if @var{l} is an empty list or pair; 0 otherwise. @node Calling Scheme procedures from C -@section Calling Scheme procedures from C +@subsection Calling Scheme procedures from C Many of the Scheme primitives are available in the @code{gh_} interface; they take and return objects of type SCM, and one could @@ -826,11 +826,11 @@ here. @node Mixing gh and scm APIs -@section Mixing gh and scm APIs +@subsection Mixing gh and scm APIs @node scm transition summary -@section Transitioning to the scm Interface +@subsection Transitioning to the scm Interface The following table summarizes the available information on how to transition from the GH to the scm interface. Where transitioning is not diff --git a/doc/ref/guile.texi b/doc/ref/guile.texi index 35e3a22bb..8a7c4fbe6 100644 --- a/doc/ref/guile.texi +++ b/doc/ref/guile.texi @@ -10,22 +10,19 @@ @copying This reference manual documents Guile, GNU's Ubiquitous Intelligent -Language for Extensions, manual edition @value{MANUAL-EDITION} +Language for Extensions. This is edition @value{MANUAL-EDITION} corresponding to Guile @value{VERSION}. Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 Free Software Foundation. -Permission is granted to copy, distribute and/or modify this -document under the terms of the GNU Free Documentation License, -Version 1.2 or any later version published by the Free Software -Foundation; with the no Invariant Sections, with the Front-Cover -Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in -(a) below. A copy of the license is included in the section -entitled "GNU Free Documentation License". - -(a) The FSF's Back-Cover Text is: ``You are free to copy and modify -this GNU Manual.'' +Permission is granted to copy, distribute and/or modify this document +under the terms of the GNU Free Documentation License, Version 1.2 or +any later version published by the Free Software Foundation; with the +no Invariant Sections, with the Front-Cover Texts being ``A GNU +Manual,'' and with the Back-Cover Text ``You are free to copy and +modify this GNU Manual.''. A copy of the license is included in the +section entitled "GNU Free Documentation License". @end copying @@ -124,14 +121,14 @@ x * Guile Reference: (guile). The Guile reference manual. @end direntry -@setchapternewpage off +@setchapternewpage odd @titlepage @sp 10 @comment The title is printed in a large font. @title Guile Reference Manual @subtitle Edition @value{MANUAL-EDITION}, for use with Guile @value{VERSION} -@subtitle $Id: guile.texi,v 1.29 2004-02-18 20:07:19 mvo Exp $ +@c @subtitle $Id: guile.texi,v 1.30 2004-04-21 14:32:24 mvo Exp $ @c See preface.texi for the list of authors @author The Guile Developers @@ -151,7 +148,7 @@ x @set example-dir doc/examples @ifnottex -@node Top, Contributors, (dir), (dir) +@node Top, Preface, (dir), (dir) @top The Guile Reference Manual @insertcopying @@ -159,78 +156,20 @@ x @end ifnottex @menu -Preface - -* Contributors:: Contributors to this manual. -* Guile License:: Conditions for copying and using Guile. -* Manual Layout:: How to read the rest of this manual. -* Manual Conventions:: Conventional terminology. - -Part I: Introduction to Guile - -* What is Guile?:: And what does it do? -* Whirlwind Tour:: An introductory whirlwind tour. -* Obtaining and Installing Guile:: -* Reporting Bugs:: Reporting bugs in Guile or this manual. - -Part II: Writing and Running Guile Scheme - -* Running Intro:: Introduction to this part. -* Guile Scheme:: Guile's implementation of Scheme. -* Guile Scripting:: How to write Guile scripts. -* Command Line Handling:: Command line options and arguments. -* Debugging Features:: Features for debugging errors. -* Autoconf Support:: Guile-specific configure.in macros. -* Miscellaneous Tools:: Snarfing, linting, etc. -* Basic Ideas:: Basic ideas in Scheme. -* Further Reading:: Where to find out more about Scheme. - -Part III: Guile as an Extension Language - -* Programming Intro:: Introduction to this part. -* Libguile Intro:: Using Guile as an extension language. -* Programming Overview:: An overview of Guile programming. -* Data Representation:: Data representation in Guile. -* GH:: The deprecated GH interface. -Part IV: Guile API Reference +* Preface:: +* Introduction to Guile:: -* Reference Intro:: Introduction to the Guile API reference. -* API Overview:: Overview of the Guile API. -* Simple Data Types:: Numbers, strings, booleans and so on. -* Compound Data Types:: Data types for holding other data. -* Procedures and Macros:: Procedures and macros. -* Utility Functions:: General utility functions. -* Binding Constructs:: Definitions and variable bindings. -* Control Mechanisms:: Controlling the flow of program execution. -* Input and Output:: Ports, reading and writing. -* Read/Load/Eval:: Reading and evaluating Scheme code. -* Memory Management:: Memory management and garbage collection. -* Objects:: Low level object orientation support. -* Modules:: Designing reusable code libraries. -* Scheduling:: Threads, mutexes, asyncs and dynamic roots. -* Options and Config:: Configuration, features and runtime options. -* Translation:: Support for translating other languages. -* Debugging:: Internal debugging interface. -* Deprecated:: Features that are planned to disappear. +* Programming in Scheme:: +* Programming in C:: -Part V: Guile Modules +* API Reference:: -* SLIB:: Using the SLIB Scheme library. -* POSIX:: POSIX system calls and networking. -* SRFI Support:: Support for various SRFIs. -* Readline Support:: Module for using the readline library. -* Value History:: Maintaining a value history in the REPL. -* Pretty Printing:: Nicely formatting Scheme objects for output. -* Formatted Output:: The @code{format} procedure. -* Rx Regexps:: The Rx regular expression library. -* File Tree Walk:: Traversing the file system. -* Queues:: First-in first-out queuing. -* Expect:: Controlling interactive programs with Guile. -* The Scheme shell (scsh):: Using scsh interfaces in Guile. +* Guile Modules:: Appendices +* Data Representation:: All the details. * GNU Free Documentation License:: The license of this manual. Indices @@ -247,16 +186,10 @@ Indices @include preface.texi -@iftex -@page -@unnumbered{Part I: Introduction to Guile} -@end iftex - @include intro.texi -@page -@node Running Intro -@unnumbered Part II: Writing and Running Guile Scheme +@node Programming in Scheme +@chapter Programming in Scheme Guile's core language is Scheme, and an awful lot can be achieved simply by using Guile to write and run Scheme programs. In this part of the @@ -269,49 +202,108 @@ includes a chapter that presents the basic concepts of the language, and gives references to freely available Scheme tutorial material on the web. -For detailed reference information on the variables, functions etc. that -make up Guile's application programming interface (API), please refer to -Part IV (@pxref{Reference Intro,,Part IV --- Guile API Reference}). +For detailed reference information on the variables, functions +etc. that make up Guile's application programming interface (API), +@xref{API Reference}. + +@menu +* Basic Ideas:: Basic ideas in Scheme. +* Guile Scheme:: Guile's implementation of Scheme. +* Guile Scripting:: How to write Guile scripts. +* Debugging Features:: Features for finding errors. +* Further Reading:: Where to find out more about Scheme. +@end menu +@include scheme-ideas.texi @include scheme-intro.texi @include scripts.texi -@include script-getopt.texi @include debugging.texi -@include autoconf.texi -@include tools.texi -@include scheme-ideas.texi @include scheme-reading.texi -@page -@node Programming Intro -@unnumbered Part III: Guile as an Extension Language - -In this part of the manual, we aim to present a wide ranging picture of -what it means to use Guile as an application extension language, to -provide guidance, practical guidelines and tips for @emph{how} to -program in Guile, and to document the tools that are available to help -you with your programming. For detailed reference information on the -variables, functions etc. that make up Guile's application programming -interface (API), please refer to Part IV (@pxref{Reference Intro,,Part -IV --- Guile API Reference}). - -@include extend.texi +@node Programming in C +@chapter Programming in C + +This part of the manual explains the general concepts that you need to +understand when interfacing to Guile from C. You will learn about how +the latent typing of Scheme is embedded into the static typing of C, how +the garbage collection of Guile is made available to C code, and how +continuations influence the control flow in a C program. + +This knowledge should make it straightforward to add new functions to +Guile that can be called from Scheme. Adding new data types is also +possible and is done by defining @dfn{smobs}. + +The @ref{Programming Overview} section of this part contains general +musings and guidelines about programming with Guile. It explores +different ways to design aprogram around Guile, or how to embed Guile +into existing programs. + +There is also a pedagogical yet detailed explanation of how the data +representation of Guile is implemented, @xref{Data Representation}. +You don't need to know the details given there to use Guile from C, +but they are useful when you want to modify Guile itself or when you +are just curious about how it is all done. + +For detailed reference information on the variables, functions +etc. that make up Guile's application programming interface (API), +@xref{API Reference}. + +@menu +* Linking Programs With Guile:: More precisely, with the libguile library. +* Linking Guile with Libraries:: To extend Guile itself. +* General Libguile Concepts:: General concepts for using libguile. +* Defining New Types (Smobs):: Adding new types to Guile. +* Function Snarfing:: A way to define new functions. +* Programming Overview:: An overview of Guile programming. +@end menu + +@include libguile-linking.texi +@include libguile-extensions.texi +@include libguile-concepts.texi +@include libguile-smobs.texi +@include libguile-snarf.texi @include program.texi -@include data-rep.texi -@include gh.texi -@page -@node Reference Intro -@unnumbered Part IV: Guile API Reference +@node API Reference +@chapter API Reference Guile provides an application programming interface (@dfn{API}) to developers in two core languages: Scheme and C. This part of the manual contains reference documentation for all of the functionality that is available through both Scheme and C interfaces. +@menu +* API Overview:: Overview of the Guile API. +* The @code{SCM} Type:: The fundamental data type for C code. +* Initialization:: Initializing Guile. +* Snarfing Macros:: Macros for snarfing initialization actions. +* Simple Data Types:: Numbers, strings, booleans and so on. +* Compound Data Types:: Data types for holding other data. +* Smobs:: Defining new data types in C. +* Procedures and Macros:: Procedures and macros. +* Utility Functions:: General utility functions. +* Binding Constructs:: Definitions and variable bindings. +* Control Mechanisms:: Controlling the flow of program execution. +* Input and Output:: Ports, reading and writing. +* Read/Load/Eval:: Reading and evaluating Scheme code. +* Memory Management:: Memory management and garbage collection. +* Objects:: Low level object orientation support. +* Modules:: Designing reusable code libraries. +* Scheduling:: Threads, mutexes, asyncs and dynamic roots. +* Options and Config:: Configuration, features and runtime options. +* Translation:: Support for translating other languages. +* Debugging:: Internal debugging interface. +* Deprecated:: Features that are planned to disappear. +* GH:: The deprecated GH interface. +@end menu + @include scm.texi +@include scheme-scm.texi +@include ref-init.texi +@include scheme-snarf.texi @include scheme-data.texi @include scheme-compound.texi +@include scheme-smobs.texi @include scheme-procedures.texi @include scheme-utility.texi @include scheme-binding.texi @@ -326,20 +318,37 @@ available through both Scheme and C interfaces. @include scheme-translation.texi @include scheme-debug.texi @include deprecated.texi +@include gh.texi -@iftex -@page -@unnumbered{Part V: Guile Modules} -@end iftex +@node Guile Modules +@chapter Guile Modules + +@menu +* SLIB:: Using the SLIB Scheme library. +* POSIX:: POSIX system calls and networking. +* getopt-long:: Command line handling. +* SRFI Support:: Support for various SRFIs. +* Readline Support:: Module for using the readline library. +* Value History:: Maintaining a value history in the REPL. +* Pretty Printing:: Nicely formatting Scheme objects for output. +* Formatted Output:: The @code{format} procedure. +* Rx Regexps:: The Rx regular expression library. +* File Tree Walk:: Traversing the file system. +* Queues:: First-in first-out queuing. +* Expect:: Controlling interactive programs with Guile. +* The Scheme shell (scsh):: Using scsh interfaces in Guile. +@end menu @include slib.texi @include posix.texi +@include mod-getopt-long.texi @include srfi-modules.texi @include repl-modules.texi @include misc-modules.texi @include expect.texi @include scsh.texi +@include data-rep.texi @include fdl.texi @iftex diff --git a/doc/ref/indices.texi b/doc/ref/indices.texi index a715b3084..7772bdc95 100644 --- a/doc/ref/indices.texi +++ b/doc/ref/indices.texi @@ -25,7 +25,7 @@ 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}. +@xref{API Overview}. @printindex fn @@ -42,7 +42,7 @@ 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}. +in the section @xref{API Overview}. @printindex vr diff --git a/doc/ref/intro.texi b/doc/ref/intro.texi index 01c581714..e09a797c5 100644 --- a/doc/ref/intro.texi +++ b/doc/ref/intro.texi @@ -4,9 +4,18 @@ @c Free Software Foundation, Inc. @c See the file guile.texi for copying conditions. -@page +@node Introduction to Guile +@chapter Introduction to Guile + +@menu +* What is Guile?:: +* Obtaining and Installing Guile:: +* Whirlwind Tour:: +* Reporting Bugs:: +@end menu + @node What is Guile? -@chapter What is Guile? +@section What is Guile? Guile is an interpreter for the Scheme programming language, packaged for use in a wide variety of environments. Guile implements Scheme as @@ -54,26 +63,75 @@ can program applications which use Guile in the language of their choice, rather than having the tastes of the application's author imposed on them. +@node Obtaining and Installing Guile +@section Obtaining and Installing Guile + +Guile can be obtained from the main GNU archive site +@url{ftp://ftp.gnu.org} or any of its mirrors. The file will be named +guile-version.tar.gz. The current version is @value{VERSION}, so the +file you should grab is: + +@url{ftp://ftp.gnu.org/pub/gnu/guile-@value{VERSION}.tar.gz} + +To unbundle Guile use the instruction + +@example +zcat guile-@value{VERSION}.tar.gz | tar xvf - +@end example + +which will create a directory called @file{guile-@value{VERSION}} with +all the sources. You can look at the file @file{INSTALL} for detailed +instructions on how to build and install Guile, but you should be able +to just do + +@example +cd guile-@value{VERSION} +./configure +make +make install +@end example + +This will install the Guile executable @file{guile}, the Guile library +@file{-lguile} and various associated header files and support +libraries. It will also install the Guile tutorial and reference +manual. + +@c [[include instructions for getting R5RS]] + +Since this manual frequently refers to the Scheme ``standard'', also +known as R5RS, or the +@iftex +``Revised$^5$ Report on the Algorithmic Language Scheme'', +@end iftex +@ifnottex +``Revised^5 Report on the Algorithmic Language Scheme'', +@end ifnottex +we have included the report in the Guile distribution; +@xref{Top, , Introduction, r5rs, Revised(5) Report on the Algorithmic +Language Scheme}. +This will also be installed in your info directory. -@page @node Whirlwind Tour -@chapter A Whirlwind Tour +@section A Whirlwind Tour This chapter presents a quick tour of all the ways that Guile can be used. There are additional examples in the @file{examples/} directory in the Guile source distribution. +The following examples assume that Guile has been installed in +@code{/usr/local/}. + @menu * Running Guile Interactively:: -* Guile Scripts:: -* Linking Programs With Guile:: -* Writing Extensions for Guile:: -* Guile Modules:: +* Running Guile Scripts:: +* Linking Guile into Programs:: +* Writing Guile Extensions:: +* Using the Guile Module System:: @end menu @node Running Guile Interactively -@section Running Guile Interactively +@subsection Running Guile Interactively In its simplest form, Guile acts as an interactive interpreter for the Scheme programming language, reading and evaluating Scheme expressions @@ -96,393 +154,51 @@ guile> @kbd{C-d} $ @end example -@c [[When we get a fancier read-eval-print loop, with features for bouncing -@c around among modules, referring to the value of the last expression, -@c etc. then this section will get longer.]] - -@node Guile Scripts -@section Guile Scripts +@node Running Guile Scripts +@subsection Running Guile Scripts 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. -Before we present the details, here is a trivial Guile script: - -@example -#!/usr/local/bin/guile -s -!# -(display "Hello, world!") -(newline) -@end example - -@menu -* The Top of a Script File:: How to start a Guile script. -* Scripting Examples:: Simple Guile scripts, explained. -@end menu - - -@node The Top of a Script File -@subsection The Top of a Script File - -The first line of a Guile script must tell the operating system to use -Guile to evaluate the script, and then tell Guile how to go about doing -that. Here is the simplest case: - -@itemize @bullet - -@item -The first two characters of the file must be @samp{#!}. - -The operating system interprets this to mean that the rest of the line -is the name of an executable that can interpret the script. Guile, -however, interprets these characters as the beginning of a multi-line -comment, terminated by the characters @samp{!#} on a line by themselves. -(This is an extension to the syntax described in R5RS, added to support -shell scripts.) +Here is a trivial Guile script, for more details @xref{Guile Scripting}. -@item -Immediately after those two characters must come the full pathname to -the Guile interpreter. On most systems, this would be -@samp{/usr/local/bin/guile}. - -@item -Then must come a space, followed by a command-line argument to pass to -Guile; this should be @samp{-s}. This switch tells Guile to run a -script, instead of soliciting the user for input from the terminal. -There are more elaborate things one can do here; see @ref{The Meta -Switch}. - -@item -Follow this with a newline. - -@item -The second line of the script should contain only the characters -@samp{!#} --- just like the top of the file, but reversed. The -operating system never reads this far, but Guile treats this as the end -of the comment begun on the first line by the @samp{#!} characters. - -@item -The rest of the file should be a Scheme program. - -@end itemize - -Guile reads the program, evaluating expressions in the order that they -appear. Upon reaching the end of the file, Guile exits. - -The function @code{command-line} returns the name of the script file and -any command-line arguments passed by the user, as a list of strings. - -For example, consider the following script file: -@example -#!/usr/local/bin/guile -s -!# -(write (command-line)) -(newline) -@end example - -If you put that text in a file called @file{foo} in the current -directory, then you could make it executable and try it out like this: -@example -$ chmod a+x foo -$ ./foo -("./foo") -$ ./foo bar baz -("./foo" "bar" "baz") -$ -@end example - -As another example, here is a simple replacement for the POSIX -@code{echo} command: -@example -#!/usr/local/bin/guile -s -!# -(for-each (lambda (s) (display s) (display " ")) - (cdr (command-line))) -(newline) -@end example - -@deffn {Scheme Procedure} command-line -@deffnx {Scheme Procedure} program-arguments -Return a list of the command-line arguments passed to the currently -running program. If the program invoked Guile with the @samp{-s}, -@samp{-c} or @samp{--} switches, these procedures ignore everything up -to and including those switches. -@end deffn - - -@node Scripting Examples -@subsection Scripting Examples - -To start with, here are some examples of invoking Guile directly: - -@table @code - -@item guile -- a b c -Run Guile interactively; @code{(command-line)} will return @* -@code{("/usr/local/bin/guile" "a" "b" "c")}. - -@item guile -s /u/jimb/ex2 a b c -Load the file @file{/u/jimb/ex2}; @code{(command-line)} will return @* -@code{("/u/jimb/ex2" "a" "b" "c")}. - -@item guile -c '(write %load-path) (newline)' -Write the value of the variable @code{%load-path}, print a newline, -and exit. - -@item guile -e main -s /u/jimb/ex4 foo -Load the file @file{/u/jimb/ex4}, and then call the function -@code{main}, passing it the list @code{("/u/jimb/ex4" "foo")}. - -@item guile -l first -ds -l last -s script -Load the files @file{first}, @file{script}, and @file{last}, in that -order. The @code{-ds} switch says when to process the @code{-s} -switch. For a more motivated example, see the scripts below. - -@end table - - -Here is a very simple Guile script: @example #!/usr/local/bin/guile -s !# (display "Hello, world!") (newline) @end example -The first line marks the file as a Guile script. When the user invokes -it, the system runs @file{/usr/local/bin/guile} to interpret the script, -passing @code{-s}, the script's filename, and any arguments given to the -script as command-line arguments. When Guile sees @code{-s -@var{script}}, it loads @var{script}. Thus, running this program -produces the output: -@example -Hello, world! -@end example - -Here is a script which prints the factorial of its argument: -@example -#!/usr/local/bin/guile -s -!# -(define (fact n) - (if (zero? n) 1 - (* n (fact (- n 1))))) - -(display (fact (string->number (cadr (command-line))))) -(newline) -@end example -In action: -@example -$ fact 5 -120 -$ -@end example - -However, suppose we want to use the definition of @code{fact} in this -file from another script. We can't simply @code{load} the script file, -and then use @code{fact}'s definition, because the script will try to -compute and display a factorial when we load it. To avoid this problem, -we might write the script this way: - -@example -#!/usr/local/bin/guile \ --e main -s -!# -(define (fact n) - (if (zero? n) 1 - (* n (fact (- n 1))))) - -(define (main args) - (display (fact (string->number (cadr args)))) - (newline)) -@end example -This version packages the actions the script should perform in a -function, @code{main}. This allows us to load the file purely for its -definitions, without any extraneous computation taking place. Then we -used the meta switch @code{\} and the entry point switch @code{-e} to -tell Guile to call @code{main} after loading the script. -@example -$ fact 50 -30414093201713378043612608166064768844377641568960512000000000000 -@end example - -Suppose that we now want to write a script which computes the -@code{choose} function: given a set of @var{m} distinct objects, -@code{(choose @var{n} @var{m})} is the number of distinct subsets -containing @var{n} objects each. It's easy to write @code{choose} given -@code{fact}, so we might write the script this way: -@example -#!/usr/local/bin/guile \ --l fact -e main -s -!# -(define (choose n m) - (/ (fact m) (* (fact (- m n)) (fact n)))) - -(define (main args) - (let ((n (string->number (cadr args))) - (m (string->number (caddr args)))) - (display (choose n m)) - (newline))) -@end example - -The command-line arguments here tell Guile to first load the file -@file{fact}, and then run the script, with @code{main} as the entry -point. In other words, the @code{choose} script can use definitions -made in the @code{fact} script. Here are some sample runs: -@example -$ choose 0 4 -1 -$ choose 1 4 -4 -$ choose 2 4 -6 -$ choose 3 4 -4 -$ choose 4 4 -1 -$ choose 50 100 -100891344545564193334812497256 -@end example -@node Linking Programs With Guile -@section Linking Programs With Guile +@node Linking Guile into Programs +@subsection Linking Guile into Programs The Guile interpreter is available as an object library, to be linked into applications using Scheme as a configuration or extension -language. This chapter covers the mechanics of linking your program -with Guile on a typical POSIX system. - -Parts III and IV of this manual describe the C functions Guile provides. -Furthermore, any Scheme function described in this manual as a -``Primitive'' is also callable from C; see @ref{Primitives}. - -The header file @code{<libguile.h>} provides declarations for all of -Guile's functions and constants. You should @code{#include} it at the -head of any C source file that uses identifiers described in this -manual. Once you've compiled your source files, you need to link them -against the Guile object code library, @code{libguile}. - -On most systems, you should not need to tell the compiler and linker -explicitly where they can find @file{libguile.h} and @file{libguile}. -When Guile has been installed in a peculiar way, or when you are on a -peculiar system, things might not be so easy and you might need to pass -additional @code{-I} or @code{-L} options to the compiler. Guile -provides the utility program @code{guile-config} to help you find the -right values for these options. You would typically run -@code{guile-config} during the configuration phase of your program and -use the obtained information in the Makefile. +language. -@menu -* Guile Initialization Functions:: What to call first. -* A Sample Guile Main Program:: Sources and makefiles. -@end menu - - -@node Guile Initialization Functions -@subsection Guile Initialization Functions - -To initialize Guile, you can use one of two functions. The first, -@code{scm_boot_guile}, is the most portable way to initialize Guile. It -should be used whenever you have control over the main function of your -program because it never returns. The second function, -@code{scm_init_guile}, does return and can thus be used in more -situations. However, @code{scm_init_guile} is not as widely available -as @code{scm_boot_guile} because it needs to rely on non-portable code -to find the stack bounds. When Guile does not know how to find these -bounds on your system, it will not provide @code{scm_init_guile}. - -When you can tolerate the limits of @code{scm_boot_guile}, you should -use it in favor of @code{scm_init_guile} since that will make your -program more portable. - -@deftypefun void scm_boot_guile (int @var{argc}, char **@var{argv}, void (*@var{main_func}) (), void *@var{closure}) -Initialize the Guile Scheme interpreter. Then call @var{main_func}, -passing it @var{closure}, @var{argc}, and @var{argv}. @var{main_func} -should do all the work of the program (initializing other packages, -defining application-specific functions, reading user input, and so on) -before returning. When @var{main_func} returns, call @code{exit (0)}; -@code{scm_boot_guile} never returns. If you want some other exit value, -have @var{main_func} call exit itself. - -@code{scm_boot_guile} arranges for the Scheme @code{command-line} -function to return the strings given by @var{argc} and @var{argv}. If -@var{main_func} modifies @var{argc} or @var{argv}, it should call -@code{scm_set_program_arguments} with the final list, so Scheme code -will know which arguments have been processed. - -Why must the caller do all the real work from @var{main_func}? Guile's -garbage collector scans the stack to find all local variables that -reference Scheme objects. To do this, it needs to know the bounds of -the stack that might contain such references. Because there is no -portable way in C to find the base of the stack, @code{scm_boot_guile} -assumes that all references are above its own stack frame. If you try -to manipulate Scheme objects after this function returns, it's the luck -of the draw whether Guile's storage manager will be able to find the -objects you allocate. So, @code{scm_boot_guile} function exits, rather -than returning, to discourage you from making that mistake. - -See @code{scm_init_guile}, below, for a function that can find the real -base of the stack, but not in a portable way. -@end deftypefun - -@deftypefun void scm_init_guile () -Initialize the Guile Scheme interpreter. - -In contrast to @code{scm_boot_guile}, this function knows how to find -the true base of the stack and thus does not need to usurp the control -flow of your program. However, since finding the stack base can not be -done portably, this function might not be available in all installations -of Guile. If you can, you should use @code{scm_boot_guile} instead. - -Note that @code{scm_init_guile} does not inform Guile about the command -line arguments that should be returned by the Scheme function -@code{command-line}. You can use @code{scm_set_program_arguments} to do -this. -@end deftypefun - -One common way to use Guile is to write a set of C functions which -perform some useful task, make them callable from Scheme, and then link -the program with Guile. This yields a Scheme interpreter just like -@code{guile}, but augmented with extra functions for some specific -application --- a special-purpose scripting language. - -In this situation, the application should probably process its -command-line arguments in the same manner as the stock Guile -interpreter. To make that straightforward, Guile provides this -function: - -@deftypefun void scm_shell (int @var{argc}, char **@var{argv}) -Process command-line arguments in the manner of the @code{guile} -executable. This includes loading the normal Guile initialization -files, interacting with the user or running any scripts or expressions -specified by @code{-s} or @code{-e} options, and then exiting. -@xref{Invoking Guile}, for more details. - -Since this function does not return, you must do all -application-specific initialization before calling this function. -@end deftypefun - - -@node A Sample Guile Main Program -@subsection A Sample Guile Main Program - -Here is @file{simple-guile.c}, source code for a @code{main} and an -@code{inner_main} function that will produce a complete Guile -interpreter. +Here is @file{simple-guile.c}, source code for a program that will +produce a complete Guile interpreter. In addition to all usual +functions provided by Guile, it will also offer the function +@code{my-hostname}. @example -/* simple-guile.c --- how to start up the Guile - interpreter from C code. */ - -/* Get declarations for all the scm_ functions. */ +#include <stdlib.h> #include <libguile.h> +static SCM +my_hostname (void) +@{ + return scm_str2string (getenv ("HOSTNAME")); +@} + static void -inner_main (void *closure, int argc, char **argv) +inner_main (void *data, int argc, char **argv) @{ - /* module initializations would go here */ + scm_c_define_gsubr ("my-hostname", 0, 0, 0, my_hostname); scm_shell (argc, argv); @} @@ -494,155 +210,36 @@ main (int argc, char **argv) @} @end example -The @code{main} function calls @code{scm_boot_guile} to initialize -Guile, passing it @code{inner_main}. Once @code{scm_boot_guile} is -ready, it invokes @code{inner_main}, which calls @code{scm_shell} to -process the command-line arguments in the usual way. +When Guile is correctly installed on your system, the above program +can be compiled and linked like this: -Here is a Makefile which you can use to compile the above program. It -uses @code{guile-config} to learn about the necessary compiler and -linker flags. @example -# Use GCC, if you have it installed. -CC=gcc - -# Tell the C compiler where to find <libguile.h> -CFLAGS=`guile-config compile` - -# Tell the linker what libraries to use and where to find them. -LIBS=`guile-config link` - -simple-guile: simple-guile.o - $@{CC@} simple-guile.o $@{LIBS@} -o simple-guile - -simple-guile.o: simple-guile.c - $@{CC@} -c $@{CFLAGS@} simple-guile.c -@end example - -If you are using the GNU Autoconf package to make your application more -portable, Autoconf will settle many of the details in the Makefile above -automatically, making it much simpler and more portable; we recommend -using Autoconf with Guile. Guile also provides the @code{GUILE_FLAGS} -macro for autoconf that performs all necessary checks. Here is a -@file{configure.in} file for @code{simple-guile} that uses this macro. -Autoconf can use as this file as template to generate a @code{configure} -script. In order for Autoconf to find the @code{GUILE_FLAGS} macro, you -will need to run @code{aclocal} first. This is not really Guile -specific, so you should refer to the Autoconf documentation REFFIXME -when in doubt. -@example -AC_INIT(simple-guile.c) - -# Find a C compiler. -AC_PROG_CC - -# Check for Guile -GUILE_FLAGS - -# Generate a Makefile, based on the results. -AC_OUTPUT(Makefile) +$ gcc -o simple-guile simple-guile.c -lguile @end example -Here is a @code{Makefile.in} template, from which the @code{configure} -script produces a Makefile customized for the host system: -@example -# The configure script fills in these values. -CC=@@CC@@ -CFLAGS=@@GUILE_CFLAGS@@ -LIBS=@@GUILE_LDFLAGS@@ - -simple-guile: simple-guile.o - $@{CC@} simple-guile.o $@{LIBS@} -o simple-guile -simple-guile.o: simple-guile.c - $@{CC@} -c $@{CFLAGS@} simple-guile.c -@end example - -The developer should use Autoconf to generate the @file{configure} -script from the @file{configure.in} template, and distribute -@file{configure} with the application. Here's how a user might go about -building the application: +When it is run, it behaves just like the @code{guile} program except +that you can also call the new @code{my-hostname} function. @example -$ ls -Makefile.in configure* configure.in simple-guile.c -$ ./configure -creating cache ./config.cache -checking for gcc... (cached) gcc -checking whether the C compiler (gcc ) works... yes -checking whether the C compiler (gcc ) is a cross-compiler... no -checking whether we are using GNU C... (cached) yes -checking whether gcc accepts -g... (cached) yes -checking for Guile... yes -creating ./config.status -creating Makefile -$ make -gcc -c -I/usr/local/include simple-guile.c -gcc simple-guile.o -L/usr/local/lib -lguile -lqthreads -lpthread -lm -o simple-guile $ ./simple-guile guile> (+ 1 2 3) 6 -guile> (getpwnam "jimb") -#("jimb" "83Z7d75W2tyJQ" 4008 10 "Jim Blandy" "/u/jimb" - "/usr/local/bin/bash") -guile> (exit) -$ +guile> (my-hostname) +"burns" @end example +@node Writing Guile Extensions +@subsection Writing Guile Extensions -@node Writing Extensions for Guile -@section Writing Extensions for Guile - -The previous sections have briefly explained how to write programs that -make use of an embedded Guile interpreter. But sometimes, all you want -to do is make new primitive procedures and data types available to the -Scheme programmer. Writing a new version of @code{guile} is -inconvenient in this case and it would in fact make the life of the -users of your new features needlessly hard. - -@c [[ the following is probably a bit long-winded ]] - -For example, suppose that there is a program @code{guile-db} that is a -version of Guile with additional features for accessing a database. -People who want to write Scheme programs that use these features would -have to use @code{guile-db} instead of the usual @code{guile} program. -Now suppose that there is also a program @code{guile-gtk} that extends -Guile with access to the popular Gtk+ toolkit for graphical user -interfaces. People who want to write GUIs in Scheme would have to use -@code{guile-gtk}. Now, what happens when you want to write a Scheme -application that uses a GUI to let the user access a database? You -would have to write a @emph{third} program that incorporates both the -database stuff and the GUI stuff. This might not be easy (because -@code{guile-gtk} might be a quite obscure program, say) and taking this -example further makes it easy to see that this approach can not work in -practice. - -It would have been much better if both the database features and the GUI -feature had been provided as libraries that can just be linked with -@code{guile}. Guile makes it easy to do just this, and we encourage you -to make your extensions to Guile available as libraries whenever -possible. - -You write the new primitive procedures and data types in the normal -fashion, and link them into a shared library instead of into a -stand-alone program. The shared library can then be loaded dynamically -by Guile. - -@menu -* A Sample Guile Extension:: -@end menu +You can link Guile into your program and make Scheme available to the +users of your program. You can also link your library into Guile and +make its functionality available to all users of Guile. +A library that is linked into Guile is called an @dfn{extensions}, but +it really just is an ordinary object library. -@node A Sample Guile Extension -@subsection A Sample Guile Extension - -This section explains how to make the Bessel functions of the C library -available to Scheme. 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. - -Consider the following file @file{bessel.c}. +The following example shows how to write a simple extension for Guile +that makes the @code{j0} function available to Scheme code. @smallexample #include <math.h> @@ -672,33 +269,19 @@ For creating shared libraries portably, we recommend the use of @code{GNU Libtool}. A shared library can be loaded into a running Guile process with the -function @code{load-extension}. In addition to the name of the -library to load, this function also expects the name of function from -that library that will be called to initialize it. For our example, -we are going to call the function @code{init_bessel} which will make -@code{j0_wrapper} available to Scheme programs with the name -@code{j0}. Note that we do not specify a filename extension such as -@file{.so} when invoking @code{load-extension}. The right extension for -the host platform will be provided automatically. - -@smalllisp -(load-extension "libguile-bessel" "init_bessel") -(j0 2) -@result{} 0.223890779141236 -@end smalllisp - -For this to work, @code{load-extension} must be able to find -@file{libguile-bessel}, of course. It will look in the places that -are usual for your operating system, and it will additionally look -into the directories listed in the @code{LTDL_LIBRARY_PATH} -environment variable. +function @code{load-extension}. The @code{j0} is then immediately +available: -To see how these Guile extensions via shared libraries relate to the -module system, see below @xref{Intro to Modules and Extensions}. +@smallexample +$ guile +guile> (load-extension "./libguile-bessel" "init_bessel") +guile> (j0 2) +0.223890779141236 +@end smallexample -@node Guile Modules -@section Guile Modules +@node Using the Guile Module System +@subsection Using the Guile Module System Guile has support for dividing a program into @dfn{modules}. By using modules, you can group related code together and manage the @@ -711,274 +294,92 @@ Details on the module system beyond this introductory material can be found in @xref{Modules}. @menu -* Intro to Using Guile Modules:: -* Intro to Writing New Modules:: -* Intro to Modules and Extensions:: +* Using Modules:: +* Writing new Modules:: +* Putting Extensions into Modules:: @end menu -@node Intro to Using Guile Modules -@subsection Intro to Using Existing Modules +@node Using Modules +@subsubsection Using Modules Guile comes with a lot of useful modules, for example for string processing or command line parsing. Additionally, there exist many Guile modules written by other Guile hackers, but which have to be installed manually. -Existing modules have to be placed in places where Guile looks for them -by default or in colon-separated directories in the environment variable -@code{GUILE_LOAD_PATH}. When this variable is set, those directories -are searched first, then the the default. The following command -shows the complete list of directories searched: +Here is a sample interactive session that shows how to use the +@code{(ice-9 popen)} module which provides the means for communicating +with other processes over pipes together with the @code{(ice-9 +rdelim)} module that provides the function @code{read-line}. @smallexample -guile -c '(write %load-path) (newline)' -@end smallexample - -Suppose you want to use the procedures and variables exported by the -module @code{(ice-9 popen)}, which provides the means for communicating -with other processes over pipes. Add the following line to your -currently running Guile REPL or the top of your script file. - -@lisp -(use-modules (ice-9 popen)) -@end lisp - -This will load the module and make the procedures exported by -@code{(ice-9 popen)} automatically available. The next step could be -to open a pipe to @file{ls} and read the contents of the current -directory, one line at a time. For the latter, we use the function -@code{read-line}, which can be found in the module @code{(ice-9 -rdelim)}, so we use that module as well. - -@lisp -(use-modules (ice-9 rdelim)) -(define p (open-input-pipe "ls -l")) -(read-line p) -@result{} +$ guile +guile> (use-modules (ice-9 popen)) +guile> (use-modules (ice-9 rdelim)) +guile> (define p (open-input-pipe "ls -l")) +guile> (read-line p) "total 30" -(read-line p) -@result{} +guile> (read-line p) "drwxr-sr-x 2 mgrabmue mgrabmue 1024 Mar 29 19:57 CVS" -@end lisp - -The macro @code{use-modules} can take any number of modules to use. -Therefore, we could have written the two @code{use-modules} statements -in the code above as +@end smallexample -@lisp -(use-modules (ice-9 popen) (ice-9 rdelim)) -@end lisp +@node Writing new Modules +@subsubsection Writing new Modules -@node Intro to Writing New Modules -@subsection Intro to Writing New Modules +You can create new modules using the syntactic form +@code{define-module}. All definitions following this form until the +next @code{define-module} are placed into the new module. -Of course it is possible to write modules yourself. Using modules for -structuring your programs makes them more readable and lets you -distribute them more easily. Also, explicitly defining the procedures -and variables which are exported from a module adds documentation to the -source and specifies the interface a module provides. +One module is usually placed into one file, and that file is installed +in a location where Guile can automatically find it. The following +session shows a simple example. -In Guile, you can create new modules and switch to existing modules in -order to add bindings to them using the syntactic form -@code{define-module}. +@smallexample +$ cat /usr/local/share/guile/foo/bar.scm -@lisp (define-module (foo bar)) - -(define (frob x) x) -@end lisp - -Will create the module @code{(foo bar)}.@footnote{It is only convention -that the module names in this section have two elements. One or more -than two elements are perfectly fine, such as @code{(foo)} or @code{(foo -bar braz)}} All definitions following this statement will add bindings -to the module @code{(foo bar)}, and these bindings will not be visible -outside of the module. To make the bindings accessible to other -modules, you have to export them explicitly using one of the following -means: - -@itemize @bullet -@item -Export them with the @code{export} form: -@lisp (export frob) -@end lisp - -@item -Include them into the @code{define-module} form with the keyword -@code{export}: -@lisp -(define-module (foo bar) - #:export (frob)) -@end lisp -@item -Change the definition of @code{frob} to use @code{define-public}, which -is a combination of @code{define} and @code{export}. -@lisp -(define-public (frob x) x) -@end lisp -@end itemize - -After exporting, other modules can access the exported items simply by -using @code{use-modules} to load the module @code{(foo bar)}. +(define (frob x) (* 2 x)) +$ guile +guile> (use-modules (foo bar)) +guile> (frob 12) +24 +@end smallexample -@node Intro to Modules and Extensions -@subsection Intro to Modules and Extensions +@node Putting Extensions into Modules +@subsubsection Putting Extensions into Modules In addition to Scheme code you can also put things that are defined in C into a module. -You do this by writing a small Scheme file that defines the module. -That Scheme file in turn invokes @code{load-extension} to make the -features defined in C available. This works since all definitions -made by @code{scm_c_define_gsubr} etc. go into the @emph{current -module} and @code{define-module} causes the newly defined module to be -current while the code that follows it is executed. - -Suppose we want to put the Bessel function @code{j0} from the example -extension into a module called @code{(math bessel)}. We would have to -write a Scheme file with this contents +You do this by writing a small Scheme file that defines the module and +call @code{load-extension} directly in the body of the module. @smallexample -(define-module (math bessel)) +$ cat /usr/local/share/guile/math/bessel.scm +(define-module (math bessel)) (export j0) (load-extension "libguile-bessel" "init_bessel") -@end smallexample - -This file should of course be saved in the right place for -autoloading, for example as -@file{/usr/local/share/guile/math/bessel.scm}. -When @code{init_bessel} is called, the new @code{(math bessel)} module -is the current one. Thus, the call to @code{scm_c_define_gsubr} will -put the new definition for @code{j0} into it, just as we want it. - -The definitions made in the C code are not automatically exported from -a module. You need to explicitly list the ones you want to export in -@code{export} statements or with the @code{:export} option of -@code{define-module}. +$ file /usr/local/lib/libguile-bessel.so +@dots{} ELF 32-bit LSB shared object @dots{} +$ guile +guile> (use-modules (math bessel)) +guile> (j0 2) +0.223890779141236 +@end smallexample There is also a way to manipulate the module system from C but only Scheme files can be autoloaded. Thus, we recommend that you define your modules in Scheme. - -@page -@node Obtaining and Installing Guile -@chapter Obtaining and Installing Guile - -Here is the information you will need to get and install Guile and extra -packages and documentation you might need or find interesting. - -@menu -* The Basic Guile Package:: -* Packages not shipped with Guile:: -@end menu - - -@node The Basic Guile Package -@section The Basic Guile Package - -Guile can be obtained from the main GNU archive site -@url{ftp://ftp.gnu.org} or any of its mirrors. The file -will be named guile-version.tar.gz. The current version is -@value{VERSION}, so the file you should grab is: - -@url{ftp://ftp.gnu.org/pub/gnu/guile-@value{VERSION}.tar.gz} - -To unbundle Guile use the instruction - -@example -zcat guile-@value{VERSION}.tar.gz | tar xvf - -@end example - -which will create a directory called @file{guile-@value{VERSION}} with -all the sources. You can look at the file @file{INSTALL} for detailed -instructions on how to build and install Guile, but you should be able -to just do - -@example -cd guile-@value{VERSION} -./configure -make -make install -@end example - -This will install the Guile executable @file{guile}, the Guile library -@file{-lguile} and various associated header files and support -libraries. It will also install the Guile tutorial and reference -manual. - -@c [[include instructions for getting R5RS]] - -Since this manual frequently refers to the Scheme ``standard'', also -known as R5RS, or the -@iftex -``Revised$^5$ Report on the Algorithmic Language Scheme'', -@end iftex -@ifnottex -``Revised^5 Report on the Algorithmic Language Scheme'', -@end ifnottex -we have included the report in the Guile distribution; -@xref{Top, , Introduction, r5rs, Revised(5) Report on the Algorithmic -Language Scheme}. -This will also be installed in your info directory. - - -@node Packages not shipped with Guile -@section Packages not shipped with Guile - -We ship the Guile tutorial and reference manual with the Guile -distribution. Since the Scheme standard (R5RS) is a stable document, we -ship that too. - -Here are references (usually World Wide Web URLs) to some other freely -redistributable documents and packages which you might find useful if -you are using Guile. - -@table @strong -@item SCSH -the Scheme Shell. Gary Houston has ported SCSH to Guile. The relevant -chapter (@pxref{The Scheme shell (scsh)}) has references to the SCSH web -page with all its documentation. - -@item SLIB -a portable Scheme library maintained by Aubrey Jaffer. SLIB can be -obtained by ftp from @url{ftp://prep.ai.mit.edu/pub/gnu/jacal/}. - -The SLIB package should be unpacked somewhere in Guile's load path. It -will typically be unpacked in @file{/usr/local/share/guile/site}, so -that it will be @file{/usr/local/share/guile/site/slib}. - -Guile might have been installed with a different prefix, in which case -the load path can be checked from inside the interpreter with: - -@smalllisp -guile> %load-path -("/usr/local/share/guile/site" "/usr/local/share/guile/1.3a" "/usr/local/share/guile" ".") -@end smalllisp - -The relevant chapter (@pxref{SLIB}) has details on how to use SLIB with -Guile. - -@item JACAL -a symbolic math package by Aubrey Jaffer. The latest version of Jacal -can be obtained from @url{ftp://prep.ai.mit.edu/pub/gnu/jacal/}, and -should be unpacked in @file{/usr/local/share/guile/site/slib} so that -it will be in @file{/usr/local/share/guile/site/slib/jacal}. - -The relevant section (@pxref{JACAL}) has details on how to use Jacal. -@end table - - -@page @node Reporting Bugs -@chapter Reporting Bugs +@section Reporting Bugs Any problems with the installation should be reported to @email{bug-guile@@gnu.org}. diff --git a/doc/ref/libguile-concepts.texi b/doc/ref/libguile-concepts.texi new file mode 100644 index 000000000..870c051f3 --- /dev/null +++ b/doc/ref/libguile-concepts.texi @@ -0,0 +1,379 @@ +@c -*-texinfo-*- +@c This is part of the GNU Guile Reference Manual. +@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 +@c Free Software Foundation, Inc. +@c See the file guile.texi for copying conditions. + +@page +@node General Libguile Concepts +@section General concepts for using libguile + +When you want to embed the Guile Scheme interpreter into your program, +you need to link it against the @file{libguile} library (@pxref{Linking +Programs With Guile}). Once you have done this, your C code has access +to a number of data types and functions that can be used to invoke the +interpreter, or make new functions that you have written in C available +to be called from Scheme code, among other things. + +Scheme is different from C in a number of significant ways, and Guile +tries to make the advantages of Scheme available to C as well. Thus, in +addition to a Scheme interpreter, libguile also offers dynamic types, +garbage collection, continuations, arithmetic on arbitrary sized +numbers, and other things. + +The two fundamental concepts are dynamic types and garbage collection. +You need to understand how libguile offers them to C programs in order +to use the rest of libguile. Also, the more general control flow of +Scheme caused by continuations needs to be dealt with. + +@menu +* Dynamic Types:: Dynamic Types. +* Garbage Collection:: Garbage Collection. +* Control Flow:: Control Flow. +@end menu + +@node Dynamic Types +@subsection Dynamic Types + +Scheme is a dynamically-typed language; this means that the system +cannot, in general, determine the type of a given expression at compile +time. Types only become apparent at run time. Variables do not have +fixed types; a variable may hold a pair at one point, an integer at the +next, and a thousand-element vector later. Instead, values, not +variables, have fixed types. + +In order to implement standard Scheme functions like @code{pair?} and +@code{string?} and provide garbage collection, the representation of +every value must contain enough information to accurately determine its +type at run time. Often, Scheme systems also use this information to +determine whether a program has attempted to apply an operation to an +inappropriately typed value (such as taking the @code{car} of a string). + +Because variables, pairs, and vectors may hold values of any type, +Scheme implementations use a uniform representation for values --- a +single type large enough to hold either a complete value or a pointer +to a complete value, along with the necessary typing information. + +In Guile, this uniform representation of all Scheme values is the C type +@code{SCM}. This is an opaque type and its size is typically equivalent +to that of a pointer to @code{void}. Thus, @code{SCM} values can be +passed around efficiently and they take up reasonably little storage on +their own. + +The most important rule is: You never access a @code{SCM} value +directly; you only pass it to functions or macros defined in libguile. + +As an obvious example, although a @code{SCM} variable can contain +integers, you can of course not compute the sum of two @code{SCM} values +by adding them with the C @code{+} operator. You must use the libguile +function @code{scm_sum}. + +Less obvious and therefore more important to keep in mind is that you +also cannot directly test @code{SCM} values for trueness. In Scheme, +the value @code{#f} is considered false and of course a @code{SCM} +variable can represent that value. But there is no guarantee that the +@code{SCM} representation of @code{#f} looks false to C code as well. +You need to use @code{scm_is_true} or @code{scm_is_false} to test a +@code{SCM} value for trueness or falseness, respectively. + +You also can not directly compare two @code{SCM} values to find out +whether they are identical (that is, whether they are @code{eq?} in +Scheme terms). You need to use @code{scm_is_eq} for this. + +The one exception is that you can directly assign a @code{SCM} value to +a @code{SCM} variable by using the C @code{=} operator. + +The following (contrieved) example shows how to do it right. It +implements a function of two arguments (@var{a} and @var{flag}) that +returns @var{a}+1 if @var{flag} is true, else it returns @var{a} +unchanged. + +@example +SCM +my_incrementing_function (SCM a, SCM flag) +@{ + SCM result; + + if (scm_is_true (flag)) + result = scm_sum (a, scm_from_int (1)); + else + result = a; + + return result; +@} +@end example + +Often, you need to convert between @code{SCM} values and approriate C +values. For example, we needed to convert the integer @code{1} to its +@code{SCM} representation in order to add it to @var{a}. Libguile +provides many function to do these conversions, both from C to +@code{SCM} and from @code{SCM} to C. + +The conversion functions follow a common naming pattern: those that make +a @code{SCM} value from a C value have names of the form +@code{scm_from_@var{type} (@dots{})} and those that convert a @code{SCM} +value to a C value use the form @code{scm_to_@var{type} (@dots{})}. + +However, it is best to avoid converting values when you can. When you +must combine C values and @code{SCM} values in a computation, it is +often better to convert the C values to @code{SCM} values and do the +computation by using libguile functions than to the other way around +(converting @code{SCM} to C and doing the computation some other way). + +As a simple example, consider this version of +@code{my_incrementing_function} from above: + +@example +SCM +my_other_incrementing_function (SCM a, SCM flag) +@{ + int result; + + if (scm_is_true (flag)) + result = scm_to_int (a) + 1; + else + result = scm_to_int (a); + + return scm_from_int (result); +@} +@end example + +This version is much less general than the original one: it will only +work for values @var{A} that can fit into a @code{int}. The original +function will work for all values that Guile can represent and that +@code{scm_sum} can understand, including integers bigger than @code{long +long}, floating point numbers, complex numbers, and new numerical types +that have been added to Guile by third-party libraries. + +Also, computing with @code{SCM} is not necessarily inefficient. Small +integers will be encoded directly in the @code{SCM} value, for example, +and do not need any additional memory on the heap. See @ref{Data +Representation} to find out the details. + +Some special @code{SCM} values are available to C code without needing +to convert them from C values: + +@multitable {Scheme value} {C representation} +@item Scheme value @tab C representation +@item @nicode{#f} @tab @nicode{SCM_BOOL_F} +@item @nicode{#t} @tab @nicode{SCM_BOOL_T} +@item @nicode{()} @tab @nicode{SCM_EOL} +@end multitable + +In addition to @code{SCM}, Guile also defines the related type +@code{scm_t_bits}. This is an unsigned integral type of sufficient +size to hold all information that is directly contained in a +@code{SCM} value. The @code{scm_t_bits} type is used internally by +Guile to do all the bit twiddling explained in @ref{Data +Representation}, but you will encounter it occasionally in low-level +user code as well. + + +@node Garbage Collection +@subsection Garbage Collection + +As explained above, the @code{SCM} type can represent all Scheme values. +Some values fit entirely into a @code{SCM} value (such as small +integers), but other values require additional storage in the heap (such +as strings and vectors). This additional storage is managed +automatically by Guile. You don't need to explicitely deallocate it +when a @code{SCM} value is no longer used. + +Two things must be guaranteed so that Guile is able to manage the +storage automatically: it must know about all blocks of memory that have +ever been allocated for Scheme values, and it must know about all Scheme +values that are still being used. Given this knowledge, Guile can +periodically free all blocks that have been allocated but are not used +by any active Scheme values. This activity is called @dfn{garbage +collection}. + +It is easy for Guile to remember all blocks of memory that is has +allocated for use by Scheme values, but you need to help it with finding +all Scheme values that are in use by C code. + +You do this when writing a SMOB mark function, for example +(@pxref{Garbage Collecting Smobs}). By calling this function, the +garbage collector learns about all references that your SMOB has to +other @code{SCM} values. + +Other references to @code{SCM} objects, such as global variables of type +@code{SCM} or other random data structures in the heap that contain +fields of type @code{SCM}, can be made visible to the garbage collector +by calling the functions @code{scm_gc_protect} or +@code{scm_permanent_object}. You normally use these funtions for long +lived objects such as a hash table that is stored in a global variable. +For temporary references in local variables or function arguments, using +these functions would be too expensive. + +These references are handled differently: Local variables (and function +arguments) of type @code{SCM} are automatically visible to the garbage +collector. This works because the collector scans the stack for +potential references to @code{SCM} objects and considers all referenced +objects to be alive. The scanning considers each and every word of the +stack, regardless of what it is actually used for, and then decides +whether it could possible be a reference to a @code{SCM} object. Thus, +the scanning is guaranteed to find all actual references, but it might +also find words that only accidentally look like references. These +`false positives' might keep @code{SCM} objects alive that would +otherwise be considered dead. While this might waste memory, keeping an +object around longer than it strictly needs to is harmless. This is why +this technique is called ``conservative garbage collection''. In +practice, the wasted memory seems to be no problem. + +The stack of every thread is scanned in this way and the registers of +the CPU and all other memory locations where local variables or function +parameters might show up are included in this scan as well. + +The consequence of the conservative scanning is that you can just +declare local variables and function parameters of type @code{SCM} and +be sure that the garbage collector will not free the corresponding +objects. + +However, a local variable or function parameter is only protected as +long as it is really on the stack (or in some register). As an +optimization, the C compiler might reuse its location for some other +value and the @code{SCM} object would no longer be protected. Normally, +this leads to exactly the right behabvior: the compiler will only +overwrite a reference when it is no longer needed and thus the object +becomes unprotected precisely when the reference disappears, just as +wanted. + +There are situations, however, where a @code{SCM} object needs to be +around longer than its reference from a local variable or function +parameter. This happens, for example, when you retrieve the array of +characters from a Scheme string and work on that array directly. The +reference to the @code{SCM} string object might be dead after the +character array has been retrieved, but the array itself is still in use +and thus the string object must be protected. The compiler does not +know about this connection and might overwrite the @code{SCM} reference +too early. + +To get around this problem, you can use @code{scm_remember_upto_here_1} +and its cousins. It will keep the compiler from overwriting the +reference. For a typical example of its use, see @ref{Remembering +During Operations}. + +@node Control Flow +@subsection Control Flow + +Scheme has a more general view of program flow than C, both locally and +non-locally. + +Controlling the local flow of control involves things like gotos, loops, +calling functions and returning from them. Non-local control flow +refers to situations where the program jumps across one or more levels +of function activations without using the normal call or return +operations. + +The primitive means of C for local control flow is the @code{goto} +statement, together with @code{if}. Loops done with @code{for}, +@code{while} or @code{do} could in principle be rewritten with just +@code{goto} and @code{if}. In Scheme, the primitive means for local +control flow is the @emph{function call} (together with @code{if}). +Thus, the repetition of some computation in a loop is ultimately +implemented by a function that calls itself, that is, by recursion. + +This approach is theoretically very powerful since it is easier to +reason formally about recursion than about gotos. In C, using +recursion exclusively would not be practical, tho, since it would eat +up the stack very quickly. In Scheme, however, it is practical: +function calls that appear in a @dfn{tail position} do not use any +additional stack space. + +A function call is in a tail position when it is the last thing the +calling function does. The value returned by the called function is +immediately returned from the calling function. In the following +example, the call to @code{bar-1} is in a tail position, while the +call to @code{bar-2} is not. (The call to @code{1-} in @code{foo-2} +is in a tail position, tho.) + +@lisp +(define (foo-1 x) + (bar-1 (1- x))) + +(define (foo-2 x) + (1- (bar-2 x))) +@end lisp + +Thus, when you take care to recurse only in tail positions, the +recursion will only use constant stack space and will be as good as a +loop constructed from gotos. + +Scheme offers a few syntactic abstractions (@code{do} and @dfn{named} +@code{let}) that make writing loops slightly easier. + +But only Scheme functions can call other functions in a tail position: +C functions can not. This matters when you have, say, two functions +that call each other recursively to form a common loop. The following +(unrealistic) example shows how one might go about determing whether a +non-negative integer @var{n} is even or odd. + +@lisp +(define (my-even? n) + (cond ((zero? n) #t) + (else (my-odd? (1- n))))) + +(define (my-odd? n) + (cond ((zero? n) #f) + (else (my-even? (1- n))))) +@end lisp + +Because the calls to @code{my-even?} and @code{my-odd?} are in tail +positions, these two procedures can be applied to arbitrary large +integers without overflowing the stack. (They will still take a lot +of time, of course.) + +However, when one or both of the two procedures would be rewritten in +C, it could no longer call its companion in a tail position (since C +does not have this concept). You might need to take this +consideration into account when deciding which parts of your program +to write in Scheme and which in C. + +In addition to calling functions and returning from them, a Scheme +program can also exit non-locally from a function so that the control +flow returns directly to an outer level. This means that some functions +might not return at all. + +Even more, it is not only possible to jump to some outer level of +control, a Scheme program can also jump back into the middle of a +function that has already exited. This might cause some functions to +return more than once. + +In general, these non-local jumps are done by invoking +@dfn{continuations} that have previously been captured using +@code{call-with-current-continuation}. Guile also offers a slightly +restricted set of functions, @code{catch} and @code{throw}, that can +only be used for non-local exits. This restriction makes them more +efficient. Error reporting (with the function @code{error}) is +implemented by invoking @code{throw}, for example. The functions +@code{catch} and @code{throw} belong to the topic of @dfn{exceptions}. + +Since Scheme functions can call C functions and vice versa, C code can +experience the more general control flow of Scheme as well. It is +possible that a C function will not return at all, or will return more +than once. While C does offer @code{setjmp} and @code{longjmp} for +non-local exits, it is still an unusual thing for C code. In +contrast, non-local exits are very common in Scheme, mostly to report +errors. + +You need to be prepared for the non-local jumps in the control flow +whenever you use a function from @code{libguile}: it is best to assume +that any @code{libguile} function might signal an error or run a pending +signal handler (which in turn can do arbitrary things). + +It is often necessary to take cleanup actions when the control leaves a +function non-locally. Also, when the control returns non-locally, some +setup actions might be called for. For example, the Scheme function +@code{with-output-to-port} needs to modify the global state so that +@code{current-output-port} returns the port passed to +@code{with-output-to-port}. The global output port needs to be reset to +its previous value when @code{with-output-to-port} returns normally or +when it is exited non-locally. Likewise, the port needs to be set again +when control enters non-locally. + +Scheme code can use the @code{dynamic-wind} function to arrange for the +setting and resetting of the global state. C code could use the +corresponding @code{scm_internal_dynamic_wind} function, but it might +prefer to use the @dfn{frames} concept that is more natural for C code, +(@pxref{Frames}). + diff --git a/doc/ref/libguile-extensions.texi b/doc/ref/libguile-extensions.texi new file mode 100644 index 000000000..adcb1c5a1 --- /dev/null +++ b/doc/ref/libguile-extensions.texi @@ -0,0 +1,110 @@ +@c -*-texinfo-*- +@c This is part of the GNU Guile Reference Manual. +@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 +@c Free Software Foundation, Inc. +@c See the file guile.texi for copying conditions. + +@node Linking Guile with Libraries +@section Linking Guile with Libraries + +The previous section has briefly explained how to write programs that +make use of an embedded Guile interpreter. But sometimes, all you +want to do is make new primitive procedures and data types available +to the Scheme programmer. Writing a new version of @code{guile} is +inconvenient in this case and it would in fact make the life of the +users of your new features needlessly hard. + +For example, suppose that there is a program @code{guile-db} that is a +version of Guile with additional features for accessing a database. +People who want to write Scheme programs that use these features would +have to use @code{guile-db} instead of the usual @code{guile} program. +Now suppose that there is also a program @code{guile-gtk} that extends +Guile with access to the popular Gtk+ toolkit for graphical user +interfaces. People who want to write GUIs in Scheme would have to use +@code{guile-gtk}. Now, what happens when you want to write a Scheme +application that uses a GUI to let the user access a database? You +would have to write a @emph{third} program that incorporates both the +database stuff and the GUI stuff. This might not be easy (because +@code{guile-gtk} might be a quite obscure program, say) and taking this +example further makes it easy to see that this approach can not work in +practice. + +It would have been much better if both the database features and the GUI +feature had been provided as libraries that can just be linked with +@code{guile}. Guile makes it easy to do just this, and we encourage you +to make your extensions to Guile available as libraries whenever +possible. + +You write the new primitive procedures and data types in the normal +fashion, and link them into a shared library instead of into a +stand-alone program. The shared library can then be loaded dynamically +by Guile. + +@menu +* A Sample Guile Extension:: +@end menu + + +@node A Sample Guile Extension +@subsection A Sample Guile Extension + +This section explains how to make the Bessel functions of the C library +available to Scheme. 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. + +Consider the following file @file{bessel.c}. + +@smallexample +#include <math.h> +#include <libguile.h> + +SCM +j0_wrapper (SCM x) +@{ + return scm_make_real (j0 (scm_num2dbl (x, "j0"))); +@} + +void +init_bessel () +@{ + scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper); +@} +@end smallexample + +This C source file needs to be compiled into a shared library. Here is +how to do it on GNU/Linux: + +@smallexample +gcc -shared -o libguile-bessel.so -fPIC bessel.c +@end smallexample + +For creating shared libraries portably, we recommend the use of +@code{GNU Libtool}. + +A shared library can be loaded into a running Guile process with the +function @code{load-extension}. In addition to the name of the +library to load, this function also expects the name of function from +that library that will be called to initialize it. For our example, +we are going to call the function @code{init_bessel} which will make +@code{j0_wrapper} available to Scheme programs with the name +@code{j0}. Note that we do not specify a filename extension such as +@file{.so} when invoking @code{load-extension}. The right extension for +the host platform will be provided automatically. + +@smalllisp +(load-extension "libguile-bessel" "init_bessel") +(j0 2) +@result{} 0.223890779141236 +@end smalllisp + +For this to work, @code{load-extension} must be able to find +@file{libguile-bessel}, of course. It will look in the places that +are usual for your operating system, and it will additionally look +into the directories listed in the @code{LTDL_LIBRARY_PATH} +environment variable. + +To see how these Guile extensions via shared libraries relate to the +module system, @xref{Putting Extensions into Modules}. diff --git a/doc/ref/libguile-linking.texi b/doc/ref/libguile-linking.texi new file mode 100644 index 000000000..6fb667caa --- /dev/null +++ b/doc/ref/libguile-linking.texi @@ -0,0 +1,185 @@ +@c -*-texinfo-*- +@c This is part of the GNU Guile Reference Manual. +@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 +@c Free Software Foundation, Inc. +@c See the file guile.texi for copying conditions. + +@node Linking Programs With Guile +@section Linking Programs With Guile + +This section covers the mechanics of linking your program with Guile +on a typical POSIX system. + +The header file @code{<libguile.h>} provides declarations for all of +Guile's functions and constants. You should @code{#include} it at the +head of any C source file that uses identifiers described in this +manual. Once you've compiled your source files, you need to link them +against the Guile object code library, @code{libguile}. + +On most systems, you should not need to tell the compiler and linker +explicitly where they can find @file{libguile.h} and @file{libguile}. +When Guile has been installed in a peculiar way, or when you are on a +peculiar system, things might not be so easy and you might need to pass +additional @code{-I} or @code{-L} options to the compiler. Guile +provides the utility program @code{guile-config} to help you find the +right values for these options. You would typically run +@code{guile-config} during the configuration phase of your program and +use the obtained information in the Makefile. + +@menu +* Guile Initialization Functions:: What to call first. +* A Sample Guile Main Program:: Sources and makefiles. +@end menu + + +@node Guile Initialization Functions +@subsection Guile Initialization Functions + +To initialize Guile, you can use one of two functions. The first, +@code{scm_boot_guile}, is the most portable way to initialize Guile. It +should be used whenever you have control over the main function of your +program because it never returns. The second function, +@code{scm_init_guile}, does return and can thus be used in more +situations. However, @code{scm_init_guile} is not as widely available +as @code{scm_boot_guile} because it needs to rely on non-portable code +to find the stack bounds. When Guile does not know how to find these +bounds on your system, it will not provide @code{scm_init_guile}. + +When you can tolerate the limits of @code{scm_boot_guile}, you should +use it in favor of @code{scm_init_guile} since that will make your +program more portable. + +One common way to use Guile is to write a set of C functions which +perform some useful task, make them callable from Scheme, and then link +the program with Guile. This yields a Scheme interpreter just like +@code{guile}, but augmented with extra functions for some specific +application --- a special-purpose scripting language. + +In this situation, the application should probably process its +command-line arguments in the same manner as the stock Guile +interpreter. To make that straightforward, Guile provides the +@code{scm_shell} function. + +@node A Sample Guile Main Program +@subsection A Sample Guile Main Program + +Here is @file{simple-guile.c}, source code for a @code{main} and an +@code{inner_main} function that will produce a complete Guile +interpreter. + +@example +/* simple-guile.c --- how to start up the Guile + interpreter from C code. */ + +/* Get declarations for all the scm_ functions. */ +#include <libguile.h> + +static void +inner_main (void *closure, int argc, char **argv) +@{ + /* module initializations would go here */ + scm_shell (argc, argv); +@} + +int +main (int argc, char **argv) +@{ + scm_boot_guile (argc, argv, inner_main, 0); + return 0; /* never reached */ +@} +@end example + +The @code{main} function calls @code{scm_boot_guile} to initialize +Guile, passing it @code{inner_main}. Once @code{scm_boot_guile} is +ready, it invokes @code{inner_main}, which calls @code{scm_shell} to +process the command-line arguments in the usual way. + +Here is a Makefile which you can use to compile the above program. It +uses @code{guile-config} to learn about the necessary compiler and +linker flags. +@example +# Use GCC, if you have it installed. +CC=gcc + +# Tell the C compiler where to find <libguile.h> +CFLAGS=`guile-config compile` + +# Tell the linker what libraries to use and where to find them. +LIBS=`guile-config link` + +simple-guile: simple-guile.o + $@{CC@} simple-guile.o $@{LIBS@} -o simple-guile + +simple-guile.o: simple-guile.c + $@{CC@} -c $@{CFLAGS@} simple-guile.c +@end example + +If you are using the GNU Autoconf package to make your application more +portable, Autoconf will settle many of the details in the Makefile above +automatically, making it much simpler and more portable; we recommend +using Autoconf with Guile. Guile also provides the @code{GUILE_FLAGS} +macro for autoconf that performs all necessary checks. Here is a +@file{configure.in} file for @code{simple-guile} that uses this macro. +Autoconf can use as this file as template to generate a @code{configure} +script. In order for Autoconf to find the @code{GUILE_FLAGS} macro, you +will need to run @code{aclocal} first. This is not really Guile +specific, so you should refer to the Autoconf documentation REFFIXME +when in doubt. +@example +AC_INIT(simple-guile.c) + +# Find a C compiler. +AC_PROG_CC + +# Check for Guile +GUILE_FLAGS + +# Generate a Makefile, based on the results. +AC_OUTPUT(Makefile) +@end example + +Here is a @code{Makefile.in} template, from which the @code{configure} +script produces a Makefile customized for the host system: +@example +# The configure script fills in these values. +CC=@@CC@@ +CFLAGS=@@GUILE_CFLAGS@@ +LIBS=@@GUILE_LDFLAGS@@ + +simple-guile: simple-guile.o + $@{CC@} simple-guile.o $@{LIBS@} -o simple-guile +simple-guile.o: simple-guile.c + $@{CC@} -c $@{CFLAGS@} simple-guile.c +@end example + +The developer should use Autoconf to generate the @file{configure} +script from the @file{configure.in} template, and distribute +@file{configure} with the application. Here's how a user might go about +building the application: + +@example +$ ls +Makefile.in configure* configure.in simple-guile.c +$ ./configure +creating cache ./config.cache +checking for gcc... (cached) gcc +checking whether the C compiler (gcc ) works... yes +checking whether the C compiler (gcc ) is a cross-compiler... no +checking whether we are using GNU C... (cached) yes +checking whether gcc accepts -g... (cached) yes +checking for Guile... yes +creating ./config.status +creating Makefile +$ make +gcc -c -I/usr/local/include simple-guile.c +gcc simple-guile.o -L/usr/local/lib -lguile -lqthreads -lpthread -lm -o simple-guile +$ ./simple-guile +guile> (+ 1 2 3) +6 +guile> (getpwnam "jimb") +#("jimb" "83Z7d75W2tyJQ" 4008 10 "Jim Blandy" "/u/jimb" + "/usr/local/bin/bash") +guile> (exit) +$ +@end example + diff --git a/doc/ref/libguile-smobs.texi b/doc/ref/libguile-smobs.texi new file mode 100644 index 000000000..b424017d0 --- /dev/null +++ b/doc/ref/libguile-smobs.texi @@ -0,0 +1,675 @@ +@c -*-texinfo-*- +@c This is part of the GNU Guile Reference Manual. +@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 +@c Free Software Foundation, Inc. +@c See the file guile.texi for copying conditions. + +@node Defining New Types (Smobs) +@section Defining New Types (Smobs) + +@dfn{Smobs} are Guile's mechanism for adding new primitive types to +the system. The term ``smob'' was coined by Aubrey Jaffer, who says +it comes from ``small object'', referring to the fact that they are +quite limited in size: they can hold just one pointer to a larger +memory block plus 16 extra bits. + +To define a new smob type, the programmer provides Guile with some +essential information about the type --- how to print it, how to +garbage collect it, and so on --- and Guile allocates a fresh type tag +for it. The programmer can then use @code{scm_c_define_gsubr} to make +a set of C functions visible to Scheme code that create and operate on +these objects. + +(You can find a complete version of the example code used in this +section in the Guile distribution, in @file{doc/example-smob}. That +directory includes a makefile and a suitable @code{main} function, so +you can build a complete interactive Guile shell, extended with the +datatypes described here.) + +@menu +* Describing a New Type:: +* Creating Instances:: +* Type checking:: +* Garbage Collecting Smobs:: +* Garbage Collecting Simple Smobs:: +* Remembering During Operations:: +* Double Smobs:: +* The Complete Example:: +@end menu + +@node Describing a New Type +@subsection Describing a New Type + +To define a new type, the programmer must write four functions to +manage instances of the type: + +@table @code +@item mark +Guile will apply this function to each instance of the new type it +encounters during garbage collection. This function is responsible for +telling the collector about any other @code{SCM} values that the object +has stored. The default smob mark function does nothing. +@xref{Garbage Collecting Smobs}, for more details. + +@item free +Guile will apply this function to each instance of the new type that is +to be deallocated. The function should release all resources held by +the object. This is analogous to the Java finalization method-- it is +invoked at an unspecified time (when garbage collection occurs) after +the object is dead. The default free function frees the smob data (if +the size of the struct passed to @code{scm_make_smob_type} is non-zero) +using @code{scm_gc_free}. @xref{Garbage Collecting Smobs}, for more +details. + +@item print +Guile will apply this function to each instance of the new type to print +the value, as for @code{display} or @code{write}. The default print +function prints @code{#<NAME ADDRESS>} where @code{NAME} is the first +argument passed to @code{scm_make_smob_type}. For more information on +printing, see @ref{Port Data}. + +@item equalp +If Scheme code asks the @code{equal?} function to compare two instances +of the same smob type, Guile calls this function. It should return +@code{SCM_BOOL_T} if @var{a} and @var{b} should be considered +@code{equal?}, or @code{SCM_BOOL_F} otherwise. If @code{equalp} is +@code{NULL}, @code{equal?} will assume that two instances of this type are +never @code{equal?} unless they are @code{eq?}. + +@end table + +To actually register the new smob type, call @code{scm_make_smob_type}. +It returns a value of type @code{scm_t_bits} which identifies the new +smob type. + +The four special functions descrtibed above are registered by calling +one of @code{scm_set_smob_mark}, @code{scm_set_smob_free}, +@code{scm_set_smob_print}, or @code{scm_set_smob_equalp}, as +appropriate. Each function is intended to be used at most once per +type, and the call should be placed immediately following the call to +@code{scm_make_smob_type}. + +There can only be at most 256 different smob types in the system. +Instead of registering a huge number of smob types (for example, one +for each relevant C struct in your application), it is sometimes +better to register just one and implement a second alyer of type +dispatching on top of it. This second layer might use the 16 extra +bits for as an extended type, for example. + +Here is how one might declare and register a new type representing +eight-bit gray-scale images: + +@example +#include <libguile.h> + +struct image @{ + int width, height; + char *pixels; + + /* The name of this image */ + SCM name; + + /* A function to call when this image is + modified, e.g., to update the screen, + or SCM_BOOL_F if no action necessary */ + SCM update_func; +@}; + +static scm_t_bits image_tag; + +void +init_image_type (void) +@{ + image_tag = scm_make_smob_type ("image", sizeof (struct image)); + scm_set_smob_mark (image_tag, mark_image); + scm_set_smob_free (image_tag, free_image); + scm_set_smob_print (image_tag, print_image); +@} +@end example + + +@node Creating Instances +@subsection Creating Instances + +Normally, smobs can have one @emph{immediate} words of data. This word +stores either a pointer to an additional memory block that holds the +real data, or it might hold the data itself when it fits. The word is +of type @code{scm_t_bits} and is large enough for a @code{SCM} value or +a pointer to @code{void}. + +You can also create smobs that have two or three immediate words, and +when these words suffice to store all data, it is more efficient to use +these super-sized smobs instead of using a normal smob plus a memory +block. @xref{Double Smobs}, for their discussion. + +To retrieve the immediate word of a smob, you use the macro +@code{SCM_SMOB_DATA}. It can be set with @code{SCM_SET_SMOB_DATA}. +The 16 extra bits can be accessed with @code{SCM_SMOB_FLAGS} and +@code{SCM_SET_SMOB_FLAGS}. + +Guile provides functions for managing memory which are often helpful +when implementing smobs. @xref{Memory Blocks}. + +Creating a smob instance can be tricky when it consists of multiple +steps that allocate resources and might fail. It is recommended that +you go about creating a smob in the following way: + +@itemize +@item +Allocate the memory block for holding the data with +@code{scm_gc_malloc}. +@item +Initialize it to a valid state without calling any functions that might +cause a non-local exits. For example, initialize pointers to NULL. +Also, do not store @code{SCM} values in it that must be protected. +Initialize these fields with @code{SCM_BOOL_F}. + +A valid state is one that can be safely acted upon by the @emph{mark} +and @emph{free} functions of your smob type. +@item +Create the smob using @code{SCM_NEWSMOB}, passing it the initialized +memory block. (This step will always succeed.) +@item +Complete the initialization of the memory block by, for example, +allocating additional resources and making it point to them. +@end itemize + +This precedure ensures that the smob is in a valid state as soon as it +exists, that all resources that are allocated for the smob are properly +associated with it so that they can be properly freed, and that no +@code{SCM} values that need to be protected are stored in it while the +smob does not yet competely exist and thus can not protect them. + +Continuing the example from above, if the global variable +@code{image_tag} contains a tag returned by @code{scm_make_smob_type}, +here is how we could construct a smob whose immediate word contains a +pointer to a freshly allocated @code{struct image}: + +@example +SCM +make_image (SCM name, SCM s_width, SCM s_height) +@{ + SCM smob; + struct image *image; + int width = scm_to_int (s_width); + int height = scm_to_int (s_height); + + /* Step 1: Allocate the memory block. + */ + image = (struct image *) scm_gc_malloc (sizeof (struct image), "image"); + + /* Step 2: Initialize it with straight code. + */ + image->width = width; + image->height = height; + image->pixels = NULL; + image->name = SCM_BOOL_F; + image->update_func = SCM_BOOL_F; + + /* Step 3: Create the smob. + */ + SCM_NEWSMOB (smob, image); + + /* Step 4: Finish the initialization. + */ + image->name = name; + image->pixels = scm_gc_malloc (width * height, "image pixels"); + + return smob; +@} +@end example + +Let us look at what might happen when @code{make_image} is called. + +The conversions of @var{s_width} and @var{s_height} to @code{int}s might +fail and signal an error, thus causing a non-local exit. This is not a +problem since no resources have been allocated yet that would have to be +freed. + +The allocation of @var{image} in step 1 might fail, but this is likewise +no problem. + +Step 2 can not exit non-locally. At the end of it, the @var{image} +struct is in a valid state for the @code{mark_image} and +@code{free_image} functions (see below). + +Step 3 can not exit non-locally either. This is guaranteed by Guile. +After it, @var{smob} contains a valid smob that is properly initialized +and protected, and in turn can properly protect the Scheme values in its +@var{image} struct. + +But before the smob is completely created, @code{SCM_NEWSMOB} might +cause the garbage collector to run. During this garbage collection, the +@code{SCM} values in the @var{image} struct would be invisible to Guile. +It only gets to know about them via the @code{mark_image} function, but +that function can not yet do its job since the smob has not been created +yet. Thus, it is important to not store @code{SCM} values in the +@var{image} struct until after the smob has been created. + +Step 4, finally, might fail and cause a non-local exit. In that case, +the creation of the smob has not been successful. It will eventually be +freed by the garbage collector, and all the resources that have been +allocated for it will be correctly freed by @code{free_image}. + +@node Type checking +@subsection Type checking + +Functions that operate on smobs should check that the passed @code{SCM} +value indeed is a suitable smob before accessing its data. + +For example, here is a simple function that operates on an image smob, +and checks the type of its argument. + +@example +SCM +clear_image (SCM image_smob) +@{ + int area; + struct image *image; + + SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob), + image_smob, SCM_ARG1, "clear-image"); + + image = (struct image *) SCM_SMOB_DATA (image_smob); + area = image->width * image->height; + memset (image->pixels, 0, area); + + /* Invoke the image's update function. + */ + if (scm_is_true (image->update_func)) + scm_call_0 (image->update_func); + + scm_remember_upto_here_1 (image_smob); + + return SCM_UNSPECIFIED; +@} +@end example + +See @ref{Remembering During Operations} for an explanation of the call +to @code{scm_remember_upto_here_1}. + + +@node Garbage Collecting Smobs +@subsection Garbage Collecting Smobs + +Once a smob has been released to the tender mercies of the Scheme +system, it must be prepared to survive garbage collection. Guile calls +the @emph{mark} and @emph{free} functions of the smob to manage this. + +As described in more detail elsewhere (@pxref{Conservative GC}), every +object in the Scheme system has a @dfn{mark bit}, which the garbage +collector uses to tell live objects from dead ones. When collection +starts, every object's mark bit is clear. The collector traces pointers +through the heap, starting from objects known to be live, and sets the +mark bit on each object it encounters. When it can find no more +unmarked objects, the collector walks all objects, live and dead, frees +those whose mark bits are still clear, and clears the mark bit on the +others. + +The two main portions of the collection are called the @dfn{mark phase}, +during which the collector marks live objects, and the @dfn{sweep +phase}, during which the collector frees all unmarked objects. + +The mark bit of a smob lives in a special memory region. When the +collector encounters a smob, it sets the smob's mark bit, and uses the +smob's type tag to find the appropriate @emph{mark} function for that +smob. It then calls this @emph{mark} function, passing it the smob as +its only argument. + +The @emph{mark} function is responsible for marking any other Scheme +objects the smob refers to. If it does not do so, the objects' mark +bits will still be clear when the collector begins to sweep, and the +collector will free them. If this occurs, it will probably break, or at +least confuse, any code operating on the smob; the smob's @code{SCM} +values will have become dangling references. + +To mark an arbitrary Scheme object, the @emph{mark} function calls +@code{scm_gc_mark}. + +Thus, here is how we might write @code{mark_image}: + +@example +@group +SCM +mark_image (SCM image_smob) +@{ + /* Mark the image's name and update function. */ + struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); + + scm_gc_mark (image->name); + scm_gc_mark (image->update_func); + + return SCM_BOOL_F; +@} +@end group +@end example + +Note that, even though the image's @code{update_func} could be an +arbitrarily complex structure (representing a procedure and any values +enclosed in its environment), @code{scm_gc_mark} will recurse as +necessary to mark all its components. Because @code{scm_gc_mark} sets +an object's mark bit before it recurses, it is not confused by +circular structures. + +As an optimization, the collector will mark whatever value is returned +by the @emph{mark} function; this helps limit depth of recursion during +the mark phase. Thus, the code above should really be written as: +@example +@group +SCM +mark_image (SCM image_smob) +@{ + /* Mark the image's name and update function. */ + struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); + + scm_gc_mark (image->name); + return image->update_func; +@} +@end group +@end example + + +Finally, when the collector encounters an unmarked smob during the sweep +phase, it uses the smob's tag to find the appropriate @emph{free} +function for the smob. It then calls that function, passing it the smob +as its only argument. + +The @emph{free} function must release any resources used by the smob. +However, it must not free objects managed by the collector; the +collector will take care of them. For historical reasons, the return +type of the @emph{free} function should be @code{size_t}, an unsigned +integral type; the @emph{free} function should always return zero. + +Here is how we might write the @code{free_image} function for the image +smob type: +@example +size_t +free_image (SCM image_smob) +@{ + struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); + + scm_gc_free (image->pixels, image->width * image->height, "image pixels"); + scm_gc_free (image, sizeof (struct image), "image"); + + return 0; +@} +@end example + +During the sweep phase, the garbage collector will clear the mark bits +on all live objects. The code which implements a smob need not do this +itself. + +There is no way for smob code to be notified when collection is +complete. + +It is usually a good idea to minimize the amount of processing done +during garbage collection; keep the @emph{mark} and @emph{free} +functions very simple. Since collections occur at unpredictable times, +it is easy for any unusual activity to interfere with normal code. + + +@node Garbage Collecting Simple Smobs +@subsection Garbage Collecting Simple Smobs + +It is often useful to define very simple smob types --- smobs which have +no data to mark, other than the cell itself, or smobs whose immediate +data word is simply an ordinary Scheme object, to be marked recursively. +Guile provides some functions to handle these common cases; you can use +this function as your smob type's @emph{mark} function, if your smob's +structure is simple enough. + +If the smob refers to no other Scheme objects, then no action is +necessary; the garbage collector has already marked the smob cell +itself. In that case, you can use zero as your mark function. + +@deftypefun SCM scm_markcdr (SCM @var{x}) +Mark the references in the smob @var{x}, assuming that @var{x}'s first +data word contains an ordinary Scheme object, and @var{x} refers to no +other objects. This function simply returns @var{x}'s first data word. + +This is only useful for simple smobs created by @code{SCM_NEWSMOB} or +@code{SCM_RETURN_NEWSMOB}, not for smobs allocated as double cells. +@end deftypefun + +@node Remembering During Operations +@subsection Remembering During Operations +@cindex Remembering + +It's important that a smob is visible to the garbage collector +whenever its contents are being accessed. Otherwise it could be freed +while code is still using it. + +For example, consider a procedure to convert image data to a list of +pixel values. + +@example +SCM +image_to_list (SCM image_smob) +@{ + struct image *image; + SCM lst; + int i; + SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob), + image_smob, SCM_ARG1, "image->list"); + + image = (struct image *) SCM_SMOB_DATA (image_smob); + lst = SCM_EOL; + for (i = image->width * image->height - 1; i >= 0; i--) + lst = scm_cons (scm_from_char (image->pixels[i]), lst); + + scm_remember_upto_here_1 (image_smob); + return lst; +@} +@end example + +In the loop, only the @code{image} pointer is used and the C compiler +has no reason to keep the @code{image_smob} value anywhere. If +@code{scm_cons} results in a garbage collection, @code{image_smob} might +not be on the stack or anywhere else and could be freed, leaving the +loop accessing freed data. The use of @code{scm_remember_upto_here_1} +prevents this, by creating a reference to @code{image_smob} after all +data accesses. + +There's no need to do the same for @code{lst}, since that's the return +value and the compiler will certainly keep it in a register or +somewhere throughout the routine. + +The @code{clear_image} example previously shown (@pxref{Type checking}) +also used @code{scm_remember_upto_here_1} for this reason. + +It's only in quite rare circumstances that a missing +@code{scm_remember_upto_here_1} will bite, but when it happens the +consequences are serious. Fortunately the rule is simple: whenever +calling a Guile library function or doing something that might, ensure +the @code{SCM} of a smob is referenced past all accesses to its +insides. Do this by adding an @code{scm_remember_upto_here_1} if +there are no other references. + +In a multi-threaded program, the rule is the same. As far as a given +thread is concerned, a garbage collection still only occurs within a +Guile library function, not at an arbitrary time. (Guile waits for all +threads to reach one of its library functions, and holds them there +while the collector runs.) + +@node Double Smobs +@subsection Double Smobs + +Smobs are called smob because they are small: they normally have only +room for one @code{scm_t_bits} value plus 16 bits. The reason for +this is that smobs are directly implemented by using the low-level, +two-word cells of Guile that are also used to implement pairs, for +example. (@pxref{Data Representation} for the details.) One word of +the two-word cells is used for @code{SCM_SMOB_DATA}, the other +contains the 16-bit type tag and the 16 extra bits. + +In addition to the fundamental two-word cells, Guile also has +four-word cells, which are appropriately called @dfn{double cells}. +You can use them for @dfn{double smobs} and get two more immediate +words of type @code{scm_t_bits}. + +A double smob is created with @code{SCM_NEWSMOB2} or +@code{SCM_NEWSMOB3} instead of @code{SCM_NEWSMOB}. Its immediate +words can be retrieved with @code{SCM_SMOB_DATA2} and +@code{SCM_SMOB_DATA3} in addition to @code{SCM_SMOB_DATA}. +Unsurprisingly, the words can be set with @code{SCM_SET_SMOB_DATA2} +and @code{SCM_SET_SMOB_DATA3}. + +@node The Complete Example +@subsection The Complete Example + +Here is the complete text of the implementation of the image datatype, +as presented in the sections above. We also provide a definition for +the smob's @emph{print} function, and make some objects and functions +static, to clarify exactly what the surrounding code is using. + +As mentioned above, you can find this code in the Guile distribution, in +@file{doc/example-smob}. That directory includes a makefile and a +suitable @code{main} function, so you can build a complete interactive +Guile shell, extended with the datatypes described here.) + +@example +/* file "image-type.c" */ + +#include <stdlib.h> +#include <libguile.h> + +static scm_t_bits image_tag; + +struct image @{ + int width, height; + char *pixels; + + /* The name of this image */ + SCM name; + + /* A function to call when this image is + modified, e.g., to update the screen, + or SCM_BOOL_F if no action necessary */ + SCM update_func; +@}; + +static SCM +make_image (SCM name, SCM s_width, SCM s_height) +@{ + SCM smob; + struct image *image; + int width = scm_to_int (s_width); + int height = scm_to_int (s_height); + + /* Step 1: Allocate the memory block. + */ + image = (struct image *) scm_gc_malloc (sizeof (struct image), "image"); + + /* Step 2: Initialize it with straight code. + */ + image->width = width; + image->height = height; + image->pixels = NULL; + image->name = SCM_BOOL_F; + image->update_func = SCM_BOOL_F; + + /* Step 3: Create the smob. + */ + SCM_NEWSMOB (smob, image); + + /* Step 4: Finish the initialization. + */ + image->name = name; + image->pixels = scm_gc_malloc (width * height, "image pixels"); + + return smob; +@} + +SCM +clear_image (SCM image_smob) +@{ + int area; + struct image *image; + + SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob), + image_smob, SCM_ARG1, "clear-image"); + + image = (struct image *) SCM_SMOB_DATA (image_smob); + area = image->width * image->height; + memset (image->pixels, 0, area); + + /* Invoke the image's update function. + */ + if (scm_is_true (image->update_func)) + scm_call_0 (image->update_func); + + scm_remember_upto_here_1 (image_smob); + + return SCM_UNSPECIFIED; +@} + +static SCM +mark_image (SCM image_smob) +@{ + /* Mark the image's name and update function. */ + struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); + + scm_gc_mark (image->name); + return image->update_func; +@} + +static size_t +free_image (SCM image_smob) +@{ + struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); + + scm_gc_free (image->pixels, image->width * image->height, "image pixels"); + scm_gc_free (image, sizeof (struct image), "image"); + + return 0; +@} + +static int +print_image (SCM image_smob, SCM port, scm_print_state *pstate) +@{ + struct image *image = (struct image *) SCM_SMOB_DATA (image_smob); + + scm_puts ("#<image ", port); + scm_display (image->name, port); + scm_puts (">", port); + + /* non-zero means success */ + return 1; +@} + +void +init_image_type (void) +@{ + image_tag = scm_make_smob_type ("image", sizeof (struct image)); + scm_set_smob_mark (image_tag, mark_image); + scm_set_smob_free (image_tag, free_image); + scm_set_smob_print (image_tag, print_image); + + scm_c_define_gsubr ("clear-image", 1, 0, 0, clear_image); + scm_c_define_gsubr ("make-image", 3, 0, 0, make_image); +@} +@end example + +Here is a sample build and interaction with the code from the +@file{example-smob} directory, on the author's machine: + +@example +zwingli:example-smob$ make CC=gcc +gcc `guile-config compile` -c image-type.c -o image-type.o +gcc `guile-config compile` -c myguile.c -o myguile.o +gcc image-type.o myguile.o `guile-config link` -o myguile +zwingli:example-smob$ ./myguile +guile> make-image +#<primitive-procedure make-image> +guile> (define i (make-image "Whistler's Mother" 100 100)) +guile> i +#<image Whistler's Mother> +guile> (clear-image i) +guile> (clear-image 4) +ERROR: In procedure clear-image in expression (clear-image 4): +ERROR: Wrong type argument in position 1: 4 +ABORT: (wrong-type-arg) + +Type "(backtrace)" to get more information. +guile> +@end example diff --git a/doc/ref/libguile-snarf.texi b/doc/ref/libguile-snarf.texi new file mode 100644 index 000000000..38fdb6c66 --- /dev/null +++ b/doc/ref/libguile-snarf.texi @@ -0,0 +1,131 @@ +@c -*-texinfo-*- +@c This is part of the GNU Guile Reference Manual. +@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 +@c Free Software Foundation, Inc. +@c See the file guile.texi for copying conditions. + +@node Function Snarfing +@section Function Snarfing + +When writing C code for use with Guile, you typically define a set of +C functions, and then make some of them visible to the Scheme world by +calling @code{scm_c_define_gsubr} or related functions. If you have +many functions to publish, it can sometimes be annoying to keep the +list of calls to @code{scm_c_define_gsubr} in sync with the list of +function definitions. + +Guile provides the @code{guile-snarf} program to manage this problem. +Using this tool, you can keep all the information needed to define the +function alongside the function definition itself; @code{guile-snarf} +will extract this information from your source code, and automatically +generate a file of calls to @code{scm_c_define_gsubr} which you can +@code{#include} into an initialization function. + +The snarfing mechanism works for many kind of initialiation actions, +not just for collecting calls to @code{scm_c_define_gsubr}. For a +full list of what can be done, @xref{Snarfing Macros}. + +@cindex guile-snarf invocation +@cindex guile-snarf example + +The @code{guile-snarf} program is invoked like this: + +@smallexample +guile-snarf [-o @var{outfile}] [@var{cpp-args} ...] +@end smallexample + +This command will extract initialization actions to @var{outfile}. +When no @var{outfile} has been specified or when @var{outfile} is +@code{-}, standard output will be used. The C preprocessor is called +with @var{cpp-args} (which usually include an input file) and the +output is filtered to extract the initialization actions. + +If there are errors during processing, @var{outfile} is deleted and the +program exits with non-zero status. + +During snarfing, the pre-processor macro @code{SCM_MAGIC_SNARFER} is +defined. You could use this to avoid including snarfer output files +that don't yet exist by writing code like this: + +@smallexample +#ifndef SCM_MAGIC_SNARFER +#include "foo.x" +#endif +@end smallexample + +Here is how you might define the Scheme function @code{clear-image}, +implemented by the C function @code{clear_image}: + +@example +@group +#include <libguile.h> + +SCM_DEFINE (clear_image, "clear-image", 1, 0, 0, + (SCM image_smob), + "Clear the image.") +@{ + /* C code to clear the image in @code{image_smob}... */ +@} + +void +init_image_type () +@{ +#include "image-type.x" +@} +@end group +@end example + +The @code{SCM_DEFINE} declaration says that the C function +@code{clear_image} implements a Scheme function called +@code{clear-image}, which takes one required argument (of type +@code{SCM} and named @code{image_smob}), no optional arguments, and no +rest argument. The string @code{"Clear the image."} provides a short +help text for the function, it is called a @dfn{docstring}. + +For historical reasons, the @code{SCM_DEFINE} macro also defines a +static array of characters named @code{s_clear_image}, initialized to +the string "clear-image". You shouldn't use this array, but you might +need to be aware that it exists. + +Assuming the text above lives in a file named @file{image-type.c}, you +will need to execute the following command to prepare this file for +compilation: + +@example +guile-snarf -o image-type.x image-type.c +@end example + +This scans @file{image-type.c} for @code{SCM_DEFINE} +declarations, and writes to @file{image-type.x} the output: + +@example +scm_c_define_gsubr ("clear-image", 1, 0, 0, (SCM (*)() ) clear_image); +@end example + +When compiled normally, @code{SCM_DEFINE} is a macro which expands to +the function header for @code{clear_image}. + +Note that the output file name matches the @code{#include} from the +input file. Also, you still need to provide all the same information +you would if you were using @code{scm_c_define_gsubr} yourself, but you +can place the information near the function definition itself, so it is +less likely to become incorrect or out-of-date. + +If you have many files that @code{guile-snarf} must process, you should +consider using a fragment like the following in your Makefile: + +@example +snarfcppopts = $(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS) +.SUFFIXES: .x +.c.x: + guile-snarf -o $@@ $< $(snarfcppopts) +@end example + +This tells make to run @code{guile-snarf} to produce each needed +@file{.x} file from the corresponding @file{.c} file. + +The program @code{guile-snarf} passes its command-line arguments +directly to the C preprocessor, which it uses to extract the +information it needs from the source code. this means you can pass +normal compilation flags to @code{guile-snarf} to define preprocessor +symbols, add header file directories, and so on. diff --git a/doc/ref/misc-modules.texi b/doc/ref/misc-modules.texi index 10117b86a..0d8bfdcaf 100644 --- a/doc/ref/misc-modules.texi +++ b/doc/ref/misc-modules.texi @@ -6,7 +6,7 @@ @page @node Pretty Printing -@chapter Pretty Printing +@section Pretty Printing @c FIXME::martin: Review me! @@ -81,7 +81,7 @@ used by @code{write}, but not by @code{pretty-print}. @page @node Formatted Output -@chapter Formatted Output +@section Formatted Output @c FIXME::martin: Review me! @@ -312,7 +312,7 @@ of the interpreter is not unnecessarily increased. @page @node Rx Regexps -@chapter The Rx Regular Expression Library +@section The Rx Regular Expression Library [FIXME: this is taken from Gary and Mark's quick summaries and should be reviewed and expanded. Rx is pretty stable, so could already be done!] @@ -445,7 +445,7 @@ Test whether obj is a compiled regular expression. @node File Tree Walk -@chapter File Tree Walk +@section File Tree Walk @cindex file tree walk The functions in this section traverse a tree of files and @@ -622,7 +622,7 @@ use @code{throw} or similar to escape. @node Queues -@chapter Queues +@section Queues @cindex Queues @tindex Queues diff --git a/doc/ref/mod-getopt-long.texi b/doc/ref/mod-getopt-long.texi new file mode 100644 index 000000000..cba660b83 --- /dev/null +++ b/doc/ref/mod-getopt-long.texi @@ -0,0 +1,341 @@ +@c -*-texinfo-*- +@c This is part of the GNU Guile Reference Manual. +@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 +@c Free Software Foundation, Inc. +@c See the file guile.texi for copying conditions. + +@node getopt-long +@section The (ice-9 getopt-long) Module + +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 section 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 section, 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 section 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 {Scheme 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 {Scheme 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. diff --git a/doc/ref/posix.texi b/doc/ref/posix.texi index 6ee040826..0bb4e6b58 100644 --- a/doc/ref/posix.texi +++ b/doc/ref/posix.texi @@ -5,7 +5,7 @@ @c See the file guile.texi for copying conditions. @node POSIX -@chapter @acronym{POSIX} System Calls and Networking +@section @acronym{POSIX} System Calls and Networking @menu * Conventions:: Conventions employed by the POSIX interface. @@ -26,7 +26,7 @@ @end menu @node Conventions -@section @acronym{POSIX} Interface Conventions +@subsection @acronym{POSIX} Interface Conventions These interfaces provide access to operating system facilities. They provide a simple wrapping around the underlying C interfaces @@ -99,7 +99,7 @@ It can be extracted with the function @code{system-error-errno}: @end example @node Ports and File Descriptors -@section Ports and File Descriptors +@subsection Ports and File Descriptors Conventions generally follow those of scsh, @ref{The Scheme shell (scsh)}. @@ -534,7 +534,7 @@ An additional @code{select!} interface is provided. @end deffn @node File System -@section File System +@subsection File System These procedures allow querying and setting file system attributes (such as owner, @@ -873,7 +873,7 @@ If @var{suffix} is provided, and is equal to the end of @node User Information -@section User Information +@subsection User Information The facilities in this section provide an interface to the user and group database. @@ -1016,7 +1016,7 @@ information cannot be obtained. @node Time -@section Time +@subsection Time @deffn {Scheme Procedure} current-time @deffnx {C Function} scm_current_time () @@ -1198,7 +1198,7 @@ included but subprocesses are not. @end deffn @node Runtime Environment -@section Runtime Environment +@subsection Runtime Environment @deffn {Scheme Procedure} program-arguments @deffnx {Scheme Procedure} command-line @@ -1261,7 +1261,7 @@ The return value is unspecified. @node Processes -@section Processes +@subsection Processes @findex cd @deffn {Scheme Procedure} chdir str @@ -1595,7 +1595,7 @@ specified processes. @node Signals -@section Signals +@subsection Signals Procedures to raise, handle and wait for signals. @@ -1746,7 +1746,7 @@ the seconds and microseconds of the timer @code{it_value}. @node Terminals and Ptys -@section Terminals and Ptys +@subsection Terminals and Ptys @deffn {Scheme Procedure} isatty? port @deffnx {C Function} scm_isatty_p (port) @@ -1790,7 +1790,7 @@ controlling terminal. The return value is unspecified. @end deffn @node Pipes -@section Pipes +@subsection Pipes The following procedures provide an interface to the @code{popen} and @code{pclose} system routines. The code is in a separate ``popen'' @@ -1835,7 +1835,7 @@ close a pipe, but doesn't return the status. @end deffn @node Networking -@section Networking +@subsection Networking @menu * Network Address Conversion:: @@ -1845,12 +1845,12 @@ close a pipe, but doesn't return the status. @end menu @node Network Address Conversion -@subsection Network Address Conversion +@subsubsection Network Address Conversion This section describes procedures which convert internet addresses between numeric and string formats. -@subsubsection IPv4 Address Conversion +@subsubheading IPv4 Address Conversion An IPv4 Internet address is a 4-byte value, represented in Guile as an integer in network byte order (meaning the first byte is the most @@ -1927,7 +1927,7 @@ Make an IPv4 Internet address by combining the network number @end lisp @end deffn -@subsubsection IPv6 Address Conversion +@subsubheading IPv6 Address Conversion @deffn {Scheme Procedure} inet-ntop family address @deffnx {C Function} scm_inet_ntop (family, address) @@ -1959,13 +1959,13 @@ the result is an integer with normal host byte ordering. @node Network Databases -@subsection Network Databases +@subsubsection Network Databases This section describes procedures which query various network databases. Care should be taken when using the database routines since they are not reentrant. -@subsubsection The Host Database +@subsubheading The Host Database A @dfn{host object} is a structure that represents what is known about a network host, and is the usual way of representing a system's network @@ -2043,7 +2043,8 @@ Close the stream used by @code{gethostent}. The return value is unspecified. If @var{stayopen} is omitted, this is equivalent to @code{endhostent}. Otherwise it is equivalent to @code{sethostent stayopen}. @end deffn -@subsubsection The Network Database + +@subsubheading The Network Database The following functions accept an object representing a network and return a selected component: @@ -2101,7 +2102,7 @@ If @var{stayopen} is omitted, this is equivalent to @code{endnetent}. Otherwise it is equivalent to @code{setnetent stayopen}. @end deffn -@subsubsection The Protocol Database +@subsubheading The Protocol Database The following functions accept an object representing a protocol and return a selected component: @@ -2154,7 +2155,7 @@ If @var{stayopen} is omitted, this is equivalent to @code{endprotoent}. Otherwise it is equivalent to @code{setprotoent stayopen}. @end deffn -@subsubsection The Service Database +@subsubheading The Service Database The following functions accept an object representing a service and return a selected component: @@ -2224,7 +2225,7 @@ Otherwise it is equivalent to @code{setservent stayopen}. @end deffn @node Network Sockets and Communication -@subsection Network Sockets and Communication +@subsubsection Network Sockets and Communication Socket ports can be created using @code{socket} and @code{socketpair}. The ports are initially unbuffered, to make reading and writing to the @@ -2614,18 +2615,11 @@ These procedures are inconvenient to use at present, but consider: @node Internet Socket Examples -@subsection Network Socket Examples - -The following sections give examples of how to use network sockets. - -@menu -* Internet Socket Client:: -* Internet Socket Server:: -@end menu +@subsubsection Network Socket Examples +The following give examples of how to use network sockets. -@node Internet Socket Client -@subsubsection Internet Socket Client Example +@subsubheading Internet Socket Client Example @cindex socket client example The following example demonstrates an Internet socket client. @@ -2644,8 +2638,7 @@ returns the contents of the root index URL. @end example -@node Internet Socket Server -@subsubsection Internet Socket Server Example +@subsubheading Internet Socket Server Example @cindex socket server example The following example shows a simple Internet server which listens on @@ -2681,7 +2674,7 @@ client. @node System Identification -@section System Identification +@subsection System Identification This section lists the various procedures Guile provides for accessing information about the system it runs on. @@ -2740,7 +2733,7 @@ no other easy or unambiguous way of detecting such features. @end deffn @node Locales -@section Locales +@subsection Locales @deffn {Scheme Procedure} setlocale category [locale] @deffnx {C Function} scm_setlocale (category, locale) @@ -2769,7 +2762,7 @@ Manual}. @end deffn @node Encryption -@section Encryption +@subsection Encryption Please note that the procedures in this section are not suited for strong encryption, they are only interfaces to the well-known and diff --git a/doc/ref/preface.texi b/doc/ref/preface.texi index eb7764646..9e5cb10f6 100644 --- a/doc/ref/preface.texi +++ b/doc/ref/preface.texi @@ -4,9 +4,8 @@ @c Free Software Foundation, Inc. @c See the file guile.texi for copying conditions. -@iftex -@page -@unnumbered Preface +@node Preface +@chapter Preface This reference manual documents Guile, GNU's Ubiquitous Intelligent Language for Extensions. It describes how to use Guile in many useful @@ -14,17 +13,16 @@ and interesting ways. This is edition @value{MANUAL-EDITION} of the reference manual, and corresponds to Guile version @value{VERSION}. -@end iftex +@menu +* Contributors:: +* Guile License:: +* Manual Layout:: +* Manual Conventions:: +@end menu -@iftex -@section Contributors to this Manual -@end iftex - -@ifnottex @node Contributors -@chapter Contributors to this Manual -@end ifnottex +@section Contributors to this Manual The Guile reference and tutorial manuals were written and edited largely by Mark Galassi and Jim Blandy. In particular, Jim wrote the @@ -56,14 +54,8 @@ filling out a lot of the documentation of Scheme data types, control mechanisms and procedures. In addition, he wrote the documentation for Guile's SRFI modules and modules associated with the Guile REPL. -@iftex -@section The Guile License -@end iftex - -@ifnottex @node Guile License -@chapter The Guile License -@end ifnottex +@section The Guile License Guile is Free Software. Guile is copyrighted, not public domain, and there are restrictions on its distribution or redistribution, but @@ -100,98 +92,50 @@ You must be aware there is no warranty whatsoever for Guile. This is described in full in the licenses. -@iftex -@section Layout of this Manual -@end iftex - -@ifnottex @node Manual Layout -@chapter Layout of this Manual -@end ifnottex +@section Layout of this Manual -The manual is divided into five parts. +The manual is divided into five chapters. @table @strong -@item 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 +@item Chapter 1: Introduction to Guile +This part 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. Everything introduced here is documented again and in full by the later parts of the manual. This part also explains how to obtain and install new versions of Guile, and how to report bugs effectively. -@item Part II: Writing and Running Guile Scheme -@itemx Part III: Programming with Guile -Document all aspects of practical programming using Guile. This -covers both the Scheme level --- where we provide an introduction to -the key ideas of the Scheme language --- and use of Guile's @code{scm} -interface to write new primitives and objects in C, and to incorporate -Guile into a C application. It also covers the use of Guile as a -@acronym{POSIX}-compliant script interpreter and how to use the Guile -debugger. - -@c @strong{Part V: Extending Applications Using Guile} explains the options -@c available for using Guile as a application extension language. At the -@c simpler end of the scale, an application might use Guile to define some -@c application-specific primitives in C and then load an application Scheme -@c file. In this case most of the application code is written on the -@c Scheme level, and uses the application-specific primitives as an -@c extension to standard Scheme. At the other end of the scale, an -@c application might be predominantly written in C --- with its main -@c control loop implemented in C --- but make occasional forays into Scheme -@c to, say, read configuration data or run user-defined customization code. -@c This part of the manual covers the complete range of application -@c extension options. - -@item Part IV: Guile API Reference -Documents Guile's core @acronym{API}. Most of the variables and -procedures in Guile's core programming interface are available in both -Scheme and C and are related systematically such that the C interface -can be inferred from the Scheme interface and vice versa. Therefore, -this part of the manual documents the Guile @acronym{API} in +@item Chapter 2: Programming in Scheme +This part provides an overview over programming in Scheme with Guile. +It covers how to invoke the @code{guile} program from the command-line +and how to write scripts in Scheme. It also gives an introduction +into the basic ideas of Scheme itself and to the various extensions +that Guile offers beyond standard Scheme. + +@item Chapter 3: Programming in C +This part provides an overview of how to use Guile in a C program. It +discusses the fundamental concepts that you need to understand to +access the features of Guile, such as dynamic types and the garbage +collector. It explains in a tutorial like manner how to define new +data types and functions for the use by Scheme programs. + +@item Chapter 4: Guile API Reference +This part of the manual documents the Guile @acronym{API} in functionality-based groups with the Scheme and C interfaces presented -side by side. Where the Scheme and C interfaces for a particular -functional area do differ --- which is sometimes inevitable, given the -differences in the structure of the two languages --- this is pointed -out and explained. In all cases the overriding principle is that all -the reference documentation for a given functional area is grouped -together. - -@c the core Scheme language and features that Guile implements. Although -@c the basis for this is the Scheme language described in R5RS, this part -@c of the manual does not assume any prior familiarity with R5RS in -@c particular, or with Scheme in general. Basic Scheme concepts, standard -@c aspects of the Scheme language and Guile extensions on top of R5RS are -@c all documented from scratch, and organized by functionality rather than -@c by the defining standards. - -@item Part V: Guile Modules +side by side. + +@item Chapter 5: Guile Modules Describes some important modules, distributed as part of the Guile distribution, that extend the functionality provided by the Guile -Scheme core. Two important examples are: - -@itemize @bullet -@item -The @acronym{POSIX} module, which provides Scheme-level procedures for -system and network programming that conform to the @acronym{POSIX} -standard. +Scheme core. -@item -The @acronym{SLIB} module, which makes Aubrey Jaffer's portable Scheme -library available for use in Guile. -@end itemize @end table -@iftex -@section Manual Conventions -@end iftex - -@ifnottex @node Manual Conventions -@chapter Conventions used in this Manual -@end ifnottex +@section Conventions used in this Manual We use some conventions in this manual. diff --git a/doc/ref/program.texi b/doc/ref/program.texi index 7471f298c..92a2db933 100644 --- a/doc/ref/program.texi +++ b/doc/ref/program.texi @@ -6,7 +6,7 @@ @page @node Programming Overview -@chapter An Overview of Guile Programming +@section An Overview of Guile Programming Guile is designed as an extension language interpreter that is straightforward to integrate with applications written in C (and C++). @@ -35,7 +35,7 @@ available. @node Extending Dia -@section How One Might Extend Dia Using Guile +@subsection How One Might Extend Dia Using Guile Dia is a free software program for drawing schematic diagrams like flow charts and floor plans (REFFIXME). This section conducts the thought @@ -55,7 +55,7 @@ applications in general. @node Dia Objective -@subsection Deciding Why You Want to Add Guile +@subsubsection Deciding Why You Want to Add Guile First off, you should understand why you want to add Guile to Dia at all, and that means forming a picture of what Dia does and how it does @@ -107,7 +107,7 @@ current page: @node Dia Steps -@subsection Four Steps Required to Add Guile +@subsubsection Four Steps Required to Add Guile Assuming this objective, four steps are needed to achieve it. @@ -135,7 +135,7 @@ The following subsections expand on these four points in turn. @node Dia Smobs -@subsection How to Represent Dia Data in Scheme +@subsubsection How to Represent Dia Data in Scheme For all but the most trivial applications, you will probably want to allow some representation of your domain objects to exist on the Scheme @@ -268,7 +268,7 @@ For full documentation on defining and using SMOB types, see @node Dia Primitives -@subsection Writing Guile Primitives for Dia +@subsubsection Writing Guile Primitives for Dia Once the details of object representation are decided, writing the primitive function code that you need is usually straightforward. @@ -328,7 +328,7 @@ structure of Guile-enabled code (@pxref{Dia Structure}). @node Dia Hook -@subsection Providing a Hook for the Evaluation of Scheme Code +@subsubsection Providing a Hook for the Evaluation of Scheme Code To make the Guile integration useful, you have to design some kind of hook into your application that application users can use to cause their @@ -348,7 +348,7 @@ calling the @code{scm_c_eval_string} function. @node Dia Structure -@subsection Top-level Structure of Guile-enabled Dia +@subsubsection Top-level Structure of Guile-enabled Dia Let's assume that the pre-Guile Dia code looks structurally like this: @@ -408,7 +408,7 @@ ideal place for this. @node Dia Advanced -@subsection Going Further with Dia and Guile +@subsubsection Going Further with Dia and Guile The steps described so far implement an initial Guile integration that already gives a lot of additional power to Dia application users. But @@ -521,7 +521,7 @@ such application yet exists; but it'll happen some day @dots{} @node Scheme vs C -@section Why Scheme is More Hackable Than C +@subsection Why Scheme is More Hackable Than C Underlying Guile's value proposition is the assumption that programming in a high level language, specifically Guile's implementation of Scheme, @@ -565,7 +565,7 @@ writing new code in their base implementation languages. @node Testbed Example -@section Example: Using Guile for an Application Testbed +@subsection Example: Using Guile for an Application Testbed As an example of what this means in practice, imagine writing a testbed for an application that is tested by submitting various requests (via a @@ -594,7 +594,7 @@ language from the application.) @node Programming Options -@section A Choice of Programming Options +@subsection A Choice of Programming Options The preceding arguments and example point to a model of Guile programming that is applicable in many cases. According to this model, @@ -647,7 +647,7 @@ your answers. @node Available Functionality -@subsection What Functionality is Already Available? +@subsubsection What Functionality is Already Available? Suppose, for the sake of argument, that you would prefer to write your whole application in Scheme. Then the API available to you consists of: @@ -704,19 +704,19 @@ existing C code to the Guile world, see REFFIXME. @node Basic Constraints -@subsection Functional and Performance Constraints +@subsubsection Functional and Performance Constraints @node Style Choices -@subsection Your Preferred Programming Style +@subsubsection Your Preferred Programming Style @node Program Control -@subsection What Controls Program Execution? +@subsubsection What Controls Program Execution? @node User Programming -@section How About Application Users? +@subsection How About Application Users? So far we have considered what Guile programming means for an application developer. But what if you are instead @emph{using} an diff --git a/doc/ref/ref-init.texi b/doc/ref/ref-init.texi new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/doc/ref/ref-init.texi diff --git a/doc/ref/repl-modules.texi b/doc/ref/repl-modules.texi index c2ab7b9d8..de744dc09 100644 --- a/doc/ref/repl-modules.texi +++ b/doc/ref/repl-modules.texi @@ -6,7 +6,7 @@ @page @node Readline Support -@chapter Readline Support +@section Readline Support @c FIXME::martin: Review me! @@ -26,7 +26,7 @@ history entries. @node Loading Readline Support -@section Loading Readline Support +@subsection 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: @@ -67,7 +67,7 @@ expressions available. @node Readline Options -@section Readline Options +@subsection Readline Options @c FIXME::martin: Review me! @@ -106,7 +106,7 @@ the readline module, because it is defined in that module. @page @node Value History -@chapter Value History +@section Value History @c FIXME::martin: Review me! diff --git a/doc/ref/scheme-binding.texi b/doc/ref/scheme-binding.texi index a89ddb80b..e69de29bb 100644 --- a/doc/ref/scheme-binding.texi +++ b/doc/ref/scheme-binding.texi @@ -1,283 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@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 - -@cindex variable definition - -On the top level of a program (i.e. when not inside the body of a -procedure definition or a @code{let}, @code{let*} or @code{letrec} -expression), a definition of the form - -@lisp -(define a @var{value}) -@end lisp - -@noindent -defines a variable called @code{a} and sets it to the value @var{value}. - -If the variable already exists, because it has already been created by a -previous @code{define} expression with the same name, its value is -simply changed to the new @var{value}. In this case, then, the above -form is completely equivalent to - -@lisp -(set! a @var{value}) -@end lisp - -@noindent -This equivalence means that @code{define} can be used interchangeably -with @code{set!} to change the value of variables at the top level of -the REPL or a Scheme source file. It is useful during interactive -development when reloading a Scheme file that you have modified, because -it allows the @code{define} expressions in that file to work as expected -both the first time that the file is loaded and on subsequent occasions. - -Note, though, that @code{define} and @code{set!} are not always -equivalent. For example, a @code{set!} is not allowed if the named -variable does not already exist, and the two expressions can behave -differently in the case where there are imported variables visible from -another module. - -@deffn {Scheme Syntax} define name value -Create a top level variable named @var{name} with value @var{value}. -If the named variable already exists, just change its value. The return -value of a @code{define} expression is unspecified. -@end deffn - -The C API equivalents of @code{define} are @code{scm_define} and -@code{scm_c_define}, which differ from each other in whether the -variable name is specified as a @code{SCM} symbol or as a -null-terminated C string. - -@deffn {C Function} scm_define (sym, value) -@deffnx {C Function} scm_c_define (const char *name, value) -C equivalents of @code{define}, with variable name specified either by -@var{sym}, a symbol, or by @var{name}, a null-terminated C string. Both -variants return the new or preexisting variable object. -@end deffn - -@code{define} (when it occurs at top level), @code{scm_define} and -@code{scm_c_define} all create or set the value of a variable in the top -level environment of the current module. If there was not already a -variable with the specified name belonging to the current module, but a -similarly named variable from another module was visible through having -been imported, the newly created variable in the current module will -shadow the imported variable, such that the imported variable is no -longer visible. - -Attention: Scheme 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 though 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 whether a symbol is bound in the -top level environment. - -@c NJFIXME explain [env] -@deffn {Scheme Procedure} defined? sym [env] -@deffnx {C Function} scm_defined_p (sym, env) -Return @code{#t} if @var{sym} is defined in the lexical environment @var{env}. When @var{env} is not specified, look in the top-level environment as defined by the current module. -@end deffn - - -@c Local Variables: -@c TeX-master: "guile.texi" -@c End: diff --git a/doc/ref/scheme-compound.texi b/doc/ref/scheme-compound.texi index 49e206161..e69de29bb 100644 --- a/doc/ref/scheme-compound.texi +++ b/doc/ref/scheme-compound.texi @@ -1,2540 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@page -@node Compound Data Types -@chapter Compound Data Types - -This chapter describes Guile's compound data types. By @dfn{compound} -we mean that the primary purpose of these data types is to act as -containers for other kinds of data (including other compound objects). -For instance, a (non-uniform) vector with length 5 is a container that -can hold five arbitrary Scheme objects. - -The various kinds of container object differ from each other in how -their memory is allocated, how they are indexed, and how particular -values can be looked up within them. - -@menu -* Pairs:: Scheme's basic building block. -* Lists:: Special list functions supported by Guile. -* Vectors:: One-dimensional arrays of Scheme objects. -* Records:: -* Structures:: -* Arrays:: Arrays of values. -* Association Lists and Hash Tables:: Dictionary data types. -@end menu - - -@node Pairs -@section Pairs -@tpindex Pairs - -Pairs are used to combine two Scheme objects into one compound object. -Hence the name: A pair stores a pair of objects. - -The data type @dfn{pair} is extremely important in Scheme, just like in -any other Lisp dialect. The reason is that pairs are not only used to -make two values available as one object, but that pairs are used for -constructing lists of values. Because lists are so important in Scheme, -they are described in a section of their own (@pxref{Lists}). - -Pairs can literally get entered in source code or at the REPL, in the -so-called @dfn{dotted list} syntax. This syntax consists of an opening -parentheses, the first element of the pair, a dot, the second element -and a closing parentheses. The following example shows how a pair -consisting of the two numbers 1 and 2, and a pair containing the symbols -@code{foo} and @code{bar} can be entered. It is very important to write -the whitespace before and after the dot, because otherwise the Scheme -parser would not be able to figure out where to split the tokens. - -@lisp -(1 . 2) -(foo . bar) -@end lisp - -But beware, if you want to try out these examples, you have to -@dfn{quote} the expressions. More information about quotation is -available in the section (REFFIXME). The correct way to try these -examples is as follows. - -@lisp -'(1 . 2) -@result{} -(1 . 2) -'(foo . bar) -@result{} -(foo . bar) -@end lisp - -A new pair is made by calling the procedure @code{cons} with two -arguments. Then the argument values are stored into a newly allocated -pair, and the pair is returned. The name @code{cons} stands for -"construct". Use the procedure @code{pair?} to test whether a -given Scheme object is a pair or not. - -@rnindex cons -@deffn {Scheme Procedure} cons x y -@deffnx {C Function} scm_cons (x, y) -Return a newly allocated pair whose car is @var{x} and whose -cdr is @var{y}. The pair is guaranteed to be different (in the -sense of @code{eq?}) from every previously existing object. -@end deffn - -@rnindex pair? -@deffn {Scheme Procedure} pair? x -@deffnx {C Function} scm_pair_p (x) -Return @code{#t} if @var{x} is a pair; otherwise return -@code{#f}. -@end deffn - -The two parts of a pair are traditionally called @dfn{car} and -@dfn{cdr}. They can be retrieved with procedures of the same name -(@code{car} and @code{cdr}), and can be modified with the procedures -@code{set-car!} and @code{set-cdr!}. Since a very common operation in -Scheme programs is to access the car of a pair, or the car of the cdr of -a pair, etc., the procedures called @code{caar}, @code{cadr} and so on -are also predefined. - -@rnindex car -@rnindex cdr -@deffn {Scheme Procedure} car pair -@deffnx {Scheme Procedure} cdr pair -Return the car or the cdr of @var{pair}, respectively. -@end deffn - -@deffn {Scheme Procedure} caar pair -@deffnx {Scheme Procedure} cadr pair @dots{} -@deffnx {Scheme Procedure} cdddar pair -@deffnx {Scheme Procedure} cddddr pair -These procedures are compositions of @code{car} and @code{cdr}, where -for example @code{caddr} could be defined by - -@lisp -(define caddr (lambda (x) (car (cdr (cdr x))))) -@end lisp -@end deffn - -@rnindex set-car! -@deffn {Scheme Procedure} set-car! pair value -@deffnx {C Function} scm_set_car_x (pair, value) -Stores @var{value} in the car field of @var{pair}. The value returned -by @code{set-car!} is unspecified. -@end deffn - -@rnindex set-cdr! -@deffn {Scheme Procedure} set-cdr! pair value -@deffnx {C Function} scm_set_cdr_x (pair, value) -Stores @var{value} in the cdr field of @var{pair}. The value returned -by @code{set-cdr!} is unspecified. -@end deffn - - -@node Lists -@section Lists -@tpindex Lists - -A very important data type in Scheme---as well as in all other Lisp -dialects---is the data type @dfn{list}.@footnote{Strictly speaking, -Scheme does not have a real datatype @dfn{list}. Lists are made up of -@dfn{chained pairs}, and only exist by definition---a list is a chain -of pairs which looks like a list.} - -This is the short definition of what a list is: - -@itemize @bullet -@item -Either the empty list @code{()}, - -@item -or a pair which has a list in its cdr. -@end itemize - -@c FIXME::martin: Describe the pair chaining in more detail. - -@c FIXME::martin: What is a proper, what an improper list? -@c What is a circular list? - -@c FIXME::martin: Maybe steal some graphics from the Elisp reference -@c manual? - -@menu -* List Syntax:: Writing literal lists. -* List Predicates:: Testing lists. -* List Constructors:: Creating new lists. -* List Selection:: Selecting from lists, getting their length. -* Append/Reverse:: Appending and reversing lists. -* List Modification:: Modifying existing lists. -* List Searching:: Searching for list elements -* List Mapping:: Applying procedures to lists. -@end menu - -@node List Syntax -@subsection List Read Syntax - -The syntax for lists is an opening parentheses, then all the elements of -the list (separated by whitespace) and finally a closing -parentheses.@footnote{Note that there is no separation character between -the list elements, like a comma or a semicolon.}. - -@lisp -(1 2 3) ; @r{a list of the numbers 1, 2 and 3} -("foo" bar 3.1415) ; @r{a string, a symbol and a real number} -() ; @r{the empty list} -@end lisp - -The last example needs a bit more explanation. A list with no elements, -called the @dfn{empty list}, is special in some ways. It is used for -terminating lists by storing it into the cdr of the last pair that makes -up a list. An example will clear that up: - -@lisp -(car '(1)) -@result{} -1 -(cdr '(1)) -@result{} -() -@end lisp - -This example also shows that lists have to be quoted (REFFIXME) when -written, because they would otherwise be mistakingly taken as procedure -applications (@pxref{Simple Invocation}). - - -@node List Predicates -@subsection List Predicates - -Often it is useful to test whether a given Scheme object is a list or -not. List-processing procedures could use this information to test -whether their input is valid, or they could do different things -depending on the datatype of their arguments. - -@rnindex list? -@deffn {Scheme Procedure} list? x -@deffnx {C Function} scm_list_p (x) -Return @code{#t} iff @var{x} is a proper list, else @code{#f}. -@end deffn - -The predicate @code{null?} is often used in list-processing code to -tell whether a given list has run out of elements. That is, a loop -somehow deals with the elements of a list until the list satisfies -@code{null?}. Then, the algorithm terminates. - -@rnindex null? -@deffn {Scheme Procedure} null? x -@deffnx {C Function} scm_null_p (x) -Return @code{#t} iff @var{x} is the empty list, else @code{#f}. -@end deffn - -@node List Constructors -@subsection List Constructors - -This section describes the procedures for constructing new lists. -@code{list} simply returns a list where the elements are the arguments, -@code{cons*} is similar, but the last argument is stored in the cdr of -the last pair of the list. - -@c C Function scm_list(rest) used to be documented here, but it's a -@c no-op since it does nothing but return the list the caller must -@c have already created. -@c -@deffn {Scheme Procedure} list elem1 @dots{} elemN -@deffnx {C Function} scm_list_1 (elem1) -@deffnx {C Function} scm_list_2 (elem1, elem2) -@deffnx {C Function} scm_list_3 (elem1, elem2, elem3) -@deffnx {C Function} scm_list_4 (elem1, elem2, elem3, elem4) -@deffnx {C Function} scm_list_5 (elem1, elem2, elem3, elem4, elem5) -@deffnx {C Function} scm_list_n (elem1, @dots{}, elemN, @nicode{SCM_UNDEFINED}) -@rnindex list -Return a new list containing elements @var{elem1} to @var{elemN}. - -@code{scm_list_n} takes a variable number of arguments, terminated by -the special @code{SCM_UNDEFINED}. That final @code{SCM_UNDEFINED} is -not included in the list. None of @var{elem1} to @var{elemN} can -themselves be @code{SCM_UNDEFINED}, or @code{scm_list_n} will -terminate at that point. -@end deffn - -@c C Function scm_cons_star(arg1,rest) used to be documented here, -@c but it's not really a useful interface, since it expects the -@c caller to have already consed up all but the first argument -@c already. -@c -@deffn {Scheme Procedure} cons* arg1 arg2 @dots{} -Like @code{list}, but the last arg provides the tail of the -constructed list, returning @code{(cons @var{arg1} (cons -@var{arg2} (cons @dots{} @var{argn})))}. Requires at least one -argument. If given one argument, that argument is returned as -result. This function is called @code{list*} in some other -Schemes and in Common LISP. -@end deffn - -@deffn {Scheme Procedure} list-copy lst -@deffnx {C Function} scm_list_copy (lst) -Return a (newly-created) copy of @var{lst}. -@end deffn - -@deffn {Scheme Procedure} make-list n [init] -Create a list containing of @var{n} elements, where each element is -initialized to @var{init}. @var{init} defaults to the empty list -@code{()} if not given. -@end deffn - -Note that @code{list-copy} only makes a copy of the pairs which make up -the spine of the lists. The list elements are not copied, which means -that modifying the elements of the new list also modifies the elements -of the old list. On the other hand, applying procedures like -@code{set-cdr!} or @code{delv!} to the new list will not alter the old -list. If you also need to copy the list elements (making a deep copy), -use the procedure @code{copy-tree} (@pxref{Copying}). - -@node List Selection -@subsection List Selection - -These procedures are used to get some information about a list, or to -retrieve one or more elements of a list. - -@rnindex length -@deffn {Scheme Procedure} length lst -@deffnx {C Function} scm_length (lst) -Return the number of elements in list @var{lst}. -@end deffn - -@deffn {Scheme Procedure} last-pair lst -@deffnx {C Function} scm_last_pair (lst) -Return a pointer to the last pair in @var{lst}, signalling an error if -@var{lst} is circular. -@end deffn - -@rnindex list-ref -@deffn {Scheme Procedure} list-ref list k -@deffnx {C Function} scm_list_ref (list, k) -Return the @var{k}th element from @var{list}. -@end deffn - -@rnindex list-tail -@deffn {Scheme Procedure} list-tail lst k -@deffnx {Scheme Procedure} list-cdr-ref lst k -@deffnx {C Function} scm_list_tail (lst, k) -Return the "tail" of @var{lst} beginning with its @var{k}th element. -The first element of the list is considered to be element 0. - -@code{list-tail} and @code{list-cdr-ref} are identical. It may help to -think of @code{list-cdr-ref} as accessing the @var{k}th cdr of the list, -or returning the results of cdring @var{k} times down @var{lst}. -@end deffn - -@deffn {Scheme Procedure} list-head lst k -@deffnx {C Function} scm_list_head (lst, k) -Copy the first @var{k} elements from @var{lst} into a new list, and -return it. -@end deffn - -@node Append/Reverse -@subsection Append and Reverse - -@code{append} and @code{append!} are used to concatenate two or more -lists in order to form a new list. @code{reverse} and @code{reverse!} -return lists with the same elements as their arguments, but in reverse -order. The procedure variants with an @code{!} directly modify the -pairs which form the list, whereas the other procedures create new -pairs. This is why you should be careful when using the side-effecting -variants. - -@rnindex append -@deffn {Scheme Procedure} append lst1 @dots{} lstN -@deffnx {Scheme Procedure} append! lst1 @dots{} lstN -@deffnx {C Function} scm_append (lstlst) -@deffnx {C Function} scm_append_x (lstlst) -Return a list comprising all the elements of lists @var{lst1} to -@var{lstN}. - -@lisp -(append '(x) '(y)) @result{} (x y) -(append '(a) '(b c d)) @result{} (a b c d) -(append '(a (b)) '((c))) @result{} (a (b) (c)) -@end lisp - -The last argument @var{lstN} may actually be any object; an improper -list results if the last argument is not a proper list. - -@lisp -(append '(a b) '(c . d)) @result{} (a b c . d) -(append '() 'a) @result{} a -@end lisp - -@code{append} doesn't modify the given lists, but the return may share -structure with the final @var{lstN}. @code{append!} modifies the -given lists to form its return. - -For @code{scm_append} and @code{scm_append_x}, @var{lstlst} is a list -of the list operands @var{lst1} @dots{} @var{lstN}. That @var{lstlst} -itself is not modified or used in the return. -@end deffn - -@rnindex reverse -@deffn {Scheme Procedure} reverse lst -@deffnx {Scheme Procedure} reverse! lst [newtail] -@deffnx {C Function} scm_reverse (lst) -@deffnx {C Function} scm_reverse_x (lst, newtail) -Return a list comprising the elements of @var{lst}, in reverse order. - -@code{reverse} constructs a new list, @code{reverse!} modifies -@var{lst} in constructing its return. - -For @code{reverse!}, the optional @var{newtail} is appended to to the -result. @var{newtail} isn't reversed, it simply becomes the list -tail. For @code{scm_reverse_x}, the @var{newtail} parameter is -mandatory, but can be @code{SCM_EOL} if no further tail is required. -@end deffn - -@node List Modification -@subsection List Modification - -The following procedures modify an existing list, either by changing -elements of the list, or by changing the list structure itself. - -@deffn {Scheme Procedure} list-set! list k val -@deffnx {C Function} scm_list_set_x (list, k, val) -Set the @var{k}th element of @var{list} to @var{val}. -@end deffn - -@deffn {Scheme Procedure} list-cdr-set! list k val -@deffnx {C Function} scm_list_cdr_set_x (list, k, val) -Set the @var{k}th cdr of @var{list} to @var{val}. -@end deffn - -@deffn {Scheme Procedure} delq item lst -@deffnx {C Function} scm_delq (item, lst) -Return a newly-created copy of @var{lst} with elements -@code{eq?} to @var{item} removed. This procedure mirrors -@code{memq}: @code{delq} compares elements of @var{lst} against -@var{item} with @code{eq?}. -@end deffn - -@deffn {Scheme Procedure} delv item lst -@deffnx {C Function} scm_delv (item, lst) -Return a newly-created copy of @var{lst} with elements -@code{eqv?} to @var{item} removed. This procedure mirrors -@code{memv}: @code{delv} compares elements of @var{lst} against -@var{item} with @code{eqv?}. -@end deffn - -@deffn {Scheme Procedure} delete item lst -@deffnx {C Function} scm_delete (item, lst) -Return a newly-created copy of @var{lst} with elements -@code{equal?} to @var{item} removed. This procedure mirrors -@code{member}: @code{delete} compares elements of @var{lst} -against @var{item} with @code{equal?}. -@end deffn - -@deffn {Scheme Procedure} delq! item lst -@deffnx {Scheme Procedure} delv! item lst -@deffnx {Scheme Procedure} delete! item lst -@deffnx {C Function} scm_delq_x (item, lst) -@deffnx {C Function} scm_delv_x (item, lst) -@deffnx {C Function} scm_delete_x (item, lst) -These procedures are destructive versions of @code{delq}, @code{delv} -and @code{delete}: they modify the pointers in the existing @var{lst} -rather than creating a new list. Caveat evaluator: Like other -destructive list functions, these functions cannot modify the binding of -@var{lst}, and so cannot be used to delete the first element of -@var{lst} destructively. -@end deffn - -@deffn {Scheme Procedure} delq1! item lst -@deffnx {C Function} scm_delq1_x (item, lst) -Like @code{delq!}, but only deletes the first occurrence of -@var{item} from @var{lst}. Tests for equality using -@code{eq?}. See also @code{delv1!} and @code{delete1!}. -@end deffn - -@deffn {Scheme Procedure} delv1! item lst -@deffnx {C Function} scm_delv1_x (item, lst) -Like @code{delv!}, but only deletes the first occurrence of -@var{item} from @var{lst}. Tests for equality using -@code{eqv?}. See also @code{delq1!} and @code{delete1!}. -@end deffn - -@deffn {Scheme Procedure} delete1! item lst -@deffnx {C Function} scm_delete1_x (item, lst) -Like @code{delete!}, but only deletes the first occurrence of -@var{item} from @var{lst}. Tests for equality using -@code{equal?}. See also @code{delq1!} and @code{delv1!}. -@end deffn - -@deffn {Scheme Procedure} filter pred lst -@deffnx {Scheme Procedure} filter! pred lst -Return a list containing all elements from @var{lst} which satisfy the -predicate @var{pred}. The elements in the result list have the same -order as in @var{lst}. The order in which @var{pred} is applied to -the list elements is not specified. - -@code{filter!} is allowed, but not required to modify the structure of -@end deffn - -@node List Searching -@subsection List Searching - -The following procedures search lists for particular elements. They use -different comparison predicates for comparing list elements with the -object to be searched. When they fail, they return @code{#f}, otherwise -they return the sublist whose car is equal to the search object, where -equality depends on the equality predicate used. - -@rnindex memq -@deffn {Scheme Procedure} memq x lst -@deffnx {C Function} scm_memq (x, lst) -Return the first sublist of @var{lst} whose car is @code{eq?} -to @var{x} where the sublists of @var{lst} are the non-empty -lists returned by @code{(list-tail @var{lst} @var{k})} for -@var{k} less than the length of @var{lst}. If @var{x} does not -occur in @var{lst}, then @code{#f} (not the empty list) is -returned. -@end deffn - -@rnindex memv -@deffn {Scheme Procedure} memv x lst -@deffnx {C Function} scm_memv (x, lst) -Return the first sublist of @var{lst} whose car is @code{eqv?} -to @var{x} where the sublists of @var{lst} are the non-empty -lists returned by @code{(list-tail @var{lst} @var{k})} for -@var{k} less than the length of @var{lst}. If @var{x} does not -occur in @var{lst}, then @code{#f} (not the empty list) is -returned. -@end deffn - -@rnindex member -@deffn {Scheme Procedure} member x lst -@deffnx {C Function} scm_member (x, lst) -Return the first sublist of @var{lst} whose car is -@code{equal?} to @var{x} where the sublists of @var{lst} are -the non-empty lists returned by @code{(list-tail @var{lst} -@var{k})} for @var{k} less than the length of @var{lst}. If -@var{x} does not occur in @var{lst}, then @code{#f} (not the -empty list) is returned. -@end deffn - - -@node List Mapping -@subsection List Mapping - -List processing is very convenient in Scheme because the process of -iterating over the elements of a list can be highly abstracted. The -procedures in this section are the most basic iterating procedures for -lists. They take a procedure and one or more lists as arguments, and -apply the procedure to each element of the list. They differ in their -return value. - -@rnindex map -@c begin (texi-doc-string "guile" "map") -@deffn {Scheme Procedure} map proc arg1 arg2 @dots{} -@deffnx {Scheme Procedure} map-in-order proc arg1 arg2 @dots{} -@deffnx {C Function} scm_map (proc, arg1, args) -Apply @var{proc} to each element of the list @var{arg1} (if only two -arguments are given), or to the corresponding elements of the argument -lists (if more than two arguments are given). The result(s) of the -procedure applications are saved and returned in a list. For -@code{map}, the order of procedure applications is not specified, -@code{map-in-order} applies the procedure from left to right to the list -elements. -@end deffn - -@rnindex for-each -@c begin (texi-doc-string "guile" "for-each") -@deffn {Scheme Procedure} for-each proc arg1 arg2 @dots{} -Like @code{map}, but the procedure is always applied from left to right, -and the result(s) of the procedure applications are thrown away. The -return value is not specified. -@end deffn - - -@node Vectors -@section Vectors -@tpindex Vectors - -Vectors are sequences of Scheme objects. Unlike lists, the length of a -vector, once the vector is created, cannot be changed. The advantage of -vectors over lists is that the time required to access one element of a vector -given its @dfn{position} (synonymous with @dfn{index}), a zero-origin number, -is constant, whereas lists have an access time linear to the position of the -accessed element in the list. - -Vectors can contain any kind of Scheme object; it is even possible to have -different types of objects in the same vector. For vectors containing -vectors, you may wish to use arrays, instead. Note, too, that some array -procedures operate happily on vectors (@pxref{Arrays}). - -@menu -* Vector Syntax:: Read syntax for vectors. -* Vector Creation:: Dynamic vector creation and validation. -* Vector Accessors:: Accessing and modifying vector contents. -@end menu - - -@node Vector Syntax -@subsection Read Syntax for Vectors - -Vectors can literally be entered in source code, just like strings, -characters or some of the other data types. The read syntax for vectors -is as follows: A sharp sign (@code{#}), followed by an opening -parentheses, all elements of the vector in their respective read syntax, -and finally a closing parentheses. The following are examples of the -read syntax for vectors; where the first vector only contains numbers -and the second three different object types: a string, a symbol and a -number in hexadecimal notation. - -@lisp -#(1 2 3) -#("Hello" foo #xdeadbeef) -@end lisp - -Like lists, vectors have to be quoted (REFFIXME): - -@lisp -'#(a b c) @result{} #(a b c) -@end lisp - -@node Vector Creation -@subsection Dynamic Vector Creation and Validation - -Instead of creating a vector implicitly by using the read syntax just -described, you can create a vector dynamically by calling one of the -@code{vector} and @code{list->vector} primitives with the list of Scheme -values that you want to place into a vector. The size of the vector -thus created is determined implicitly by the number of arguments given. - -@rnindex vector -@rnindex list->vector -@deffn {Scheme Procedure} vector . l -@deffnx {Scheme Procedure} list->vector l -@deffnx {C Function} scm_vector (l) -Return a newly allocated vector composed of the -given arguments. Analogous to @code{list}. - -@lisp -(vector 'a 'b 'c) @result{} #(a b c) -@end lisp -@end deffn - -(As an aside, an interesting implementation detail is that the Guile -reader reads the @code{#(@dots{})} syntax by reading everything but the -initial @code{#} as a @emph{list}, and then passing the list that -results to @code{list->vector}. Notice how neatly this fits with the -similarity between the read (and print) syntaxes for lists and vectors.) - -The inverse operation is @code{vector->list}: - -@rnindex vector->list -@deffn {Scheme Procedure} vector->list v -@deffnx {C Function} scm_vector_to_list (v) -Return a newly allocated list composed of the elements of @var{v}. - -@lisp -(vector->list '#(dah dah didah)) @result{} (dah dah didah) -(list->vector '(dididit dah)) @result{} #(dididit dah) -@end lisp -@end deffn - -To allocate a vector with an explicitly specified size, use -@code{make-vector}. With this primitive you can also specify an initial -value for the vector elements (the same value for all elements, that -is): - -@rnindex make-vector -@deffn {Scheme Procedure} make-vector k [fill] -@deffnx {C Function} scm_make_vector (k, fill) -Return a newly allocated vector of @var{k} elements. If a -second argument is given, then each position is initialized to -@var{fill}. Otherwise the initial contents of each position is -unspecified. -@end deffn - -To check whether an arbitrary Scheme value @emph{is} a vector, use the -@code{vector?} primitive: - -@rnindex vector? -@deffn {Scheme Procedure} vector? obj -@deffnx {C Function} scm_vector_p (obj) -Return @code{#t} if @var{obj} is a vector, otherwise return -@code{#f}. -@end deffn - - -@node Vector Accessors -@subsection Accessing and Modifying Vector Contents - -@code{vector-length} and @code{vector-ref} return information about a -given vector, respectively its size and the elements that are contained -in the vector. - -@rnindex vector-length -@deffn {Scheme Procedure} vector-length vector -@deffnx {C Function} scm_vector_length vector -Return the number of elements in @var{vector} as an exact integer. -@end deffn - -@rnindex vector-ref -@deffn {Scheme Procedure} vector-ref vector k -@deffnx {C Function} scm_vector_ref vector k -Return the contents of position @var{k} of @var{vector}. -@var{k} must be a valid index of @var{vector}. -@lisp -(vector-ref '#(1 1 2 3 5 8 13 21) 5) @result{} 8 -(vector-ref '#(1 1 2 3 5 8 13 21) - (let ((i (round (* 2 (acos -1))))) - (if (inexact? i) - (inexact->exact i) - i))) @result{} 13 -@end lisp -@end deffn - -A vector created by one of the dynamic vector constructor procedures -(@pxref{Vector Creation}) can be modified using the following -procedures. - -@emph{NOTE:} According to R5RS, it is an error to use any of these -procedures on a literally read vector, because such vectors should be -considered as constants. Currently, however, Guile does not detect this -error. - -@rnindex vector-set! -@deffn {Scheme Procedure} vector-set! vector k obj -@deffnx {C Function} scm_vector_set_x vector k obj -Store @var{obj} in position @var{k} of @var{vector}. -@var{k} must be a valid index of @var{vector}. -The value returned by @samp{vector-set!} is unspecified. -@lisp -(let ((vec (vector 0 '(2 2 2 2) "Anna"))) - (vector-set! vec 1 '("Sue" "Sue")) - vec) @result{} #(0 ("Sue" "Sue") "Anna") -@end lisp -@end deffn - -@rnindex vector-fill! -@deffn {Scheme Procedure} vector-fill! v fill -@deffnx {C Function} scm_vector_fill_x (v, fill) -Store @var{fill} in every position of @var{vector}. The value -returned by @code{vector-fill!} is unspecified. -@end deffn - -@deffn {Scheme Procedure} vector-move-left! vec1 start1 end1 vec2 start2 -@deffnx {C Function} scm_vector_move_left_x (vec1, start1, end1, vec2, start2) -Copy elements from @var{vec1}, positions @var{start1} to @var{end1}, -to @var{vec2} starting at position @var{start2}. @var{start1} and -@var{start2} are inclusive indices; @var{end1} is exclusive. - -@code{vector-move-left!} copies elements in leftmost order. -Therefore, in the case where @var{vec1} and @var{vec2} refer to the -same vector, @code{vector-move-left!} is usually appropriate when -@var{start1} is greater than @var{start2}. -@end deffn - -@deffn {Scheme Procedure} vector-move-right! vec1 start1 end1 vec2 start2 -@deffnx {C Function} scm_vector_move_right_x (vec1, start1, end1, vec2, start2) -Copy elements from @var{vec1}, positions @var{start1} to @var{end1}, -to @var{vec2} starting at position @var{start2}. @var{start1} and -@var{start2} are inclusive indices; @var{end1} is exclusive. - -@code{vector-move-right!} copies elements in rightmost order. -Therefore, in the case where @var{vec1} and @var{vec2} refer to the -same vector, @code{vector-move-right!} is usually appropriate when -@var{start1} is less than @var{start2}. -@end deffn - - -@node Records -@section Records - -A @dfn{record type} is a first class object representing a user-defined -data type. A @dfn{record} is an instance of a record type. - -@deffn {Scheme Procedure} record? obj -Return @code{#t} if @var{obj} is a record of any type and @code{#f} -otherwise. - -Note that @code{record?} may be true of any Scheme value; there is no -promise that records are disjoint with other Scheme types. -@end deffn - -@deffn {Scheme Procedure} make-record-type type-name field-names -Return a @dfn{record-type descriptor}, a value representing a new data -type disjoint from all others. The @var{type-name} argument must be a -string, but is only used for debugging purposes (such as the printed -representation of a record of the new type). The @var{field-names} -argument is a list of symbols naming the @dfn{fields} of a record of the -new type. It is an error if the list contains any duplicates. It is -unspecified how record-type descriptors are represented. -@end deffn - -@deffn {Scheme Procedure} record-constructor rtd [field-names] -Return a procedure for constructing new members of the type represented -by @var{rtd}. The returned procedure accepts exactly as many arguments -as there are symbols in the given list, @var{field-names}; these are -used, in order, as the initial values of those fields in a new record, -which is returned by the constructor procedure. The values of any -fields not named in that list are unspecified. The @var{field-names} -argument defaults to the list of field names in the call to -@code{make-record-type} that created the type represented by @var{rtd}; -if the @var{field-names} argument is provided, it is an error if it -contains any duplicates or any symbols not in the default list. -@end deffn - -@deffn {Scheme Procedure} record-predicate rtd -Return a procedure for testing membership in the type represented by -@var{rtd}. The returned procedure accepts exactly one argument and -returns a true value if the argument is a member of the indicated record -type; it returns a false value otherwise. -@end deffn - -@deffn {Scheme Procedure} record-accessor rtd field-name -Return a procedure for reading the value of a particular field of a -member of the type represented by @var{rtd}. The returned procedure -accepts exactly one argument which must be a record of the appropriate -type; it returns the current value of the field named by the symbol -@var{field-name} in that record. The symbol @var{field-name} must be a -member of the list of field-names in the call to @code{make-record-type} -that created the type represented by @var{rtd}. -@end deffn - -@deffn {Scheme Procedure} record-modifier rtd field-name -Return a procedure for writing the value of a particular field of a -member of the type represented by @var{rtd}. The returned procedure -accepts exactly two arguments: first, a record of the appropriate type, -and second, an arbitrary Scheme value; it modifies the field named by -the symbol @var{field-name} in that record to contain the given value. -The returned value of the modifier procedure is unspecified. The symbol -@var{field-name} must be a member of the list of field-names in the call -to @code{make-record-type} that created the type represented by -@var{rtd}. -@end deffn - -@deffn {Scheme Procedure} record-type-descriptor record -Return a record-type descriptor representing the type of the given -record. That is, for example, if the returned descriptor were passed to -@code{record-predicate}, the resulting predicate would return a true -value when passed the given record. Note that it is not necessarily the -case that the returned descriptor is the one that was passed to -@code{record-constructor} in the call that created the constructor -procedure that created the given record. -@end deffn - -@deffn {Scheme Procedure} record-type-name rtd -Return the type-name associated with the type represented by rtd. The -returned value is @code{eqv?} to the @var{type-name} argument given in -the call to @code{make-record-type} that created the type represented by -@var{rtd}. -@end deffn - -@deffn {Scheme Procedure} record-type-fields rtd -Return a list of the symbols naming the fields in members of the type -represented by @var{rtd}. The returned value is @code{equal?} to the -field-names argument given in the call to @code{make-record-type} that -created the type represented by @var{rtd}. -@end deffn - - -@node Structures -@section Structures -@tpindex Structures - -[FIXME: this is pasted in from Tom Lord's original guile.texi and should -be reviewed] - -A @dfn{structure type} is a first class user-defined data type. A -@dfn{structure} is an instance of a structure type. A structure type is -itself a structure. - -Structures are less abstract and more general than traditional records. -In fact, in Guile Scheme, records are implemented using structures. - -@menu -* Structure Concepts:: The structure of Structures -* Structure Layout:: Defining the layout of structure types -* Structure Basics:: make-, -ref and -set! procedures for structs -* Vtables:: Accessing type-specific data -@end menu - -@node Structure Concepts -@subsection Structure Concepts - -A structure object consists of a handle, structure data, and a vtable. -The handle is a Scheme value which points to both the vtable and the -structure's data. Structure data is a dynamically allocated region of -memory, private to the structure, divided up into typed fields. A -vtable is another structure used to hold type-specific data. Multiple -structures can share a common vtable. - -Three concepts are key to understanding structures. - -@itemize @bullet{} -@item @dfn{layout specifications} - -Layout specifications determine how memory allocated to structures is -divided up into fields. Programmers must write a layout specification -whenever a new type of structure is defined. - -@item @dfn{structural accessors} - -Structure access is by field number. There is only one set of -accessors common to all structure objects. - -@item @dfn{vtables} - -Vtables, themselves structures, are first class representations of -disjoint sub-types of structures in general. In most cases, when a -new structure is created, programmers must specify a vtable for the -new structure. Each vtable has a field describing the layout of its -instances. Vtables can have additional, user-defined fields as well. -@end itemize - - - -@node Structure Layout -@subsection Structure Layout - -When a structure is created, a region of memory is allocated to hold its -state. The @dfn{layout} of the structure's type determines how that -memory is divided into fields. - -Each field has a specified type. There are only three types allowed, each -corresponding to a one letter code. The allowed types are: - -@itemize @bullet{} -@item 'u' -- unprotected - -The field holds binary data that is not GC protected. - -@item 'p' -- protected - -The field holds a Scheme value and is GC protected. - -@item 's' -- self - -The field holds a Scheme value and is GC protected. When a structure is -created with this type of field, the field is initialized to refer to -the structure's own handle. This kind of field is mainly useful when -mixing Scheme and C code in which the C code may need to compute a -structure's handle given only the address of its malloc'd data. -@end itemize - - -Each field also has an associated access protection. There are only -three kinds of protection, each corresponding to a one letter code. -The allowed protections are: - -@itemize @bullet{} -@item 'w' -- writable - -The field can be read and written. - -@item 'r' -- readable - -The field can be read, but not written. - -@item 'o' -- opaque - -The field can be neither read nor written. This kind -of protection is for fields useful only to built-in routines. -@end itemize - -A layout specification is described by stringing together pairs -of letters: one to specify a field type and one to specify a field -protection. For example, a traditional cons pair type object could -be described as: - -@example -; cons pairs have two writable fields of Scheme data -"pwpw" -@end example - -A pair object in which the first field is held constant could be: - -@example -"prpw" -@end example - -Binary fields, (fields of type "u"), hold one @dfn{word} each. The -size of a word is a machine dependent value defined to be equal to the -value of the C expression: @code{sizeof (long)}. - -The last field of a structure layout may specify a tail array. -A tail array is indicated by capitalizing the field's protection -code ('W', 'R' or 'O'). A tail-array field is replaced by -a read-only binary data field containing an array size. The array -size is determined at the time the structure is created. It is followed -by a corresponding number of fields of the type specified for the -tail array. For example, a conventional Scheme vector can be -described as: - -@example -; A vector is an arbitrary number of writable fields holding Scheme -; values: -"pW" -@end example - -In the above example, field 0 contains the size of the vector and -fields beginning at 1 contain the vector elements. - -A kind of tagged vector (a constant tag followed by conventional -vector elements) might be: - -@example -"prpW" -@end example - - -Structure layouts are represented by specially interned symbols whose -name is a string of type and protection codes. To create a new -structure layout, use this procedure: - -@deffn {Scheme Procedure} make-struct-layout fields -@deffnx {C Function} scm_make_struct_layout (fields) -Return a new structure layout object. - -@var{fields} must be a string made up of pairs of characters -strung together. The first character of each pair describes a field -type, the second a field protection. Allowed types are 'p' for -GC-protected Scheme data, 'u' for unprotected binary data, and 's' for -a field that points to the structure itself. Allowed protections -are 'w' for mutable fields, 'r' for read-only fields, and 'o' for opaque -fields. The last field protection specification may be capitalized to -indicate that the field is a tail-array. -@end deffn - - - -@node Structure Basics -@subsection Structure Basics - -This section describes the basic procedures for creating and accessing -structures. - -@deffn {Scheme Procedure} make-struct vtable tail_array_size . init -@deffnx {C Function} scm_make_struct (vtable, tail_array_size, init) -Create a new structure. - -@var{type} must be a vtable structure (@pxref{Vtables}). - -@var{tail-elts} must be a non-negative integer. If the layout -specification indicated by @var{type} includes a tail-array, -this is the number of elements allocated to that array. - -The @var{init1}, @dots{} are optional arguments describing how -successive fields of the structure should be initialized. Only fields -with protection 'r' or 'w' can be initialized, except for fields of -type 's', which are automatically initialized to point to the new -structure itself; fields with protection 'o' can not be initialized by -Scheme programs. - -If fewer optional arguments than initializable fields are supplied, -fields of type 'p' get default value #f while fields of type 'u' are -initialized to 0. - -Structs are currently the basic representation for record-like data -structures in Guile. The plan is to eventually replace them with a -new representation which will at the same time be easier to use and -more powerful. - -For more information, see the documentation for @code{make-vtable-vtable}. -@end deffn - -@deffn {Scheme Procedure} struct? x -@deffnx {C Function} scm_struct_p (x) -Return @code{#t} iff @var{x} is a structure object, else -@code{#f}. -@end deffn - - -@deffn {Scheme Procedure} struct-ref handle pos -@deffnx {Scheme Procedure} struct-set! struct n value -@deffnx {C Function} scm_struct_ref (handle, pos) -@deffnx {C Function} scm_struct_set_x (struct, n, value) -Access (or modify) the @var{n}th field of @var{struct}. - -If the field is of type 'p', then it can be set to an arbitrary value. - -If the field is of type 'u', then it can only be set to a non-negative -integer value small enough to fit in one machine word. -@end deffn - - - -@node Vtables -@subsection Vtables - -Vtables are structures that are used to represent structure types. Each -vtable contains a layout specification in field -@code{vtable-index-layout} -- instances of the type are laid out -according to that specification. Vtables contain additional fields -which are used only internally to libguile. The variable -@code{vtable-offset-user} is bound to a field number. Vtable fields -at that position or greater are user definable. - -@deffn {Scheme Procedure} struct-vtable handle -@deffnx {C Function} scm_struct_vtable (handle) -Return the vtable structure that describes the type of @var{struct}. -@end deffn - -@deffn {Scheme Procedure} struct-vtable? x -@deffnx {C Function} scm_struct_vtable_p (x) -Return @code{#t} iff @var{x} is a vtable structure. -@end deffn - -If you have a vtable structure, @code{V}, you can create an instance of -the type it describes by using @code{(make-struct V ...)}. But where -does @code{V} itself come from? One possibility is that @code{V} is an -instance of a user-defined vtable type, @code{V'}, so that @code{V} is -created by using @code{(make-struct V' ...)}. Another possibility is -that @code{V} is an instance of the type it itself describes. Vtable -structures of the second sort are created by this procedure: - -@deffn {Scheme Procedure} make-vtable-vtable user_fields tail_array_size . init -@deffnx {C Function} scm_make_vtable_vtable (user_fields, tail_array_size, init) -Return a new, self-describing vtable structure. - -@var{user-fields} is a string describing user defined fields of the -vtable beginning at index @code{vtable-offset-user} -(see @code{make-struct-layout}). - -@var{tail-size} specifies the size of the tail-array (if any) of -this vtable. - -@var{init1}, @dots{} are the optional initializers for the fields of -the vtable. - -Vtables have one initializable system field---the struct printer. -This field comes before the user fields in the initializers passed -to @code{make-vtable-vtable} and @code{make-struct}, and thus works as -a third optional argument to @code{make-vtable-vtable} and a fourth to -@code{make-struct} when creating vtables: - -If the value is a procedure, it will be called instead of the standard -printer whenever a struct described by this vtable is printed. -The procedure will be called with arguments STRUCT and PORT. - -The structure of a struct is described by a vtable, so the vtable is -in essence the type of the struct. The vtable is itself a struct with -a vtable. This could go on forever if it weren't for the -vtable-vtables which are self-describing vtables, and thus terminate -the chain. - -There are several potential ways of using structs, but the standard -one is to use three kinds of structs, together building up a type -sub-system: one vtable-vtable working as the root and one or several -"types", each with a set of "instances". (The vtable-vtable should be -compared to the class <class> which is the class of itself.) - -@lisp -(define ball-root (make-vtable-vtable "pr" 0)) - -(define (make-ball-type ball-color) - (make-struct ball-root 0 - (make-struct-layout "pw") - (lambda (ball port) - (format port "#<a ~A ball owned by ~A>" - (color ball) - (owner ball))) - ball-color)) -(define (color ball) (struct-ref (struct-vtable ball) vtable-offset-user)) -(define (owner ball) (struct-ref ball 0)) - -(define red (make-ball-type 'red)) -(define green (make-ball-type 'green)) - -(define (make-ball type owner) (make-struct type 0 owner)) - -(define ball (make-ball green 'Nisse)) -ball @result{} #<a green ball owned by Nisse> -@end lisp -@end deffn - -@deffn {Scheme Procedure} struct-vtable-name vtable -@deffnx {C Function} scm_struct_vtable_name (vtable) -Return the name of the vtable @var{vtable}. -@end deffn - -@deffn {Scheme Procedure} set-struct-vtable-name! vtable name -@deffnx {C Function} scm_set_struct_vtable_name_x (vtable, name) -Set the name of the vtable @var{vtable} to @var{name}. -@end deffn - -@deffn {Scheme Procedure} struct-vtable-tag handle -@deffnx {C Function} scm_struct_vtable_tag (handle) -Return the vtable tag of the structure @var{handle}. -@end deffn - - -@node Arrays -@section Arrays -@tpindex Arrays - -@menu -* Conventional Arrays:: Arrays with arbitrary data. -* Array Mapping:: Applying a procedure to the contents of an array. -* Uniform Arrays:: Arrays with data of a single type. -* Bit Vectors:: Vectors of bits. -@end menu - -@node Conventional Arrays -@subsection Conventional Arrays - -@dfn{Conventional arrays} are a collection of cells organized into an -arbitrary number of dimensions. Each cell can hold any kind of Scheme -value and can be accessed in constant time by supplying an index for -each dimension. - -This contrasts with uniform arrays, which use memory more efficiently -but can hold data of only a single type. It contrasts also with lists -where inserting and deleting cells is more efficient, but more time is -usually required to access a particular cell. - -A conventional array is displayed as @code{#} followed by the @dfn{rank} -(number of dimensions) followed by the cells, organized into dimensions -using parentheses. The nesting depth of the parentheses is equal to -the rank. - -When an array is created, the range of each dimension must be -specified, e.g., to create a 2@cross{}3 array with a zero-based index: - -@example -(make-array 'ho 2 3) @result{} #2((ho ho ho) (ho ho ho)) -@end example - -The range of each dimension can also be given explicitly, e.g., another -way to create the same array: - -@example -(make-array 'ho '(0 1) '(0 2)) @result{} #2((ho ho ho) (ho ho ho)) -@end example - -A conventional array with one dimension based at zero is identical to -a vector: - -@example -(make-array 'ho 3) @result{} #(ho ho ho) -@end example - -The following procedures can be used with conventional arrays (or -vectors). An argument shown as @var{idx}@dots{} means one parameter -for each dimension in the array. Or a @var{idxlist} is a list of such -values, one for each dimension. - -@deffn {Scheme Procedure} array? obj [prot] -@deffnx {C Function} scm_array_p (obj, prot) -Return @code{#t} if the @var{obj} is an array, and @code{#f} if -not. - -The @var{prot} argument is used with uniform arrays (@pxref{Uniform -Arrays}). If given then the return is @code{#t} if @var{obj} is an -array and of that prototype. -@end deffn - -@deffn {Scheme Procedure} make-array initial-value bound @dots{} -Create and return an array that has as many dimensions as there are -@var{bound}s and fill it with @var{initial-value}. - -Each @var{bound} -may be a positive non-zero integer @var{N}, in which case the index for -that dimension can range from 0 through @var{N-1}; or an explicit index -range specifier in the form @code{(LOWER UPPER)}, where both @var{lower} -and @var{upper} are integers, possibly less than zero, and possibly the -same number (however, @var{lower} cannot be greater than @var{upper}). -See examples above. -@end deffn - -@c array-ref's type is `compiled-closure'. There's some weird stuff -@c going on in array.c, too. Let's call it a primitive. -twp - -@deffn {Scheme Procedure} array-ref array idx @dots{} -@deffnx {Scheme Procedure} uniform-vector-ref vec args -@deffnx {C Function} scm_uniform_vector_ref (vec, args) -Return the element at @code{(idx @dots{})} in @var{array}. - -@example -(define a (make-array 999 '(1 2) '(3 4))) -(array-ref a 2 4) @result{} 999 -@end example -@end deffn - -@deffn {Scheme Procedure} array-in-bounds? array idx @dots{} -@deffnx {C Function} scm_array_in_bounds_p (array, idxlist) -Return @code{#t} if the given index would be acceptable to -@code{array-ref}. - -@example -(define a (make-array #f '(1 2) '(3 4))) -(array-in-bounds? a 2 3) @result{} #f -(array-in-bounds? a 0 0) @result{} #f -@end example -@end deffn - -@c fixme: why do these sigs differ? -ttn 2001/07/19 01:14:12 -@deffn {Scheme Procedure} array-set! array obj idx @dots{} -@deffnx {Scheme Procedure} uniform-array-set1! array obj idxlist -@deffnx {C Function} scm_array_set_x (array, obj, idxlist) -Set the element at @code{(idx @dots{})} in @var{array} to @var{obj}. -The return value is unspecified. - -@example -(define a (make-array #f '(0 1) '(0 1))) -(array-set! a #t 1 1) -a @result{} #2((#f #f) (#f #t)) -@end example -@end deffn - -@deffn {Scheme Procedure} make-shared-array oldarray mapfunc bound @dots{} -@deffnx {C Function} scm_make_shared_array (oldarray, mapfunc, boundlist) -@code{make-shared-array} can be used to create shared subarrays of other -arrays. The @var{mapper} is a function that translates coordinates in -the new array into coordinates in the old array. A @var{mapper} must be -linear, and its range must stay within the bounds of the old array, but -it can be otherwise arbitrary. A simple example: - -@lisp -(define fred (make-array #f 8 8)) -(define freds-diagonal - (make-shared-array fred (lambda (i) (list i i)) 8)) -(array-set! freds-diagonal 'foo 3) -(array-ref fred 3 3) @result{} foo -(define freds-center - (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j))) 2 2)) -(array-ref freds-center 0 0) @result{} foo -@end lisp -@end deffn - -@deffn {Scheme Procedure} shared-array-increments array -@deffnx {C Function} scm_shared_array_increments (array) -For each dimension, return the distance between elements in the root vector. -@end deffn - -@deffn {Scheme Procedure} shared-array-offset array -@deffnx {C Function} scm_shared_array_offset (array) -Return the root vector index of the first element in the array. -@end deffn - -@deffn {Scheme Procedure} shared-array-root array -@deffnx {C Function} scm_shared_array_root (array) -Return the root vector of a shared array. -@end deffn - -@deffn {Scheme Procedure} transpose-array array dim1 @dots{} -@deffnx {C Function} scm_transpose_array (array, dimlist) -Return an array sharing contents with @var{array}, but with -dimensions arranged in a different order. There must be one -@var{dim} argument for each dimension of @var{array}. -@var{dim1}, @var{dim2}, @dots{} should be integers between 0 -and the rank of the array to be returned. Each integer in that -range must appear at least once in the argument list. - -The values of @var{dim1}, @var{dim2}, @dots{} correspond to -dimensions in the array to be returned, and their positions in the -argument list to dimensions of @var{array}. Several @var{dim}s -may have the same value, in which case the returned array will -have smaller rank than @var{array}. - -@lisp -(transpose-array '#2((a b) (c d)) 1 0) @result{} #2((a c) (b d)) -(transpose-array '#2((a b) (c d)) 0 0) @result{} #1(a d) -(transpose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 1 0) @result{} - #2((a 4) (b 5) (c 6)) -@end lisp -@end deffn - -@deffn {Scheme Procedure} enclose-array array dim1 @dots{} -@deffnx {C Function} scm_enclose_array (array, dimlist) -@var{dim1}, @var{dim2} @dots{} should be nonnegative integers less than -the rank of @var{array}. @code{enclose-array} returns an array -resembling an array of shared arrays. The dimensions of each shared -array are the same as the @var{dim}th dimensions of the original array, -the dimensions of the outer array are the same as those of the original -array that did not match a @var{dim}. - -An enclosed array is not a general Scheme array. Its elements may not -be set using @code{array-set!}. Two references to the same element of -an enclosed array will be @code{equal?} but will not in general be -@code{eq?}. The value returned by @code{array-prototype} when given an -enclosed array is unspecified. - -For example, - -@lisp -(enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1) -@result{} -#<enclosed-array (#1(a d) #1(b e) #1(c f)) (#1(1 4) #1(2 5) #1(3 6))> - -(enclose-array '#3(((a b c) (d e f)) ((1 2 3) (4 5 6))) 1 0) -@result{} -#<enclosed-array #2((a 1) (d 4)) #2((b 2) (e 5)) #2((c 3) (f 6))> -@end lisp -@end deffn - -@deffn {Scheme Procedure} array-shape array -@deffnx {Scheme Procedure} array-dimensions array -@deffnx {C Function} scm_array_dimensions (array) -Return a list of the bounds for each dimenson of @var{array}. - -@code{array-shape} gives @code{(@var{lower} @var{upper})} for each -dimension. @code{array-dimensions} instead returns just -@math{@var{upper}+1} for dimensions with a 0 lower bound. Both are -suitable as input to @code{make-array}. - -For example, - -@example -(define a (make-array 'foo '(-1 3) 5)) -(array-shape a) @result{} ((-1 3) (0 4)) -(array-dimensions a) @result{} ((-1 3) 5) -@end example -@end deffn - -@deffn {Scheme Procedure} array-rank obj -@deffnx {C Function} scm_array_rank (obj) -Return the number of dimensions of an array @var{obj}, or if @var{obj} -is not an array then return 0. -@end deffn - -@deffn {Scheme Procedure} array->list array -@deffnx {C Function} scm_array_to_list (array) -Return a list consisting of all the elements, in order, of -@var{array}. -@end deffn - -@c FIXME: Describe how the order affects the copying (it matters for -@c shared arrays with the same underlying root vector, presumably). -@c -@deffn {Scheme Procedure} array-copy! src dst -@deffnx {Scheme Procedure} array-copy-in-order! src dst -@deffnx {C Function} scm_array_copy_x (src, dst) -Copy every element from vector or array @var{src} to the corresponding -element of @var{dst}. @var{dst} must have the same rank as @var{src}, -and be at least as large in each dimension. The return value is -unspecified. -@end deffn - -@deffn {Scheme Procedure} array-fill! array fill -@deffnx {C Function} scm_array_fill_x (array, fill) -Store @var{fill} in every element of @var{array}. The value returned -is unspecified. -@end deffn - -@c begin (texi-doc-string "guile" "array-equal?") -@deffn {Scheme Procedure} array-equal? array1 array2 @dots{} -Return @code{#t} if all arguments are arrays with the same shape, the -same type, and have corresponding elements which are either -@code{equal?} or @code{array-equal?}. This function differs from -@code{equal?} in that a one dimensional shared array may be -@var{array-equal?} but not @var{equal?} to a vector or uniform vector. -@end deffn - -@deffn {Scheme Procedure} array-contents array [strict] -@deffnx {C Function} scm_array_contents (array, strict) -If @var{array} may be @dfn{unrolled} into a one dimensional shared array -without changing their order (last subscript changing fastest), then -@code{array-contents} returns that shared array, otherwise it returns -@code{#f}. All arrays made by @code{make-array} and -@code{make-uniform-array} may be unrolled, some arrays made by -@code{make-shared-array} may not be. - -If the optional argument @var{strict} is provided, a shared array will -be returned only if its elements are stored internally contiguous in -memory. -@end deffn - -@node Array Mapping -@subsection Array Mapping - -@c FIXME: array-map! accepts no source arrays at all, and in that -@c case makes calls "(proc)". Is that meant to be a documented -@c feature? -@c -@c FIXME: array-for-each doesn't say what happens if the sources have -@c different index ranges. The code currently iterates over the -@c indices of the first and expects the others to cover those. That -@c at least vaguely matches array-map!, but is is meant to be a -@c documented feature? - -@deffn {Scheme Procedure} array-map! dst proc src1 @dots{} srcN -@deffnx {Scheme Procedure} array-map-in-order! dst proc src1 @dots{} srcN -@deffnx {C Function} scm_array_map_x (dst, proc, srclist) -Set each element of the @var{dst} array to values obtained from calls -to @var{proc}. The value returned is unspecified. - -Each call is @code{(@var{proc} @var{elem1} @dots{} @var{elemN})}, -where each @var{elem} is from the corresponding @var{src} array, at -the @var{dst} index. @code{array-map-in-order!} makes the calls in -row-major order, @code{array-map!} makes them in an unspecified order. - -The @var{src} arrays must have the same number of dimensions as -@var{dst}, and must have a range for each dimension which covers the -range in @var{dst}. This ensures all @var{dst} indices are valid in -each @var{src}. -@end deffn - -@deffn {Scheme Procedure} array-for-each proc src1 @dots{} srcN -@deffnx {C Function} scm_array_for_each (proc, src1, srclist) -Apply @var{proc} to each tuple of elements of @var{src1} @dots{} -@var{srcN}, in row-major order. The value returned is unspecified. -@end deffn - -@deffn {Scheme Procedure} array-index-map! dst proc -@deffnx {C Function} scm_array_index_map_x (dst, proc) -Set each element of the @var{dst} array to values returned by calls to -@var{proc}. The value returned is unspecified. - -Each call is @code{(@var{proc} @var{i1} @dots{} @var{iN})}, where -@var{i1}@dots{}@var{iN} is the destination index, one parameter for -each dimension. The order in which the calls are made is unspecified. - -For example, to create a @m{4\times4, 4x4} matrix representing a -cyclic group, - -@tex -\advance\leftskip by 2\lispnarrowing { -$\left(\matrix{% -0 & 1 & 2 & 3 \cr -1 & 2 & 3 & 0 \cr -2 & 3 & 0 & 1 \cr -3 & 0 & 1 & 2 \cr -}\right)$} \par -@end tex -@ifnottex -@example - / 0 1 2 3 \ - | 1 2 3 0 | - | 2 3 0 1 | - \ 3 0 1 2 / -@end example -@end ifnottex - -@example -(define a (make-array #f 4 4)) -(array-index-map! a (lambda (i j) - (modulo (+ i j) 4))) -@end example -@end deffn - -@node Uniform Arrays -@subsection Uniform Arrays -@tpindex Uniform Arrays - -@noindent -@dfn{Uniform arrays} have elements all of the -same type and occupy less storage than conventional -arrays. Uniform arrays with a single zero-based dimension -are also known as @dfn{uniform vectors}. The procedures in -this section can also be used on conventional arrays, vectors, -bit-vectors and strings. - -@noindent -When creating a uniform array, the type of data to be stored -is indicated with a @var{prototype} argument. The following table -lists the types available and example prototypes: - -@example -prototype type printing character - -#t boolean (bit-vector) b -#\a char (string) a -#\nul byte (integer) y -'s short (integer) h -1 unsigned long (integer) u --1 signed long (integer) e -'l signed long long (integer) l -1.0 float (single precision) s -1/3 double (double precision float) i -0+i complex (double precision) c -() conventional vector -@end example - -Note that with the introduction of exact fractions in Guile 1.8, -@samp{1/3} here is now a fraction, where previously such an expression -was a double @samp{0.333@dots{}}. For most normal usages this should -be source code compatible. - -Unshared uniform arrays of characters with a single zero-based dimension -are identical to strings: - -@example -(make-uniform-array #\a 3) @result{} -"aaa" -@end example - -@noindent -Unshared uniform arrays of booleans with a single zero-based dimension -are identical to @ref{Bit Vectors, bit-vectors}. - -@example -(make-uniform-array #t 3) @result{} -#*111 -@end example - -@noindent -Other uniform vectors are written in a form similar to that of vectors, -except that a single character from the above table is put between -@code{#} and @code{(}. For example, a uniform vector of signed -long integers is displayed in the form @code{'#e(3 5 9)}. - -@deffn {Scheme Procedure} make-uniform-array prototype bound1 bound2 @dots{} -Create and return a uniform array of type corresponding to -@var{prototype} that has as many dimensions as there are @var{bound}s -and fill it with @var{prototype}. -@end deffn - -@deffn {Scheme Procedure} array-prototype ra -@deffnx {C Function} scm_array_prototype (ra) -Return an object that would produce an array of the same type -as @var{array}, if used as the @var{prototype} for -@code{make-uniform-array}. -@end deffn - -@deffn {Scheme Procedure} list->uniform-array ndim prot lst -@deffnx {Scheme Procedure} list->uniform-vector prot lst -@deffnx {C Function} scm_list_to_uniform_array (ndim, prot, lst) -Return a uniform array of the type indicated by prototype -@var{prot} with elements the same as those of @var{lst}. -Elements must be of the appropriate type, no coercions are -done. -@end deffn - -@deffn {Scheme Procedure} uniform-vector-fill! uve fill -Store @var{fill} in every element of @var{uve}. The value returned is -unspecified. -@end deffn - -@deffn {Scheme Procedure} uniform-vector-length v -@deffnx {C Function} scm_uniform_vector_length (v) -Return the number of elements in @var{uve}. -@end deffn - -@deffn {Scheme Procedure} dimensions->uniform-array dims prot [fill] -@deffnx {Scheme Procedure} make-uniform-vector length prototype [fill] -@deffnx {C Function} scm_dimensions_to_uniform_array (dims, prot, fill) -Create and return a uniform array or vector of type -corresponding to @var{prototype} with dimensions @var{dims} or -length @var{length}. If @var{fill} is supplied, it's used to -fill the array, otherwise @var{prototype} is used. -@end deffn - -@c Another compiled-closure. -twp - -@deffn {Scheme Procedure} uniform-array-read! ra [port_or_fd [start [end]]] -@deffnx {Scheme Procedure} uniform-vector-read! uve [port-or-fdes] [start] [end] -@deffnx {C Function} scm_uniform_array_read_x (ra, port_or_fd, start, end) -Attempt to read all elements of @var{ura}, in lexicographic order, as -binary objects from @var{port-or-fdes}. -If an end of file is encountered, -the objects up to that point are put into @var{ura} -(starting at the beginning) and the remainder of the array is -unchanged. - -The optional arguments @var{start} and @var{end} allow -a specified region of a vector (or linearized array) to be read, -leaving the remainder of the vector unchanged. - -@code{uniform-array-read!} returns the number of objects read. -@var{port-or-fdes} may be omitted, in which case it defaults to the value -returned by @code{(current-input-port)}. -@end deffn - -@deffn {Scheme Procedure} uniform-array-write v [port_or_fd [start [end]]] -@deffnx {Scheme Procedure} uniform-vector-write uve [port-or-fdes] [start] [end] -@deffnx {C Function} scm_uniform_array_write (v, port_or_fd, start, end) -Writes all elements of @var{ura} as binary objects to -@var{port-or-fdes}. - -The optional arguments @var{start} -and @var{end} allow -a specified region of a vector (or linearized array) to be written. - -The number of objects actually written is returned. -@var{port-or-fdes} may be -omitted, in which case it defaults to the value returned by -@code{(current-output-port)}. -@end deffn - -@node Bit Vectors -@subsection Bit Vectors - -@noindent -Bit vectors are a specific type of uniform array: an array of booleans -with a single zero-based index. - -@noindent -They are displayed as a sequence of @code{0}s and -@code{1}s prefixed by @code{#*}, e.g., - -@example -(make-uniform-vector 8 #t #f) @result{} -#*00000000 -@end example - -@deffn {Scheme Procedure} bit-count bool bitvector -@deffnx {C Function} scm_bit_count (bool, bitvector) -Return a count of how many entries in @var{bitvector} are equal to -@var{bool}. For example, - -@example -(bit-count #f #*000111000) @result{} 6 -@end example -@end deffn - -@deffn {Scheme Procedure} bit-position bool bitvector start -@deffnx {C Function} scm_bit_position (bool, bitvector, start) -Return the index of the first occurrance of @var{bool} in -@var{bitvector}, starting from @var{start}. If there is no @var{bool} -entry between @var{start} and the end of @var{bitvector}, then return -@code{#f}. For example, - -@example -(bit-position #t #*000101 0) @result{} 3 -(bit-position #f #*0001111 3) @result{} #f -@end example -@end deffn - -@deffn {Scheme Procedure} bit-invert! bitvector -@deffnx {C Function} scm_bit_invert_x (bitvector) -Modify @var{bitvector} by replacing each element with its negation. -@end deffn - -@deffn {Scheme Procedure} bit-set*! bitvector uvec bool -@deffnx {C Function} scm_bit_set_star_x (bitvector, uvec, bool) -Set entries of @var{bitvector} to @var{bool}, with @var{uvec} -selecting the entries to change. The return value is unspecified. - -If @var{uvec} is a bit vector, then those entries where it has -@code{#t} are the ones in @var{bitvector} which are set to @var{bool}. -@var{uvec} and @var{bitvector} must be the same length. When -@var{bool} is @code{#t} it's like @var{uvec} is OR'ed into -@var{bitvector}. Or when @var{bool} is @code{#f} it can be seen as an -ANDNOT. - -@example -(define bv #*01000010) -(bit-set*! bv #*10010001 #t) -bv -@result{} #*11010011 -@end example - -If @var{uvec} is a uniform vector of unsigned long integers, then -they're indexes into @var{bitvector} which are set to @var{bool}. - -@example -(define bv #*01000010) -(bit-set*! bv #u(5 2 7) #t) -bv -@result{} #*01100111 -@end example -@end deffn - -@deffn {Scheme Procedure} bit-count* bitvector uvec bool -@deffnx {C Function} scm_bit_count_star (bitvector, uvec, bool) -Return a count of how many entries in @var{bitvector} are equal to -@var{bool}, with @var{uvec} selecting the entries to consider. - -@var{uvec} is interpreted in the same way as for @code{bit-set*!} -above. Namely, if @var{uvec} is a bit vector then entries which have -@code{#t} there are considered in @var{bitvector}. Or if @var{uvec} -is a uniform vector of unsigned long integers then it's the indexes in -@var{bitvector} to consider. - -For example, - -@example -(bit-count* #*01110111 #*11001101 #t) @result{} 3 -(bit-count* #*01110111 #u(7 0 4) #f) @result{} 2 -@end example -@end deffn - - -@node Association Lists and Hash Tables -@section Association Lists and Hash Tables - -This chapter discusses dictionary objects: data structures that are -useful for organizing and indexing large bodies of information. - -@menu -* Dictionary Types:: About dictionary types; what they're good for. -* Association Lists:: List-based dictionaries. -* Hash Tables:: Table-based dictionaries. -@end menu - -@node Dictionary Types -@subsection Dictionary Types - -A @dfn{dictionary} object is a data structure used to index -information in a user-defined way. In standard Scheme, the main -aggregate data types are lists and vectors. Lists are not really -indexed at all, and vectors are indexed only by number -(e.g. @code{(vector-ref foo 5)}). Often you will find it useful -to index your data on some other type; for example, in a library -catalog you might want to look up a book by the name of its -author. Dictionaries are used to help you organize information in -such a way. - -An @dfn{association list} (or @dfn{alist} for short) is a list of -key-value pairs. Each pair represents a single quantity or -object; the @code{car} of the pair is a key which is used to -identify the object, and the @code{cdr} is the object's value. - -A @dfn{hash table} also permits you to index objects with -arbitrary keys, but in a way that makes looking up any one object -extremely fast. A well-designed hash system makes hash table -lookups almost as fast as conventional array or vector references. - -Alists are popular among Lisp programmers because they use only -the language's primitive operations (lists, @dfn{car}, @dfn{cdr} -and the equality primitives). No changes to the language core are -necessary. Therefore, with Scheme's built-in list manipulation -facilities, it is very convenient to handle data stored in an -association list. Also, alists are highly portable and can be -easily implemented on even the most minimal Lisp systems. - -However, alists are inefficient, especially for storing large -quantities of data. Because we want Guile to be useful for large -software systems as well as small ones, Guile provides a rich set -of tools for using either association lists or hash tables. - -@node Association Lists -@subsection Association Lists -@tpindex Association Lists -@tpindex Alist - -@cindex Association List -@cindex Alist -@cindex Database - -An association list is a conventional data structure that is often used -to implement simple key-value databases. It consists of a list of -entries in which each entry is a pair. The @dfn{key} of each entry is -the @code{car} of the pair and the @dfn{value} of each entry is the -@code{cdr}. - -@example -ASSOCIATION LIST ::= '( (KEY1 . VALUE1) - (KEY2 . VALUE2) - (KEY3 . VALUE3) - @dots{} - ) -@end example - -@noindent -Association lists are also known, for short, as @dfn{alists}. - -The structure of an association list is just one example of the infinite -number of possible structures that can be built using pairs and lists. -As such, the keys and values in an association list can be manipulated -using the general list structure procedures @code{cons}, @code{car}, -@code{cdr}, @code{set-car!}, @code{set-cdr!} and so on. However, -because association lists are so useful, Guile also provides specific -procedures for manipulating them. - -@menu -* Alist Key Equality:: -* Adding or Setting Alist Entries:: -* Retrieving Alist Entries:: -* Removing Alist Entries:: -* Sloppy Alist Functions:: -* Alist Example:: -@end menu - -@node Alist Key Equality -@subsubsection Alist Key Equality - -All of Guile's dedicated association list procedures, apart from -@code{acons}, come in three flavours, depending on the level of equality -that is required to decide whether an existing key in the association -list is the same as the key that the procedure call uses to identify the -required entry. - -@itemize @bullet -@item -Procedures with @dfn{assq} in their name use @code{eq?} to determine key -equality. - -@item -Procedures with @dfn{assv} in their name use @code{eqv?} to determine -key equality. - -@item -Procedures with @dfn{assoc} in their name use @code{equal?} to -determine key equality. -@end itemize - -@code{acons} is an exception because it is used to build association -lists which do not require their entries' keys to be unique. - -@node Adding or Setting Alist Entries -@subsubsection Adding or Setting Alist Entries - -@code{acons} adds a new entry to an association list and returns the -combined association list. The combined alist is formed by consing the -new entry onto the head of the alist specified in the @code{acons} -procedure call. So the specified alist is not modified, but its -contents become shared with the tail of the combined alist that -@code{acons} returns. - -In the most common usage of @code{acons}, a variable holding the -original association list is updated with the combined alist: - -@example -(set! address-list (acons name address address-list)) -@end example - -In such cases, it doesn't matter that the old and new values of -@code{address-list} share some of their contents, since the old value is -usually no longer independently accessible. - -Note that @code{acons} adds the specified new entry regardless of -whether the alist may already contain entries with keys that are, in -some sense, the same as that of the new entry. Thus @code{acons} is -ideal for building alists where there is no concept of key uniqueness. - -@example -(set! task-list (acons 3 "pay gas bill" '())) -task-list -@result{} -((3 . "pay gas bill")) - -(set! task-list (acons 3 "tidy bedroom" task-list)) -task-list -@result{} -((3 . "tidy bedroom") (3 . "pay gas bill")) -@end example - -@code{assq-set!}, @code{assv-set!} and @code{assoc-set!} are used to add -or replace an entry in an association list where there @emph{is} a -concept of key uniqueness. If the specified association list already -contains an entry whose key is the same as that specified in the -procedure call, the existing entry is replaced by the new one. -Otherwise, the new entry is consed onto the head of the old association -list to create the combined alist. In all cases, these procedures -return the combined alist. - -@code{assq-set!} and friends @emph{may} destructively modify the -structure of the old association list in such a way that an existing -variable is correctly updated without having to @code{set!} it to the -value returned: - -@example -address-list -@result{} -(("mary" . "34 Elm Road") ("james" . "16 Bow Street")) - -(assoc-set! address-list "james" "1a London Road") -@result{} -(("mary" . "34 Elm Road") ("james" . "1a London Road")) - -address-list -@result{} -(("mary" . "34 Elm Road") ("james" . "1a London Road")) -@end example - -Or they may not: - -@example -(assoc-set! address-list "bob" "11 Newington Avenue") -@result{} -(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road") - ("james" . "1a London Road")) - -address-list -@result{} -(("mary" . "34 Elm Road") ("james" . "1a London Road")) -@end example - -The only safe way to update an association list variable when adding or -replacing an entry like this is to @code{set!} the variable to the -returned value: - -@example -(set! address-list - (assoc-set! address-list "bob" "11 Newington Avenue")) -address-list -@result{} -(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road") - ("james" . "1a London Road")) -@end example - -Because of this slight inconvenience, you may find it more convenient to -use hash tables to store dictionary data. If your application will not -be modifying the contents of an alist very often, this may not make much -difference to you. - -If you need to keep the old value of an association list in a form -independent from the list that results from modification by -@code{acons}, @code{assq-set!}, @code{assv-set!} or @code{assoc-set!}, -use @code{list-copy} to copy the old association list before modifying -it. - -@deffn {Scheme Procedure} acons key value alist -@deffnx {C Function} scm_acons (key, value, alist) -Add a new key-value pair to @var{alist}. A new pair is -created whose car is @var{key} and whose cdr is @var{value}, and the -pair is consed onto @var{alist}, and the new list is returned. This -function is @emph{not} destructive; @var{alist} is not modified. -@end deffn - -@deffn {Scheme Procedure} assq-set! alist key val -@deffnx {Scheme Procedure} assv-set! alist key value -@deffnx {Scheme Procedure} assoc-set! alist key value -@deffnx {C Function} scm_assq_set_x (alist, key, val) -@deffnx {C Function} scm_assv_set_x (alist, key, val) -@deffnx {C Function} scm_assoc_set_x (alist, key, val) -Reassociate @var{key} in @var{alist} with @var{value}: find any existing -@var{alist} entry for @var{key} and associate it with the new -@var{value}. If @var{alist} does not contain an entry for @var{key}, -add a new one. Return the (possibly new) alist. - -These functions do not attempt to verify the structure of @var{alist}, -and so may cause unusual results if passed an object that is not an -association list. -@end deffn - -@node Retrieving Alist Entries -@subsubsection Retrieving Alist Entries -@rnindex assq -@rnindex assv -@rnindex assoc - -@code{assq}, @code{assv} and @code{assoc} take an alist and a key as -arguments and return the entry for that key if an entry exists, or -@code{#f} if there is no entry for that key. Note that, in the cases -where an entry exists, these procedures return the complete entry, that -is @code{(KEY . VALUE)}, not just the value. - -@deffn {Scheme Procedure} assq key alist -@deffnx {Scheme Procedure} assv key alist -@deffnx {Scheme Procedure} assoc key alist -@deffnx {C Function} scm_assq (key, alist) -@deffnx {C Function} scm_assv (key, alist) -@deffnx {C Function} scm_assoc (key, alist) -Fetch the entry in @var{alist} that is associated with @var{key}. To -decide whether the argument @var{key} matches a particular entry in -@var{alist}, @code{assq} compares keys with @code{eq?}, @code{assv} -uses @code{eqv?} and @code{assoc} uses @code{equal?}. If @var{key} -cannot be found in @var{alist} (according to whichever equality -predicate is in use), then return @code{#f}. These functions -return the entire alist entry found (i.e. both the key and the value). -@end deffn - -@code{assq-ref}, @code{assv-ref} and @code{assoc-ref}, on the other -hand, take an alist and a key and return @emph{just the value} for that -key, if an entry exists. If there is no entry for the specified key, -these procedures return @code{#f}. - -This creates an ambiguity: if the return value is @code{#f}, it means -either that there is no entry with the specified key, or that there -@emph{is} an entry for the specified key, with value @code{#f}. -Consequently, @code{assq-ref} and friends should only be used where it -is known that an entry exists, or where the ambiguity doesn't matter -for some other reason. - -@deffn {Scheme Procedure} assq-ref alist key -@deffnx {Scheme Procedure} assv-ref alist key -@deffnx {Scheme Procedure} assoc-ref alist key -@deffnx {C Function} scm_assq_ref (alist, key) -@deffnx {C Function} scm_assv_ref (alist, key) -@deffnx {C Function} scm_assoc_ref (alist, key) -Like @code{assq}, @code{assv} and @code{assoc}, except that only the -value associated with @var{key} in @var{alist} is returned. These -functions are equivalent to - -@lisp -(let ((ent (@var{associator} @var{key} @var{alist}))) - (and ent (cdr ent))) -@end lisp - -where @var{associator} is one of @code{assq}, @code{assv} or @code{assoc}. -@end deffn - -@node Removing Alist Entries -@subsubsection Removing Alist Entries - -To remove the element from an association list whose key matches a -specified key, use @code{assq-remove!}, @code{assv-remove!} or -@code{assoc-remove!} (depending, as usual, on the level of equality -required between the key that you specify and the keys in the -association list). - -As with @code{assq-set!} and friends, the specified alist may or may not -be modified destructively, and the only safe way to update a variable -containing the alist is to @code{set!} it to the value that -@code{assq-remove!} and friends return. - -@example -address-list -@result{} -(("bob" . "11 Newington Avenue") ("mary" . "34 Elm Road") - ("james" . "1a London Road")) - -(set! address-list (assoc-remove! address-list "mary")) -address-list -@result{} -(("bob" . "11 Newington Avenue") ("james" . "1a London Road")) -@end example - -Note that, when @code{assq/v/oc-remove!} is used to modify an -association list that has been constructed only using the corresponding -@code{assq/v/oc-set!}, there can be at most one matching entry in the -alist, so the question of multiple entries being removed in one go does -not arise. If @code{assq/v/oc-remove!} is applied to an association -list that has been constructed using @code{acons}, or an -@code{assq/v/oc-set!} with a different level of equality, or any mixture -of these, it removes only the first matching entry from the alist, even -if the alist might contain further matching entries. For example: - -@example -(define address-list '()) -(set! address-list (assq-set! address-list "mary" "11 Elm Street")) -(set! address-list (assq-set! address-list "mary" "57 Pine Drive")) -address-list -@result{} -(("mary" . "57 Pine Drive") ("mary" . "11 Elm Street")) - -(set! address-list (assoc-remove! address-list "mary")) -address-list -@result{} -(("mary" . "11 Elm Street")) -@end example - -In this example, the two instances of the string "mary" are not the same -when compared using @code{eq?}, so the two @code{assq-set!} calls add -two distinct entries to @code{address-list}. When compared using -@code{equal?}, both "mary"s in @code{address-list} are the same as the -"mary" in the @code{assoc-remove!} call, but @code{assoc-remove!} stops -after removing the first matching entry that it finds, and so one of the -"mary" entries is left in place. - -@deffn {Scheme Procedure} assq-remove! alist key -@deffnx {Scheme Procedure} assv-remove! alist key -@deffnx {Scheme Procedure} assoc-remove! alist key -@deffnx {C Function} scm_assq_remove_x (alist, key) -@deffnx {C Function} scm_assv_remove_x (alist, key) -@deffnx {C Function} scm_assoc_remove_x (alist, key) -Delete the first entry in @var{alist} associated with @var{key}, and return -the resulting alist. -@end deffn - -@node Sloppy Alist Functions -@subsubsection Sloppy Alist Functions - -@code{sloppy-assq}, @code{sloppy-assv} and @code{sloppy-assoc} behave -like the corresponding non-@code{sloppy-} procedures, except that they -return @code{#f} when the specified association list is not well-formed, -where the non-@code{sloppy-} versions would signal an error. - -Specifically, there are two conditions for which the non-@code{sloppy-} -procedures signal an error, which the @code{sloppy-} procedures handle -instead by returning @code{#f}. Firstly, if the specified alist as a -whole is not a proper list: - -@example -(assoc "mary" '((1 . 2) ("key" . "door") . "open sesame")) -@result{} -ERROR: In procedure assoc in expression (assoc "mary" (quote #)): -ERROR: Wrong type argument in position 2 (expecting association list): ((1 . 2) ("key" . "door") . "open sesame") - -(sloppy-assoc "mary" '((1 . 2) ("key" . "door") . "open sesame")) -@result{} -#f -@end example - -@noindent -Secondly, if one of the entries in the specified alist is not a pair: - -@example -(assoc 2 '((1 . 1) 2 (3 . 9))) -@result{} -ERROR: In procedure assoc in expression (assoc 2 (quote #)): -ERROR: Wrong type argument in position 2 (expecting association list): ((1 . 1) 2 (3 . 9)) - -(sloppy-assoc 2 '((1 . 1) 2 (3 . 9))) -@result{} -#f -@end example - -Unless you are explicitly working with badly formed association lists, -it is much safer to use the non-@code{sloppy-} procedures, because they -help to highlight coding and data errors that the @code{sloppy-} -versions would silently cover up. - -@deffn {Scheme Procedure} sloppy-assq key alist -@deffnx {C Function} scm_sloppy_assq (key, alist) -Behaves like @code{assq} but does not do any error checking. -Recommended only for use in Guile internals. -@end deffn - -@deffn {Scheme Procedure} sloppy-assv key alist -@deffnx {C Function} scm_sloppy_assv (key, alist) -Behaves like @code{assv} but does not do any error checking. -Recommended only for use in Guile internals. -@end deffn - -@deffn {Scheme Procedure} sloppy-assoc key alist -@deffnx {C Function} scm_sloppy_assoc (key, alist) -Behaves like @code{assoc} but does not do any error checking. -Recommended only for use in Guile internals. -@end deffn - -@node Alist Example -@subsubsection Alist Example - -Here is a longer example of how alists may be used in practice. - -@lisp -(define capitals '(("New York" . "Albany") - ("Oregon" . "Salem") - ("Florida" . "Miami"))) - -;; What's the capital of Oregon? -(assoc "Oregon" capitals) @result{} ("Oregon" . "Salem") -(assoc-ref capitals "Oregon") @result{} "Salem" - -;; We left out South Dakota. -(set! capitals - (assoc-set! capitals "South Dakota" "Pierre")) -capitals -@result{} (("South Dakota" . "Pierre") - ("New York" . "Albany") - ("Oregon" . "Salem") - ("Florida" . "Miami")) - -;; And we got Florida wrong. -(set! capitals - (assoc-set! capitals "Florida" "Tallahassee")) -capitals -@result{} (("South Dakota" . "Pierre") - ("New York" . "Albany") - ("Oregon" . "Salem") - ("Florida" . "Tallahassee")) - -;; After Oregon secedes, we can remove it. -(set! capitals - (assoc-remove! capitals "Oregon")) -capitals -@result{} (("South Dakota" . "Pierre") - ("New York" . "Albany") - ("Florida" . "Tallahassee")) -@end lisp - -@node Hash Tables -@subsection Hash Tables -@tpindex Hash Tables - -@c FIXME::martin: Review me! - -Hash tables are dictionaries which offer similar functionality as -association lists: They provide a mapping from keys to values. The -difference is that association lists need time linear in the size of -elements when searching for entries, whereas hash tables can normally -search in constant time. The drawback is that hash tables require a -little bit more memory, and that you can not use the normal list -procedures (@pxref{Lists}) for working with them. - -@menu -* Hash Table Examples:: Demonstration of hash table usage. -* Hash Table Reference:: Hash table procedure descriptions. -@end menu - - -@node Hash Table Examples -@subsubsection Hash Table Examples - -@c FIXME::martin: Review me! - -For demonstration purposes, this section gives a few usage examples of -some hash table procedures, together with some explanation what they do. - -First we start by creating a new hash table with 31 slots, and -populate it with two key/value pairs. - -@lisp -(define h (make-hash-table 31)) - -(hashq-create-handle! h 'foo "bar") -@result{} -(foo . "bar") - -(hashq-create-handle! h 'braz "zonk") -@result{} -(braz . "zonk") - -(hashq-create-handle! h 'frob #f) -@result{} -(frob . #f) -@end lisp - -You can get the value for a given key with the procedure -@code{hashq-ref}, but the problem with this procedure is that you -cannot reliably determine whether a key does exists in the table. The -reason is that the procedure returns @code{#f} if the key is not in -the table, but it will return the same value if the key is in the -table and just happens to have the value @code{#f}, as you can see in -the following examples. - -@lisp -(hashq-ref h 'foo) -@result{} -"bar" - -(hashq-ref h 'frob) -@result{} -#f - -(hashq-ref h 'not-there) -@result{} -#f -@end lisp - -Better is to use the procedure @code{hashq-get-handle}, which makes a -distinction between the two cases. Just like @code{assq}, this -procedure returns a key/value-pair on success, and @code{#f} if the -key is not found. - -@lisp -(hashq-get-handle h 'foo) -@result{} -(foo . "bar") - -(hashq-get-handle h 'not-there) -@result{} -#f -@end lisp - -There is no procedure for calculating the number of key/value-pairs in -a hash table, but @code{hash-fold} can be used for doing exactly that. - -@lisp -(hash-fold (lambda (key value seed) (+ 1 seed)) 0 h) -@result{} -3 -@end lisp - -@node Hash Table Reference -@subsubsection Hash Table Reference - -@c FIXME: Describe in broad terms what happens for resizing, and what -@c the initial size means for this. - -Like the association list functions, the hash table functions come in -several varieties, according to the equality test used for the keys. -Plain @code{hash-} functions use @code{equal?}, @code{hashq-} -functions use @code{eq?}, @code{hashv-} functions use @code{eqv?}, and -the @code{hashx-} functions use an application supplied test. - -A single @code{make-hash-table} creates a hash table suitable for use -with any set of functions, but it's imperative that just one set is -then used consistently, or results will be unpredictable. - -@sp 1 -Hash tables are implemented as a vector indexed by a hash value formed -from the key, with an association list of key/value pairs for each -bucket in case distinct keys hash together. Direct access to the -pairs in those lists is provided by the @code{-handle-} functions. - -When the number of table entries goes above a threshold the vector is -increased and the entries rehashed, to prevent the bucket lists -becoming too long and slowing down accesses. When the number of -entries goes below a threshold the vector is decreased to save space. - -@sp 1 -For the @code{hashx-} ``extended'' routines, an application supplies a -@var{hash} function producing an integer index like @code{hashq} etc -below, and an @var{assoc} alist search function like @code{assq} etc -(@pxref{Retrieving Alist Entries}). Here's an example of such -functions implementing case-insensitive hashing of string keys, - -@example -(use-modules (srfi srfi-1) - (srfi srfi-13)) - -(define (my-hash str size) - (remainder (string-hash-ci str) size)) -(define (my-assoc str alist) - (find (lambda (pair) (string-ci=? str (car pair))) alist)) - -(define my-table (make-hash-table)) -(hashx-set! my-hash my-assoc my-table "foo" 123) - -(hashx-ref my-hash my-assoc my-table "FOO") -@result{} 123 -@end example - -In a @code{hashx-} @var{hash} function the aim is to spread keys -across the vector, so bucket lists don't become long. But the actual -values are arbitrary as long as they're in the range 0 to -@math{@var{size}-1}. Helpful functions for forming a hash value, in -addition to @code{hashq} etc below, include @code{symbol-hash} -(@pxref{Symbol Keys}), @code{string-hash} and @code{string-hash-ci} -(@pxref{SRFI-13 Comparison}), and @code{char-set-hash} (@pxref{SRFI-14 -Predicates/Comparison}). - -Note that currently, unfortunately, there's no @code{hashx-remove!} -function, which rather limits the usefulness of the @code{hashx-} -routines. - -@sp 1 -@deffn {Scheme Procedure} make-hash-table [size] -Create a new hash table, with an optional minimum vector @var{size}. - -When @var{size} is given, the table vector will still grow and shrink -automatically, as described above, but with @var{size} as a minimum. -If an application knows roughly how many entries the table will hold -then it can use @var{size} to avoid rehashing when initial entries are -added. -@end deffn - -@deffn {Scheme Procedure} hash-ref table key [dflt] -@deffnx {Scheme Procedure} hashq-ref table key [dflt] -@deffnx {Scheme Procedure} hashv-ref table key [dflt] -@deffnx {Scheme Procedure} hashx-ref hash assoc table key [dflt] -@deffnx {C Function} scm_hash_ref (table, key, dflt) -@deffnx {C Function} scm_hashq_ref (table, key, dflt) -@deffnx {C Function} scm_hashv_ref (table, key, dflt) -@deffnx {C Function} scm_hashx_ref (hash, assoc, table, key, dflt) -Lookup @var{key} in the given hash @var{table}, and return the -associated value. If @var{key} is not found, return @var{dflt}, or -@code{#f} if @var{dflt} is not given. -@end deffn - -@deffn {Scheme Procedure} hash-set! table key val -@deffnx {Scheme Procedure} hashq-set! table key val -@deffnx {Scheme Procedure} hashv-set! table key val -@deffnx {Scheme Procedure} hashx-set! hash assoc table key val -@deffnx {C Function} scm_hash_set_x (table, key, val) -@deffnx {C Function} scm_hashq_set_x (table, key, val) -@deffnx {C Function} scm_hashv_set_x (table, key, val) -@deffnx {C Function} scm_hashx_set_x (hash, assoc, table, key, val) -Associate @var{val} with @var{key} in the given hash @var{table}. If -@var{key} is already present then it's associated value is changed. -If it's not present then a new entry is created. -@end deffn - -@deffn {Scheme Procedure} hash-remove! table key -@deffnx {Scheme Procedure} hashq-remove! table key -@deffnx {Scheme Procedure} hashv-remove! table key -@deffnx {C Function} scm_hash_remove_x (table, key) -@deffnx {C Function} scm_hashq_remove_x (table, key) -@deffnx {C Function} scm_hashv_remove_x (table, key) -Remove any association for @var{key} in the given hash @var{table}. -If @var{key} is not in @var{table} then nothing is done. -@end deffn - -@deffn {Scheme Procedure} hash key size -@deffnx {Scheme Procedure} hashq key size -@deffnx {Scheme Procedure} hashv key size -@deffnx {C Function} scm_hash (key, size) -@deffnx {C Function} scm_hashq (key, size) -@deffnx {C Function} scm_hashv (key, size) -Return a hash value for @var{key}. This is a number in the range -@math{0} to @math{@var{size}-1}, which is suitable for use in a hash -table of the given @var{size}. - -Note that @code{hashq} and @code{hashv} may use internal addresses of -objects, so if an object is garbage collected and re-created it can -have a different hash value, even when the two are notionally -@code{eq?}. For instance with symbols, - -@example -(hashq 'something 123) @result{} 19 -(gc) -(hashq 'something 123) @result{} 62 -@end example - -In normal use this is not a problem, since an object entered into a -hash table won't be garbage collected until removed. It's only if -hashing calculations are somehow separated from normal references that -its lifetime needs to be considered. -@end deffn - -@deffn {Scheme Procedure} hash-get-handle table key -@deffnx {Scheme Procedure} hashq-get-handle table key -@deffnx {Scheme Procedure} hashv-get-handle table key -@deffnx {Scheme Procedure} hashx-get-handle hash assoc table key -@deffnx {C Function} scm_hash_get_handle (table, key) -@deffnx {C Function} scm_hashq_get_handle (table, key) -@deffnx {C Function} scm_hashv_get_handle (table, key) -@deffnx {C Function} scm_hashx_get_handle (hash, assoc, table, key) -Return the @code{(@var{key} . @var{value})} pair for @var{key} in the -given hash @var{table}, or @code{#f} if @var{key} is not in -@var{table}. -@end deffn - -@deffn {Scheme Procedure} hash-create-handle! table key init -@deffnx {Scheme Procedure} hashq-create-handle! table key init -@deffnx {Scheme Procedure} hashv-create-handle! table key init -@deffnx {Scheme Procedure} hashx-create-handle! hash assoc table key init -@deffnx {C Function} scm_hash_create_handle_x (table, key, init) -@deffnx {C Function} scm_hashq_create_handle_x (table, key, init) -@deffnx {C Function} scm_hashv_create_handle_x (table, key, init) -@deffnx {C Function} scm_hashx_create_handle_x (hash, assoc, table, key, init) -Return the @code{(@var{key} . @var{value})} pair for @var{key} in the -given hash @var{table}. If @var{key} is not in @var{table} then -create an entry for it with @var{init} as the value, and return that -pair. -@end deffn - -@deffn {Scheme Procedure} hash-map->list proc table -@deffnx {Scheme Procedure} hash-for-each proc table -@deffnx {C Function} scm_hash_map_to_list (proc, table) -@deffnx {C Function} scm_hash_for_each (proc, table) -Apply @var{proc} to the entries in the given hash @var{table}. Each -call is @code{(@var{proc} @var{key} @var{value})}. @code{hash-map->list} -returns a list of the results from these calls, @code{hash-for-each} -discards the results and returns an unspecified value. - -Calls are made over the table entries in an unspecified order, and for -@code{hash-map->list} the order of the values in the returned list is -unspecified. Results will be unpredictable if @var{table} is modified -while iterating. - -For example the following returns a new alist comprising all the -entries from @code{mytable}, in no particular order. - -@example -(hash-map->list cons mytable) -@end example -@end deffn - -@deffn {Scheme Procedure} hash-for-each-handle proc table -@deffnx {C Function} scm_hash_for_each_handle (proc, table) -Apply @var{proc} to the entries in the given hash @var{table}. Each -call is @code{(@var{proc} @var{handle})}, where @var{handle} is a -@code{(@var{key} . @var{value})} pair. Return an unspecified value. - -@code{hash-for-each-handle} differs from @code{hash-for-each} only in -the argument list of @var{proc}. -@end deffn - -@deffn {Scheme Procedure} hash-fold proc init table -@deffnx {C Function} scm_hash_fold (proc, init, table) -Accumulate a result by applying @var{proc} to the elements of the -given hash @var{table}. Each call is @code{(@var{proc} @var{key} -@var{value} @var{prior-result})}, where @var{key} and @var{value} are -from the @var{table} and @var{prior-result} is the return from the -previous @var{proc} call. For the first call, @var{prior-result} is -the given @var{init} value. - -Calls are made over the table entries in an unspecified order. -Results will be unpredictable if @var{table} is modified while -@code{hash-fold} is running. - -For example, the following returns a count of how many keys in -@code{mytable} are strings. - -@example -(hash-fold (lambda (key value prior) - (if (string? key) (1+ prior) prior)) - 0 mytable) -@end example -@end deffn - - -@c Local Variables: -@c TeX-master: "guile.texi" -@c End: diff --git a/doc/ref/scheme-control.texi b/doc/ref/scheme-control.texi index 4a09f1d1d..20ea8dfa1 100644 --- a/doc/ref/scheme-control.texi +++ b/doc/ref/scheme-control.texi @@ -6,7 +6,10 @@ @page @node Control Mechanisms -@chapter Controlling the Flow of Program Execution +@section Controlling the Flow of Program Execution + +See @ref{Control Flow} for a discussion of how the more general control +flow of Scheme affects C code. @menu * begin:: Evaluating a sequence of expressions. @@ -22,130 +25,8 @@ * Handling Errors:: How to handle errors in C code. @end menu -Scheme has a more general view of program flow than C, both locally and -non-locally. - -Controlling the local flow of control involves things like gotos, loops, -calling functions and returning from them. Non-local control flow -refers to situations where the program jumps across one or more levels -of function activations without using the normal call or return -operations. - -The primitive means of C for local control flow is the @code{goto} -statement, together with @code{if}. Loops done with @code{for}, -@code{while} or @code{do} could in principle be rewritten with just -@code{goto} and @code{if}. In Scheme, the primitive means for local -control flow is the @emph{function call} (together with @code{if}). -Thus, the repetition of some computation in a loop is ultimately -implemented by a function that calls itself, that is, by recursion. - -This approach is theoretically very powerful since it is easier to -reason formally about recursion than about gotos. In C, using -recursion exclusively would not be practical, tho, since it would eat -up the stack very quickly. In Scheme, however, it is practical: -function calls that appear in a @dfn{tail position} do not use any -additional stack space. - -A function call is in a tail position when it is the last thing the -calling function does. The value returned by the called function is -immediately returned from the calling function. In the following -example, the call to @code{bar-1} is in a tail position, while the -call to @code{bar-2} is not. (The call to @code{1-} in @code{foo-2} -is in a tail position, tho.) - -@lisp -(define (foo-1 x) - (bar-1 (1- x))) - -(define (foo-2 x) - (1- (bar-2 x))) -@end lisp - -Thus, when you take care to recurse only in tail positions, the -recursion will only use constant stack space and will be as good as a -loop constructed from gotos. - -Scheme offers a few syntactic abstractions (@code{do} and @dfn{named} -@code{let}) that make writing loops slightly easier. - -But only Scheme functions can call other functions in a tail position: -C functions can not. This matters when you have, say, two functions -that call each other recursively to form a common loop. The following -(unrealistic) example shows how one might go about determing whether a -non-negative integer @var{n} is even or odd. - -@lisp -(define (my-even? n) - (cond ((zero? n) #t) - (else (my-odd? (1- n))))) - -(define (my-odd? n) - (cond ((zero? n) #f) - (else (my-even? (1- n))))) -@end lisp - -Because the calls to @code{my-even?} and @code{my-odd?} are in tail -positions, these two procedures can be applied to arbitrary large -integers without overflowing the stack. (They will still take a lot -of time, of course.) - -However, when one or both of the two procedures would be rewritten in -C, it could no longer call its companion in a tail position (since C -does not have this concept). You might need to take this -consideration into account when deciding which parts of your program -to write in Scheme and which in C. - -In addition to calling functions and returning from them, a Scheme -program can also exit non-locally from a function so that the control -flow returns directly to an outer level. This means that some functions -might not return at all. - -Even more, it is not only possible to jump to some outer level of -control, a Scheme program can also jump back into the middle of a -function that has already exited. This might cause some functions to -return more than once. - -In general, these non-local jumps are done by invoking -@dfn{continuations} that have previously been captured using -@code{call-with-current-continuation}. Guile also offers a slightly -restricted set of functions, @code{catch} and @code{throw}, that can -only be used for non-local exits. This restriction makes them more -efficient. Error reporting (with the function @code{error}) is -implemented by invoking @code{throw}, for example. The functions -@code{catch} and @code{throw} belong to the topic of @dfn{exceptions}. - -Since Scheme functions can call C functions and vice versa, C code can -experience the more general control flow of Scheme as well. It is -possible that a C function will not return at all, or will return more -than once. While C does offer @code{setjmp} and @code{longjmp} for -non-local exits, it is still an unusual thing for C code. In -contrast, non-local exits are very common in Scheme, mostly to report -errors. - -You need to be prepared for the non-local jumps in the control flow -whenever you use a function from @code{libguile}: it is best to assume -that any @code{libguile} function might signal an error or run a pending -signal handler (which in turn can do arbitrary things). - -It is often necessary to take cleanup actions when the control leaves a -function non-locally. Also, when the control returns non-locally, some -setup actions might be called for. For example, the Scheme function -@code{with-output-to-port} needs to modify the global state so that -@code{current-output-port} returns the port passed to -@code{with-output-to-port}. The global output port needs to be reset to -its previous value when @code{with-output-to-port} returns normally or -when it is exited non-locally. Likewise, the port needs to be set again -when control enters non-locally. - -Scheme code can use the @code{dynamic-wind} function to arrange for -the setting and resetting of the global state. C code could use the -corresponding @code{scm_internal_dynamic_wind} function, but it might -prefer to use the @dfn{frames} concept that is more natural for C -code. - - @node begin -@section Evaluating a Sequence of Expressions +@subsection Evaluating a Sequence of Expressions @cindex begin @cindex sequencing @@ -178,7 +59,7 @@ sub-expressions. Such an expression returns the `unspecified' value. @end deffn @node if cond case -@section Simple Conditional Evaluation +@subsection Simple Conditional Evaluation @cindex conditional evaluation @cindex if @@ -260,7 +141,7 @@ unspecified. @node and or -@section Conditional Evaluation of a Sequence of Expressions +@subsection Conditional Evaluation of a Sequence of Expressions @code{and} and @code{or} evaluate all their arguments in order, similar to @code{begin}, but evaluation stops as soon as one of the expressions @@ -288,7 +169,7 @@ If used without expressions, @code{#f} is returned. @node while do -@section Iteration mechanisms +@subsection Iteration mechanisms @cindex iteration @cindex looping @@ -444,7 +325,7 @@ times. @node Continuations -@section Continuations +@subsection Continuations @cindex continuations A ``continuation'' is the code that will execute when a given function @@ -590,7 +471,7 @@ do). @node Multiple Values -@section Returning and Accepting Multiple Values +@subsection Returning and Accepting Multiple Values @cindex multiple values @cindex receive @@ -664,7 +545,7 @@ the expressions in @var{body} @dots{} are evaluated in order. @node Exceptions -@section Exceptions +@subsection Exceptions @cindex error handling @cindex exception handling @@ -709,7 +590,7 @@ more conveniently. @node Exception Terminology -@subsection Exception Terminology +@subsubsection 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 @@ -737,7 +618,7 @@ this terminology matches the corresponding Guile primitives. @node Catch -@subsection Catching Exceptions +@subsubsection 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 @@ -864,7 +745,7 @@ Operations}). @node Throw -@subsection Throwing Exceptions +@subsubsection 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 @@ -928,7 +809,7 @@ expression. @node Lazy Catch -@subsection Catch Without Unwinding +@subsubsection 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 @@ -1029,7 +910,7 @@ error is thrown. For an example of this, see REFFIXME:stack-catch. @node Exception Implementation -@subsection How Guile Implements Exceptions +@subsubsection How Guile Implements Exceptions It is traditional in Scheme to implement exception systems using @code{call-with-current-continuation}. Continuations @@ -1061,7 +942,7 @@ this @emph{upwards only} nature of exceptions. @node Error Reporting -@section Procedures for Signaling Errors +@subsection 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 @@ -1104,7 +985,7 @@ if an exception occurs then @code{#f} is returned instead. @node Dynamic Wind -@section Dynamic Wind +@subsection Dynamic Wind @rnindex dynamic-wind @deffn {Scheme Procedure} dynamic-wind in_guard thunk out_guard @@ -1160,7 +1041,7 @@ a-cont @end deffn @node Frames -@section Frames +@subsection Frames For Scheme code, the fundamental procedure to react to non-local entry and exits of dynamic contexts is @code{dynamic-wind}. C code could use @@ -1315,7 +1196,7 @@ The function @code{scm_frame_rewind_handler_with_scm} takes care that @node Handling Errors -@section How to Handle Errors +@subsection How to Handle Errors Error handling is based on @code{catch} and @code{throw}. Errors are always thrown with a @var{key} and four arguments: @@ -1419,7 +1300,7 @@ expression library. @end itemize -@subsection C Support +@subsubsection C Support In the following C functions, @var{SUBR} and @var{MESSAGE} parameters can be @code{NULL} to give the effect of @code{#f} described above. diff --git a/doc/ref/scheme-data.texi b/doc/ref/scheme-data.texi index 28f62861f..6a23fc95c 100755 --- a/doc/ref/scheme-data.texi +++ b/doc/ref/scheme-data.texi @@ -6,7 +6,7 @@ @page @node Simple Data Types -@chapter Simple Generic Data Types +@section Simple Generic Data Types This chapter describes those of Guile's simple data types which are primarily used for their role as items of generic data. By @@ -15,29 +15,29 @@ containers to hold other data --- i.e.@: pairs, lists, vectors and so on. For the documentation of such @dfn{compound} data types, see @ref{Compound Data Types}. -One of the great strengths of Scheme is that there is no straightforward -distinction between ``data'' and ``functionality''. For example, -Guile's support for dynamic linking could be described: - -@itemize @bullet -@item -either in a ``data-centric'' way, as the behaviour and properties of the -``dynamically linked object'' data type, and the operations that may be -applied to instances of this type - -@item -or in a ``functionality-centric'' way, as the set of procedures that -constitute Guile's support for dynamic linking, in the context of the -module system. -@end itemize - -The contents of this chapter are, therefore, a matter of judgment. By -@dfn{generic}, we mean to select those data types whose typical use as -@emph{data} in a wide variety of programming contexts is more important -than their use in the implementation of a particular piece of -@emph{functionality}. The last section of this chapter provides -references for all the data types that are documented not here but in a -``functionality-centric'' way elsewhere in the manual. +@c One of the great strengths of Scheme is that there is no straightforward +@c distinction between ``data'' and ``functionality''. For example, +@c Guile's support for dynamic linking could be described: + +@c @itemize @bullet +@c @item +@c either in a ``data-centric'' way, as the behaviour and properties of the +@c ``dynamically linked object'' data type, and the operations that may be +@c applied to instances of this type + +@c @item +@c or in a ``functionality-centric'' way, as the set of procedures that +@c constitute Guile's support for dynamic linking, in the context of the +@c module system. +@c @end itemize + +@c The contents of this chapter are, therefore, a matter of judgment. By +@c @dfn{generic}, we mean to select those data types whose typical use as +@c @emph{data} in a wide variety of programming contexts is more important +@c than their use in the implementation of a particular piece of +@c @emph{functionality}. The last section of this chapter provides +@c references for all the data types that are documented not here but in a +@c ``functionality-centric'' way elsewhere in the manual. @menu * Booleans:: True/false values. @@ -52,7 +52,7 @@ references for all the data types that are documented not here but in a @node Booleans -@section Booleans +@subsection Booleans @tpindex Booleans The two boolean values are @code{#t} for true and @code{#f} for false. @@ -145,7 +145,7 @@ sense; return false in the C sense otherwise. @end deffn @node Numbers -@section Numerical data types +@subsection Numerical data types @tpindex Numbers Guile supports a rich ``tower'' of numerical types --- integer, @@ -177,7 +177,7 @@ in Scheme, which is particularly clear and accessible: see @node Numerical Tower -@subsection Scheme's Numerical ``Tower'' +@subsubsection Scheme's Numerical ``Tower'' @rnindex number? Scheme's numerical ``tower'' consists of the following categories of @@ -249,7 +249,7 @@ The next few subsections document each of Guile's numerical data types in detail. @node Integers -@subsection Integers +@subsubsection Integers @tpindex Integer numbers @@ -313,7 +313,7 @@ Return @code{#t} if @var{x} is an integer number, else @code{#f}. @node Reals and Rationals -@subsection Real and Rational Numbers +@subsubsection Real and Rational Numbers @tpindex Real numbers @tpindex Rational numbers @@ -432,7 +432,7 @@ Return @code{#t} if @var{x} is @samp{+nan.0}, @code{#f} otherwise. @end deffn @node Complex Numbers -@subsection Complex Numbers +@subsubsection Complex Numbers @tpindex Complex numbers @rnindex complex? @@ -473,7 +473,7 @@ rational or integer number. @node Exactness -@subsection Exact and Inexact Numbers +@subsubsection Exact and Inexact Numbers @tpindex Exact numbers @tpindex Inexact numbers @@ -549,7 +549,7 @@ Convert the number @var{z} to its inexact representation. @node Number Syntax -@subsection Read Syntax for Numerical Data +@subsubsection Read Syntax for Numerical Data The read syntax for integers is a string of digits, optionally preceded by a minus or plus character, a code indicating the @@ -631,7 +631,7 @@ The sign is ignored for `not-a-number' and the value is always printed as @samp{+nan.0}. @node Integer Operations -@subsection Operations on Integer Values +@subsubsection Operations on Integer Values @rnindex odd? @rnindex even? @rnindex quotient @@ -705,7 +705,7 @@ Scheme function can take an arbitrary number. @node Comparison -@subsection Comparison Predicates +@subsubsection Comparison Predicates @rnindex zero? @rnindex positive? @rnindex negative? @@ -775,7 +775,7 @@ zero. @node Conversion -@subsection Converting Numbers To and From Strings +@subsubsection Converting Numbers To and From Strings @rnindex number->string @rnindex string->number @@ -800,7 +800,7 @@ syntactically valid notation for a number, then @node Complex -@subsection Complex Number Operations +@subsubsection Complex Number Operations @rnindex make-rectangular @rnindex make-polar @rnindex real-part @@ -846,7 +846,7 @@ Return the angle of the complex number @var{z}. @node Arithmetic -@subsection Arithmetic Functions +@subsubsection Arithmetic Functions @rnindex max @rnindex min @rnindex + @@ -942,7 +942,7 @@ Round the number @var{x} towards infinity. @node Scientific -@subsection Scientific Functions +@subsubsection Scientific Functions The following procedures accept any kind of number as arguments, including complex numbers. @@ -1046,7 +1046,7 @@ Return the hyperbolic arctangent of @var{z}. @node Primitive Numerics -@subsection Primitive Numeric Functions +@subsubsection Primitive Numeric Functions Many of Guile's numeric procedures which accept any kind of numbers as arguments, including complex numbers, are implemented as Scheme @@ -1190,7 +1190,7 @@ respectively. @node Bitwise Operations -@subsection Bitwise Operations +@subsubsection Bitwise Operations For the following bitwise functions, negative numbers are treated as infinite precision twos-complements. For instance @math{-6} is bits @@ -1356,7 +1356,7 @@ through @var{end} (exclusive) bits of @var{n}. The @node Random -@subsection Random Number Generation +@subsubsection Random Number Generation Pseudo-random numbers are generated from a random state object, which can be created with @code{seed->random-state}. The @var{state} @@ -1437,7 +1437,7 @@ The global random state used by the above functions when the @node Characters -@section Characters +@subsection Characters @tpindex Characters @noindent @@ -1639,15 +1639,15 @@ mentioned above. @node Strings -@section Strings +@subsection Strings @tpindex Strings Strings are fixed-length sequences of characters. They can be created by calling constructor procedures, but they can also literally get entered at the @acronym{REPL} or in Scheme source files. -Guile provides a rich set of string processing procedures, because text -handling is very important when Guile is used as a scripting language. +@c Guile provides a rich set of string processing procedures, because text +@c handling is very important when Guile is used as a scripting language. Strings always carry the information about how many characters they are composed of with them, so there is no special end-of-string character, @@ -1671,7 +1671,7 @@ called with string containing unusual characters. @end menu @node String Syntax -@subsection String Read Syntax +@subsubsection String Read Syntax The read syntax for strings is an arbitrarily long sequence of characters enclosed in double quotes (@code{"}).@footnote{Actually, @@ -1693,7 +1693,7 @@ The following are examples of string literals: @c FIXME::martin: What about escape sequences like \r, \n etc.? @node String Predicates -@subsection String Predicates +@subsubsection String Predicates The following procedures can be used to check whether a given string fulfills some specified property. @@ -1716,7 +1716,7 @@ y @result{} "foo" @end deffn @node String Constructors -@subsection String Constructors +@subsubsection String Constructors The string constructor procedures create new string objects, possibly initializing them with some specified character data. @@ -1742,7 +1742,7 @@ of the @var{string} are unspecified. @end deffn @node List/String Conversion -@subsection List/String conversion +@subsubsection List/String conversion When processing strings, it is often convenient to first convert them into a list representation by using the procedure @code{string->list}, @@ -1782,7 +1782,7 @@ result list. @node String Selection -@subsection String Selection +@subsubsection String Selection Portions of strings can be extracted by these procedures. @code{string-ref} delivers individual characters whereas @@ -1820,7 +1820,7 @@ exact integers satisfying: @end deffn @node String Modification -@subsection String Modification +@subsubsection String Modification These procedures are for modifying strings in-place. This means that the result of the operation is not a new string; instead, the original string's @@ -1863,7 +1863,7 @@ into @var{str2} beginning at position @var{start2}. @node String Comparison -@subsection String Comparison +@subsubsection String Comparison The procedures in this section are similar to the character ordering predicates (@pxref{Characters}), but are defined on character sequences. @@ -1946,7 +1946,7 @@ equal to @var{s2} regardless of case. @node String Searching -@subsection String Searching +@subsubsection String Searching When searching for the index of a character in a string, these procedures can be used. @@ -1991,7 +1991,7 @@ the C library. @end deffn @node Alphabetic Case Mapping -@subsection Alphabetic Case Mapping +@subsubsection Alphabetic Case Mapping These are procedures for mapping strings to their upper- or lower-case equivalents, respectively, or for capitalizing strings. @@ -2051,7 +2051,7 @@ y @result{} "Hello World" @node Appending Strings -@subsection Appending Strings +@subsubsection Appending Strings The procedure @code{string-append} appends several strings together to form a longer result string. @@ -2071,7 +2071,7 @@ concatenation of the given strings, @var{args}. @node Regular Expressions -@section Regular Expressions +@subsection Regular Expressions @tpindex Regular expressions @cindex regular expressions @@ -2105,7 +2105,7 @@ regex))}. @node Regexp Functions -@subsection Regexp Functions +@subsubsection Regexp Functions By default, Guile supports POSIX extended regular expressions. That means that the characters @samp{(}, @samp{)}, @samp{+} and @@ -2315,7 +2315,7 @@ follows to remove the @code{string-match} stage: @node Match Structures -@subsection Match Structures +@subsubsection Match Structures @cindex match structures @@ -2429,7 +2429,7 @@ Return the original @var{target} string. @node Backslash Escapes -@subsection Backslash Escapes +@subsubsection Backslash Escapes Sometimes you will want a regexp to match characters like @samp{*} or @samp{$} exactly. For example, to check whether a particular string @@ -2513,7 +2513,7 @@ to this cumbersome escape syntax. @node Symbols -@section Symbols +@subsection Symbols @tpindex Symbols Symbols in Scheme are widely used in three ways: as items of discrete @@ -2589,7 +2589,7 @@ which more below (@pxref{Symbol Variables}). @node Symbol Data -@subsection Symbols as Discrete Data +@subsubsection Symbols as Discrete Data Numbers and symbols are similar to the extent that they both lend themselves to @code{eq?} comparison. But symbols are more descriptive @@ -2669,7 +2669,7 @@ makes them ideal for use as discrete data. @node Symbol Keys -@subsection Symbols as Lookup Keys +@subsubsection Symbols as Lookup Keys Given their efficiency and descriptive power, it is natural to use symbols as the keys in an association list or hash table. @@ -2735,7 +2735,7 @@ list. @node Symbol Variables -@subsection Symbols as Denoting Variables +@subsubsection Symbols as Denoting Variables When an unquoted symbol in a Scheme program is evaluated, it is interpreted as a variable reference, and the result of the evaluation is @@ -2756,7 +2756,7 @@ Guile's module system. @node Symbol Primitives -@subsection Operations Related to Symbols +@subsubsection Operations Related to Symbols Given any Scheme value, you can determine whether it is a symbol using the @code{symbol?} primitive: @@ -2889,7 +2889,7 @@ and read back in. @node Symbol Props -@subsection Function Slots and Property Lists +@subsubsection Function Slots and Property Lists In traditional Lisp dialects, symbols are often understood as having three kinds of value at once: @@ -2969,7 +2969,7 @@ all.) For a more modern and Schemely approach to properties, see @node Symbol Read Syntax -@subsection Extended Read Syntax for Symbols +@subsubsection Extended Read Syntax for Symbols The read syntax for a symbol is a sequence of letters, digits, and @dfn{extended alphabetic characters}, beginning with a character that @@ -3022,7 +3022,7 @@ very readable. @node Symbol Uninterned -@subsection Uninterned Symbols +@subsubsection Uninterned Symbols What makes symbols useful is that they are automatically kept unique. There are no two symbols that are distinct objects but have the same @@ -3115,7 +3115,7 @@ foo-3 @node Keywords -@section Keywords +@subsection Keywords @tpindex Keywords Keywords are self-evaluating objects with a convenient read syntax that @@ -3134,7 +3134,7 @@ syntax extension to permit keywords to begin with @code{:} as well as @end menu @node Why Use Keywords? -@subsection Why Use Keywords? +@subsubsection Why Use Keywords? Keywords are useful in contexts where a program or procedure wants to be able to accept a large number of optional arguments without making its @@ -3194,7 +3194,7 @@ So the decision whether to use keywords or not is purely pragmatic: use them if they will clarify the procedure invocation at point of call. @node Coding With Keywords -@subsection Coding With Keywords +@subsubsection Coding With Keywords If a procedure wants to support keywords, it should take a rest argument and then use whatever means is convenient to extract keywords and their @@ -3255,7 +3255,7 @@ facilities provided by the @code{(ice-9 optargs)} module, see @node Keyword Read Syntax -@subsection Keyword Read Syntax +@subsubsection Keyword Read Syntax Guile, by default, only recognizes the keyword syntax specified by R5RS. A token of the form @code{#:NAME}, where @code{NAME} has the same syntax @@ -3298,7 +3298,7 @@ ABORT: (unbound-variable) @end smalllisp @node Keyword Procedures -@subsection Keyword Procedures +@subsubsection Keyword Procedures The following procedures can be used for converting symbols to keywords and back. @@ -3313,7 +3313,7 @@ Return a symbol with the same characters as in @var{kw}. @node Keyword Primitives -@subsection Keyword Primitives +@subsubsection Keyword Primitives Internally, a keyword is implemented as something like a tagged symbol, where the tag identifies the keyword as being self-evaluating, and the @@ -3371,7 +3371,7 @@ scm_c_make_keyword ("foo") @node Other Types -@section ``Functionality-Centric'' Data Types +@subsection ``Functionality-Centric'' Data Types Procedures and macros are documented in their own chapter: see @ref{Procedures and Macros}. diff --git a/doc/ref/scheme-debug.texi b/doc/ref/scheme-debug.texi index 74465014f..e69de29bb 100644 --- a/doc/ref/scheme-debug.texi +++ b/doc/ref/scheme-debug.texi @@ -1,266 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@page -@node Debugging -@chapter Debugging Infrastructure - -@menu -* Source Properties:: Remembering the source of an expression. -* Using Traps:: -* Capturing the Stack or Innermost Stack Frame:: -* Examining the Stack:: -* Examining Stack Frames:: -* Decoding Memoized Source Expressions:: -* Starting a New Stack:: -@end menu - - -@node Source Properties -@section Source Properties - -@cindex source properties -As Guile reads in Scheme code from file or from standard input, it -remembers the file name, line number and column number where each -expression begins. These pieces of information are known as the -@dfn{source properties} of the expression. If an expression undergoes -transformation --- for example, if there is a syntax transformer in -effect, or the expression is a macro call --- the source properties are -copied from the untransformed to the transformed expression so that, if -an error occurs when evaluating the transformed expression, Guile's -debugger can point back to the file and location where the expression -originated. - -The way that source properties are stored means that Guile can only -associate source properties with parenthesized expressions, and not, for -example, with individual symbols, numbers or strings. The difference -can be seen by typing @code{(xxx)} and @code{xxx} at the Guile prompt -(where the variable @code{xxx} has not been defined): - -@example -guile> (xxx) -standard input:2:1: In expression (xxx): -standard input:2:1: Unbound variable: xxx -ABORT: (unbound-variable) -guile> xxx -<unnamed port>: In expression xxx: -<unnamed port>: Unbound variable: xxx -ABORT: (unbound-variable) -@end example - -@noindent -In the latter case, no source properties were stored, so the best that -Guile could say regarding the location of the problem was ``<unnamed -port>''. - -The recording of source properties is controlled by the read option -named ``positions'' (@pxref{Reader options}). This option is switched -@emph{on} by default, together with the debug options ``debug'' and -``backtrace'' (@pxref{Debugger options}), when Guile is run -interactively; all these options are @emph{off} by default when Guile -runs a script non-interactively. - - -@node Using Traps -@section Using Traps - -@deffn {Scheme Procedure} with-traps thunk -@deffnx {C Function} scm_with_traps (thunk) -Call @var{thunk} with traps enabled. -@end deffn - -@deffn {Scheme Procedure} debug-object? obj -@deffnx {C Function} scm_debug_object_p (obj) -Return @code{#t} if @var{obj} is a debug object. -@end deffn - - -@node Capturing the Stack or Innermost Stack Frame -@section Capturing the Stack or Innermost Stack Frame - -When an error occurs in a running program, or the program hits a -breakpoint, its state at that point can be represented by a @dfn{stack} -of all the evaluations and procedure applications that are logically in -progress at that time, each of which is known as a @dfn{frame}. The -programmer can learn more about the program's state at the point of -interruption or error by inspecting the stack and its frames. - -@deffn {Scheme Procedure} make-stack obj . args -@deffnx {C Function} scm_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 {Scheme Procedure} last-stack-frame obj -@deffnx {C Function} scm_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 - - -@node Examining the Stack -@section Examining the Stack - -@deffn {Scheme Procedure} stack? obj -@deffnx {C Function} scm_stack_p (obj) -Return @code{#t} if @var{obj} is a calling stack. -@end deffn - -@deffn {Scheme Procedure} stack-id stack -@deffnx {C Function} scm_stack_id (stack) -Return the identifier given to @var{stack} by @code{start-stack}. -@end deffn - -@deffn {Scheme Procedure} stack-length stack -@deffnx {C Function} scm_stack_length (stack) -Return the length of @var{stack}. -@end deffn - -@deffn {Scheme Procedure} stack-ref stack index -@deffnx {C Function} scm_stack_ref (stack, index) -Return the @var{index}'th frame from @var{stack}. -@end deffn - -@deffn {Scheme Procedure} display-backtrace stack port [first [depth]] -@deffnx {C Function} scm_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 - - -@node Examining Stack Frames -@section Examining Stack Frames - -@deffn {Scheme Procedure} frame? obj -@deffnx {C Function} scm_frame_p (obj) -Return @code{#t} if @var{obj} is a stack frame. -@end deffn - -@deffn {Scheme Procedure} frame-number frame -@deffnx {C Function} scm_frame_number (frame) -Return the frame number of @var{frame}. -@end deffn - -@deffn {Scheme Procedure} frame-previous frame -@deffnx {C Function} scm_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 {Scheme Procedure} frame-next frame -@deffnx {C Function} scm_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 {Scheme Procedure} frame-source frame -@deffnx {C Function} scm_frame_source (frame) -Return the source of @var{frame}. -@end deffn - -@deffn {Scheme Procedure} frame-procedure? frame -@deffnx {C Function} scm_frame_procedure_p (frame) -Return @code{#t} if a procedure is associated with @var{frame}. -@end deffn - -@deffn {Scheme Procedure} frame-procedure frame -@deffnx {C Function} scm_frame_procedure (frame) -Return the procedure for @var{frame}, or @code{#f} if no -procedure is associated with @var{frame}. -@end deffn - -@deffn {Scheme Procedure} frame-arguments frame -@deffnx {C Function} scm_frame_arguments (frame) -Return the arguments of @var{frame}. -@end deffn - -@deffn {Scheme Procedure} frame-evaluating-args? frame -@deffnx {C Function} scm_frame_evaluating_args_p (frame) -Return @code{#t} if @var{frame} contains evaluated arguments. -@end deffn - -@deffn {Scheme Procedure} frame-overflow? frame -@deffnx {C Function} scm_frame_overflow_p (frame) -Return @code{#t} if @var{frame} is an overflow frame. -@end deffn - -@deffn {Scheme Procedure} frame-real? frame -@deffnx {C Function} scm_frame_real_p (frame) -Return @code{#t} if @var{frame} is a real frame. -@end deffn - -@deffn {Scheme Procedure} display-application frame [port [indent]] -@deffnx {C Function} scm_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 - - -@node Decoding Memoized Source Expressions -@section Decoding Memoized Source Expressions - -@deffn {Scheme Procedure} memoized? obj -@deffnx {C Function} scm_memoized_p (obj) -Return @code{#t} if @var{obj} is memoized. -@end deffn - -@deffn {Scheme Procedure} unmemoize m -@deffnx {C Function} scm_unmemoize (m) -Unmemoize the memoized expression @var{m}, -@end deffn - -@deffn {Scheme Procedure} memoized-environment m -@deffnx {C Function} scm_memoized_environment (m) -Return the environment of the memoized expression @var{m}. -@end deffn - - -@node Starting a New Stack -@section Starting a New Stack - -@deffn {Scheme Syntax} start-stack id exp -Evaluate @var{exp} on a new calling stack with identity @var{id}. If -@var{exp} is interrupted during evaluation, backtraces will not display -frames farther back than @var{exp}'s top-level form. This macro is a -way of artificially limiting backtraces and stack procedures, largely as -a convenience to the user. -@end deffn - - -@c Local Variables: -@c TeX-master: "guile.texi" -@c End: diff --git a/doc/ref/scheme-evaluation.texi b/doc/ref/scheme-evaluation.texi index 5c453397b..e69de29bb 100644 --- a/doc/ref/scheme-evaluation.texi +++ b/doc/ref/scheme-evaluation.texi @@ -1,604 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@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 - -An expression to be evaluated takes one of the following forms. - -@table @nicode - -@item @var{symbol} -A symbol is evaluated by dereferencing. A binding of that symbol is -sought and the value there used. For example, - -@example -(define x 123) -x @result{} 123 -@end example - -@item (@var{proc} @var{args}@dots{}) -A parenthesised expression is a function call. @var{proc} and each -argument are evaluated, then the function (which @var{proc} evaluated -to) is called with those arguments. - -The order in which @var{proc} and the arguments are evaluated is -unspecified, so be careful when using expressions with side effects. - -@example -(max 1 2 3) @result{} 3 - -(define (get-some-proc) min) -((get-some-proc) 1 2 3) @result{} 1 -@end example - -The same sort of parenthesised form is used for a macro invocation, -but in that case the arguments are not evaluated. See the -descriptions of macros for more on this (@pxref{Macros}, and -@pxref{Syntax Rules}). - -@item @var{constant} -Number, string, character and boolean constants evaluate ``to -themselves'', so can appear as literals. - -@example -123 @result{} 123 -99.9 @result{} 99.9 -"hello" @result{} "hello" -#\z @result{} #\z -#t @result{} #t -@end example - -Note that an application must not attempt to modify literal strings, -since they may be in read-only memory. - -@item (quote @var{data}) -@itemx '@var{data} -@findex quote -@findex ' -Quoting is used to obtain a literal symbol (instead of a variable -reference), a literal list (instead of a function call), or a literal -vector. @nicode{'} is simply a shorthand for a @code{quote} form. -For example, - -@example -'x @result{} x -'(1 2 3) @result{} (1 2 3) -'#(1 (2 3) 4) @result{} #(1 (2 3) 4) -(quote x) @result{} x -(quote (1 2 3)) @result{} (1 2 3) -(quote #(1 (2 3) 4)) @result{} #(1 (2 3) 4) -@end example - -Note that an application must not attempt to modify literal lists or -vectors obtained from a @code{quote} form, since they may be in -read-only memory. - -@item (quasiquote @var{data}) -@itemx `@var{data} -@findex quasiquote -@findex ` -Backquote quasi-quotation is like @code{quote}, but selected -sub-expressions are evaluated. This is a convenient way to construct -a list or vector structure most of which is constant, but at certain -points should have expressions substituted. - -The same effect can always be had with suitable @code{list}, -@code{cons} or @code{vector} calls, but quasi-quoting is often easier. - -@table @nicode - -@item (unquote @var{expr}) -@itemx ,@var{expr} -@findex unquote -@findex , -Within the quasiquote @var{data}, @code{unquote} or @code{,} indicates -an expression to be evaluated and inserted. The comma syntax @code{,} -is simply a shorthand for an @code{unquote} form. For example, - -@example -`(1 2 ,(* 9 9) 3 4) @result{} (1 2 81 3 4) -`(1 (unquote (+ 1 1)) 3) @result{} (1 2 3) -`#(1 ,(/ 12 2)) @result{} #(1 6) -@end example - -@item (unquote-splicing @var{expr}) -@itemx ,@@@var{expr} -@findex unquote-splicing -@findex ,@@ -Within the quasiquote @var{data}, @code{unquote-splicing} or -@code{,@@} indicates an expression to be evaluated and the elements of -the returned list inserted. @var{expr} must evaluate to a list. The -``comma-at'' syntax @code{,@@} is simply a shorthand for an -@code{unquote-splicing} form. - -@example -(define x '(2 3)) -`(1 ,@@x 4) @result{} (1 2 3 4) -`(1 (unquote-splicing (map 1+ x))) @result{} (1 3 4) -`#(9 ,@@x 9) @result{} #(9 2 3 9) -@end example - -Notice @code{,@@} differs from plain @code{,} in the way one level of -nesting is stripped. For @code{,@@} the elements of a returned list -are inserted, whereas with @code{,} it would be the list itself -inserted. -@end table - -@c -@c FIXME: What can we say about the mutability of a quasiquote -@c result? R5RS doesn't seem to specify anything, though where it -@c says backquote without commas is the same as plain quote then -@c presumably the "fixed" portions of a quasiquote expression must be -@c treated as immutable. -@c - -@end table - - -@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 {Scheme Procedure} read-hash-extend chr proc -@deffnx {C Function} scm_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 {Scheme Procedure} read [port] -@deffnx {C Function} scm_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{User level -options interfaces}. 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 {Scheme 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 {Scheme Procedure} read-enable option-name -@deffnx {Scheme Procedure} read-disable option-name -@deffnx {Scheme 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 {Scheme Procedure} read-options-interface [setting] -@deffnx {C Function} scm_read_options (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 - -@xref{Environments}. - -@rnindex eval -@c ARGFIXME environment/environment specifier -@deffn {Scheme Procedure} eval exp module -@deffnx {C Function} scm_eval (exp, module) -Evaluate @var{exp}, a list representing a Scheme expression, -in the top-level environment specified by @var{module}. -While @var{exp} is evaluated (using @code{primitive-eval}), -@var{module} is made the current module. The current module -is reset to its previous value when @var{eval} returns. -@end deffn - -@rnindex interaction-environment -@deffn {Scheme Procedure} interaction-environment -@deffnx {C Function} scm_interaction_environment () -Return a specifier for the environment that contains -implementation--defined bindings, typically a superset of those -listed in the report. The intent is that this procedure will -return the environment in which the implementation would -evaluate expressions dynamically typed by the user. -@end deffn - -@deffn {Scheme Procedure} eval-string string [module] -@deffnx {C Function} scm_eval_string (string) -@deffnx {C Function} scm_eval_string_in_module (string, module) -Evaluate @var{string} as the text representation of a Scheme form or -forms, and return whatever value they produce. Evaluation takes place -in the given module, or in the current module when no module is given. -While the code is evaluated, the given module is made the current one. -The current module is restored when this procedure returns. -@end deffn - -@deffn {Scheme Procedure} apply proc arg1 @dots{} argN arglst -@deffnx {C Function} scm_apply_0 (proc, arglst) -@deffnx {C Function} scm_apply_1 (proc, arg1, arglst) -@deffnx {C Function} scm_apply_2 (proc, arg1, arg2, arglst) -@deffnx {C Function} scm_apply_3 (proc, arg1, arg2, arg3, arglst) -@deffnx {C Function} scm_apply (proc, arg, rest) -@rnindex apply -Call @var{proc} with arguments @var{arg1} @dots{} @var{argN} plus the -elements of the @var{arglst} list. - -@code{scm_apply} takes parameters corresponding to a Scheme level -@code{(lambda (proc arg . rest) ...)}. So @var{arg} and all but the -last element of the @var{rest} list make up -@var{arg1}@dots{}@var{argN} and the last element of @var{rest} is the -@var{arglst} list. Or if @var{rest} is the empty list @code{SCM_EOL} -then there's no @var{arg1}@dots{}@var{argN} and @var{arg} is the -@var{arglst}. - -@var{arglst} is not modified, but the @var{rest} list passed to -@code{scm_apply} is modified. -@end deffn - -@deffn {C Function} scm_call_0 (proc) -@deffnx {C Function} scm_call_1 (proc, arg1) -@deffnx {C Function} scm_call_2 (proc, arg1, arg2) -@deffnx {C Function} scm_call_3 (proc, arg1, arg2, arg3) -Call @var{proc} with the given arguments. -@end deffn - -@deffn {Scheme Procedure} apply:nconc2last lst -@deffnx {C Function} scm_nconc2last (lst) -@var{lst} should be a list (@var{arg1} @dots{} @var{argN} -@var{arglst}), with @var{arglst} being a list. This function returns -a list comprising @var{arg1} to @var{argN} plus the elements of -@var{arglst}. @var{lst} is modified to form the return. @var{arglst} -is not modified, though the return does share structure with it. - -This operation collects up the arguments from a list which is -@code{apply} style parameters. -@end deffn - -@deffn {Scheme Procedure} primitive-eval exp -@deffnx {C Function} scm_primitive_eval (exp) -Evaluate @var{exp} in the top-level environment specified by -the current module. -@end deffn - - -@node Loading -@section Loading Scheme Code from File - -@rnindex load -@deffn {Scheme 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 {Scheme Procedure} load-from-path filename -Similar to @code{load}, but searches for @var{filename} in the load -paths. -@end deffn - -@deffn {Scheme Procedure} primitive-load filename -@deffnx {C Function} scm_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 {Scheme Procedure} primitive-load-path filename -@deffnx {C Function} scm_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 {Scheme Procedure} %search-load-path filename -@deffnx {C Function} scm_sys_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 {Scheme Procedure} current-load-port -@deffnx {C Function} scm_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 -@cindex delayed evaluation -@cindex promises - -Promises are a convenient way to defer a calculation until its result -is actually needed, and to run such a calculation only once. - -@deffn syntax delay expr -@rnindex delay -Return a promise object which holds the given @var{expr} expression, -ready to be evaluated by a later @code{force}. -@end deffn - -@deffn {Scheme Procedure} promise? obj -@deffnx {C Function} scm_promise_p (obj) -Return true if @var{obj} is a promise. -@end deffn - -@rnindex force -@deffn {Scheme Procedure} force p -@deffnx {C Function} scm_force (p) -Return the value obtained from evaluating the @var{expr} in the given -promise @var{p}. If @var{p} has previously been forced then its -@var{expr} is not evaluated again, instead the value obtained at that -time is simply returned. - -During a @code{force}, an @var{expr} can call @code{force} again on -its own promise, resulting in a recursive evaluation of that -@var{expr}. The first evaluation to return gives the value for the -promise. Higher evaluations run to completion in the normal way, but -their results are ignored, @code{force} always returns the first -value. -@end deffn - - -@node Local Evaluation -@section Local Evaluation - -[the-environment] - -@deffn {Scheme Procedure} local-eval exp [env] -@deffnx {C Function} scm_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{User level -options interfaces}. 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 {Scheme 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 {Scheme Procedure} eval-enable option-name -@deffnx {Scheme Procedure} eval-disable option-name -@deffnx {Scheme 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 {Scheme Procedure} eval-options-interface [setting] -@deffnx {C Function} scm_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 {Scheme 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 {Scheme Procedure} trap-enable option-name -@deffnx {Scheme Procedure} trap-disable option-name -@deffnx {Scheme 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 {Scheme Procedure} evaluator-traps-interface [setting] -@deffnx {C Function} scm_evaluator_traps (setting) -Option interface for the evaluator trap options. -@end deffn - - -@c Local Variables: -@c TeX-master: "guile.texi" -@c End: diff --git a/doc/ref/scheme-ideas.texi b/doc/ref/scheme-ideas.texi index 281a0ecfd..09a265dd7 100644 --- a/doc/ref/scheme-ideas.texi +++ b/doc/ref/scheme-ideas.texi @@ -4,9 +4,8 @@ @c Free Software Foundation, Inc. @c See the file guile.texi for copying conditions. -@page @node Basic Ideas -@chapter Basic Ideas in Scheme +@section Basic Ideas in Scheme In this chapter, we introduce the basic concepts that underpin the elegance and power of the Scheme language. @@ -30,7 +29,7 @@ tutorial. @node About Data -@section Data Types, Values and Variables +@subsection Data Types, Values and Variables This section discusses the representation of data types and values, what it means for Scheme to be a @dfn{latently typed} language, and the role @@ -46,7 +45,7 @@ variable. @node Latent Typing -@subsection Latent Typing +@subsubsection Latent Typing The term @dfn{latent typing} is used to describe a computer language, such as Scheme, for which you cannot, @emph{in general}, simply look at @@ -83,7 +82,7 @@ that Scheme programs use data types, values and variables. @node Values and Variables -@subsection Values and Variables +@subsubsection Values and Variables Scheme provides many data types that you can use to represent your data. Primitive types include characters, strings, numbers and procedures. @@ -120,7 +119,7 @@ the variable happens to be storing at a particular moment. @node Definition -@subsection Defining and Setting Variables +@subsubsection Defining and Setting Variables To define a new variable, you use Scheme's @code{define} syntax like this: @@ -201,7 +200,7 @@ of an existing variable. @node About Procedures -@section The Representation and Use of Procedures +@subsection The Representation and Use of Procedures This section introduces the basics of using and creating Scheme procedures. It discusses the representation of procedures as just @@ -220,7 +219,7 @@ explicit @code{lambda} expression. @node Procedures as Values -@subsection Procedures as Values +@subsubsection Procedures as Values One of the great simplifications of Scheme is that a procedure is just another type of value, and that procedure values can be passed around @@ -279,7 +278,7 @@ procedure value. @node Simple Invocation -@subsection Simple Procedure Invocation +@subsubsection Simple Procedure Invocation A procedure invocation in Scheme is written like this: @@ -340,7 +339,7 @@ its arguments.) @node Creating a Procedure -@subsection Creating and Using a New Procedure +@subsubsection Creating and Using a New Procedure Scheme has lots of standard procedures, and Guile provides all of these via predefined top level variables. All of these standard procedures @@ -418,7 +417,7 @@ same ways. @node Lambda Alternatives -@subsection Lambda Alternatives +@subsubsection Lambda Alternatives Since it is so common in Scheme programs to want to create a procedure and then store it in a variable, there is an alternative form of the @@ -482,7 +481,7 @@ subsequently read input.) @node About Expressions -@section Expressions and Evaluation +@subsection Expressions and Evaluation So far, we have met expressions that @emph{do} things, such as the @code{define} expressions that create and initialize new variables, and @@ -515,7 +514,7 @@ expressions. @node Evaluating -@subsection Evaluating Expressions and Executing Programs +@subsubsection Evaluating Expressions and Executing Programs In Scheme, the process of executing an expression is known as @dfn{evaluation}. Evaluation has two kinds of result: @@ -578,15 +577,16 @@ one of Scheme's special syntactic expressions. The following subsections describe how each of these types of expression is evaluated. -@menu -* Eval Literal:: Evaluating literal data. -* Eval Variable:: Evaluating variable references. -* Eval Procedure:: Evaluating procedure invocation expressions. -* Eval Special:: Evaluating special syntactic expressions. -@end menu +@c @menu +@c * Eval Literal:: Evaluating literal data. +@c * Eval Variable:: Evaluating variable references. +@c * Eval Procedure:: Evaluating procedure invocation expressions. +@c * Eval Special:: Evaluating special syntactic expressions. +@c @end menu + +@c @node Eval Literal -@node Eval Literal -@subsubsection Evaluating Literal Data +@subsubheading Evaluating Literal Data When a literal data expression is evaluated, the value of the expression is simply the value that the expression describes. The evaluation of a @@ -621,8 +621,8 @@ cannot be expressed as literal data; they must be created using a using the shorthand form of @code{define} (@pxref{Lambda Alternatives}). -@node Eval Variable -@subsubsection Evaluating a Variable Reference +@c @node Eval Variable +@subsubheading Evaluating a Variable Reference When an expression that consists simply of a variable name is evaluated, the value of the expression is the value of the named variable. The @@ -649,8 +649,8 @@ If there is no variable with the specified name, evaluation of the variable reference expression signals an error. -@node Eval Procedure -@subsubsection Evaluating a Procedure Invocation Expression +@c @node Eval Procedure +@subsubheading Evaluating a Procedure Invocation Expression This is where evaluation starts getting interesting! As already noted, a procedure invocation expression has the form @@ -740,8 +740,8 @@ obtained from @var{arg1} as its arguments. The resulting value is a numeric value that is the length of the argument string, which is 12. -@node Eval Special -@subsubsection Evaluating Special Syntactic Expressions +@c @node Eval Special +@subsubheading Evaluating Special Syntactic Expressions When a procedure invocation expression is evaluated, the procedure and @emph{all} the argument expressions must be evaluated before the @@ -785,7 +785,7 @@ syntax, see @xref{Syntax Summary}. @node The REPL -@subsection Using the Guile REPL +@subsubsection Using the Guile REPL If you start Guile without specifying a particular program for it to execute, Guile enters its standard Read Evaluate Print Loop --- or @@ -814,7 +814,7 @@ REPL and checking that it gives the expected @var{result}. @node Syntax Summary -@subsection Summary of Common Syntax +@subsubsection Summary of Common Syntax This subsection lists the most commonly used Scheme syntactic expressions, simply so that you will recognize common special syntax @@ -859,7 +859,7 @@ until either there are no expressions left, or one of them evaluates to @node About Closure -@section The Concept of Closure +@subsection The Concept of Closure @cindex closure @@ -885,7 +885,7 @@ more detail. @end menu @node About Environments -@subsection Names, Locations, Values and Environments +@subsubsection Names, Locations, Values and Environments @cindex location @cindex environment @@ -933,7 +933,7 @@ closure; the next subsection shows how it is done. @node Local Variables -@subsection Local Variables and Environments +@subsubsection Local Variables and Environments @cindex local variable @cindex variable, local @@ -974,7 +974,7 @@ expression, and therefore the value of the variable @code{area}. @node Chaining -@subsection Environment Chaining +@subsubsection Environment Chaining @cindex shadowing an imported variable binding @cindex chaining environments @@ -1025,7 +1025,7 @@ level environment. @node Lexical Scope -@subsection Lexical Scope +@subsubsection Lexical Scope The rules that we have just been describing are the details of how Scheme implements ``lexical scoping''. This subsection takes a brief @@ -1056,13 +1056,13 @@ scoping, the following subsection presents an example of non-lexical scoping and examines in detail how its behavior differs from the corresponding lexically scoped code. -@menu -* Scoping Example:: An example of non-lexical scoping. -@end menu - +@c @menu +@c * Scoping Example:: An example of non-lexical scoping. +@c @end menu + -@node Scoping Example -@subsubsection An Example of Non-Lexical Scoping +@c @node Scoping Example +@subsubheading An Example of Non-Lexical Scoping To demonstrate that non-lexical scoping does exist and can be useful, we present the following example from Emacs Lisp, which is a ``dynamically @@ -1167,7 +1167,7 @@ this identifier refer to the top level variable. @node Closure -@subsection Closure +@subsubsection Closure Consider a @code{let} expression that doesn't contain any @code{lambda}s: @@ -1235,7 +1235,7 @@ present examples that explore the usefulness of this concept. @node Serial Number -@subsection Example 1: A Serial Number Generator +@subsubsection Example 1: A Serial Number Generator This example uses closure to create a procedure with a variable binding that is private to the procedure, like a local variable, but whose value @@ -1277,7 +1277,7 @@ object with an association to this environment. @node Shared Variable -@subsection Example 2: A Shared Persistent Variable +@subsubsection Example 2: A Shared Persistent Variable This example uses closure to create two procedures, @code{get-balance} and @code{deposit}, that both refer to the same captured local @@ -1328,7 +1328,7 @@ that would not be accessible at top level. @node Callback Closure -@subsection Example 3: The Callback Closure Problem +@subsubsection Example 3: The Callback Closure Problem A frequently used programming model for library code is to allow an application to register a callback function for the library to call when @@ -1386,7 +1386,7 @@ correctly. @node OO Closure -@subsection Example 4: Object Orientation +@subsubsection Example 4: Object Orientation Closure is the capture of an environment, containing persistent variable bindings, within the definition of a procedure or a set of related diff --git a/doc/ref/scheme-intro.texi b/doc/ref/scheme-intro.texi index bd6700cc8..e3542d8a1 100644 --- a/doc/ref/scheme-intro.texi +++ b/doc/ref/scheme-intro.texi @@ -4,9 +4,8 @@ @c Free Software Foundation, Inc. @c See the file guile.texi for copying conditions. -@page @node Guile Scheme -@chapter Guile's Implementation of Scheme +@section Guile's Implementation of 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 diff --git a/doc/ref/scheme-io.texi b/doc/ref/scheme-io.texi index 0c6d1593d..e69de29bb 100644 --- a/doc/ref/scheme-io.texi +++ b/doc/ref/scheme-io.texi @@ -1,1161 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@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. -* I/O Extensions:: Using and extending ports in C. -@end menu - - -@node Ports -@section Ports - -Sequential input/output in Scheme is represented by operations on a -@dfn{port}. This chapter explains the operations that Guile provides -for working with ports. - -Ports are created by opening, for instance @code{open-file} for a file -(@pxref{File Ports}). Characters can be read from an input port and -written to an output port, or both on an input/output port. A port -can be closed (@pxref{Closing}) when no longer required, after which -any attempt to read or write is an error. - -The formal definition of a port is very generic: an input port is -simply ``an object which can deliver characters on demand,'' 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. -(@pxref{Soft Ports}, and @ref{String Ports}.) - -Ports are garbage collected in the usual way (@pxref{Memory -Management}), and will be closed at that time if not already closed. -In this case any errors occuring in the close will not be reported. -Usually a program will want to explicitly close so as to be sure all -its operations have been successful. Of course if a program has -abandoned something due to an error or other condition then closing -problems are probably not of interest. - -It is strongly recommended that file ports be closed explicitly when -no longer required. Most systems have limits on how many files can be -open, both on a per-process and a system-wide basis. A program that -uses many files should take care not to hit those limits. The same -applies to similar system resources such as pipes and sockets. - -Note that automatic garbage collection is triggered only by memory -consumption, not by file or other resource usage, so a program cannot -rely on that to keep it away from system limits. An explicit call to -@code{gc} can of course be relied on to pick up unreferenced ports. -If program flow makes it hard to be certain when to close then this -may be an acceptable way to control resource usage. - -@rnindex input-port? -@deffn {Scheme Procedure} input-port? x -@deffnx {C Function} scm_input_port_p (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 {Scheme Procedure} output-port? x -@deffnx {C Function} scm_output_port_p (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 {Scheme Procedure} port? x -@deffnx {C Function} scm_port_p (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 {Scheme Procedure} eof-object? x -@deffnx {C Function} scm_eof_object_p (x) -Return @code{#t} if @var{x} is an end-of-file object; otherwise -return @code{#f}. -@end deffn - -@rnindex char-ready? -@deffn {Scheme Procedure} char-ready? [port] -@deffnx {C Function} scm_char_ready_p (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 {Scheme Procedure} read-char [port] -@deffnx {C Function} scm_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 - -@deftypefn {C Function} size_t scm_c_read (SCM port, void *buffer, size_t size) -Read up to @var{size} bytes from @var{port} and store them in -@var{buffer}. The return value is the number of bytes actually read, -which can be less than @var{size} if end-of-file has been reached. - -Note that this function does not update @code{port-line} and -@code{port-column} below. -@end deftypefn - -@rnindex peek-char -@deffn {Scheme Procedure} peek-char [port] -@deffnx {C Function} scm_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 {Scheme Procedure} unread-char cobj [port] -@deffnx {C Function} scm_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 {Scheme Procedure} unread-string str port -@deffnx {C Function} scm_unread_string (str, port) -Place the string @var{str} in @var{port} so that its characters will -be read from left-to-right as the next characters from @var{port} -during 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 {Scheme Procedure} drain-input port -@deffnx {C Function} scm_drain_input (port) -This procedure clears a port's input buffers, similar -to the way that force-output clears the output buffer. The -contents of the buffers are returned as a single string, e.g., - -@lisp -(define p (open-input-file ...)) -(drain-input p) => empty string, nothing buffered yet. -(unread-char (read-char p) p) -(drain-input p) => initial chars from p, up to the buffer size. -@end lisp - -Draining the buffers may be useful for cleanly finishing -buffered I/O so that the file descriptor can be used directly -for further input. -@end deffn - -@deffn {Scheme Procedure} port-column port -@deffnx {Scheme Procedure} port-line port -@deffnx {C Function} scm_port_column (port) -@deffnx {C Function} scm_port_line (port) -Return the current column number or line number of @var{port}. -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 {Scheme Procedure} set-port-column! port column -@deffnx {Scheme Procedure} set-port-line! port line -@deffnx {C Function} scm_set_port_column_x (port, column) -@deffnx {C Function} scm_set_port_line_x (port, line) -Set the current column or line number of @var{port}. -@end deffn - -@node Writing -@section Writing - -[Generic procedures for writing to ports.] - -@deffn {Scheme Procedure} get-print-state port -@deffnx {C Function} scm_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 write -@deffn {Scheme Procedure} write obj [port] -Send a representation of @var{obj} to @var{port} or to the current -output port if not given. - -The output is designed to be machine readable, and can be read back -with @code{read} (@pxref{Reading}). Strings are printed in -doublequotes, with escapes if necessary, and characters are printed in -@samp{#\} notation. -@end deffn - -@rnindex display -@deffn {Scheme Procedure} display obj [port] -Send a representation of @var{obj} to @var{port} or to the current -output port if not given. - -The output is designed for human readability, it differs from -@code{write} in that strings are printed without doublequotes and -escapes, and characters are printed as per @code{write-char}, not in -@samp{#\} form. -@end deffn - -@rnindex newline -@deffn {Scheme Procedure} newline [port] -@deffnx {C Function} scm_newline (port) -Send a newline to @var{port}. -If @var{port} is omitted, send to the current output port. -@end deffn - -@deffn {Scheme Procedure} port-with-print-state port pstate -@deffnx {C Function} scm_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 {Scheme Procedure} print-options-interface [setting] -@deffnx {C Function} scm_print_options (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 {Scheme Procedure} simple-format destination message . args -@deffnx {C Function} scm_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 {Scheme Procedure} write-char chr [port] -@deffnx {C Function} scm_write_char (chr, port) -Send character @var{chr} to @var{port}. -@end deffn - -@deftypefn {C Function} void scm_c_write (SCM port, const void *buffer, size_t size) -Write @var{size} bytes at @var{buffer} to @var{port}. - -Note that this function does not update @code{port-line} and -@code{port-column} (@pxref{Reading}). -@end deftypefn - -@findex fflush -@deffn {Scheme Procedure} force-output [port] -@deffnx {C Function} scm_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 {Scheme Procedure} flush-all-ports -@deffnx {C Function} scm_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 {Scheme Procedure} close-port port -@deffnx {C Function} scm_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 - -@deffn {Scheme Procedure} close-input-port port -@deffnx {Scheme Procedure} close-output-port port -@deffnx {C Function} scm_close_input_port (port) -@deffnx {C Function} scm_close_output_port (port) -@rnindex close-input-port -@rnindex close-output-port -Close the specified input or output @var{port}. An exception may be -raised if an error occurs while closing. If @var{port} is already -closed, nothing is done. The return value is unspecified. - -See also @ref{Ports and File Descriptors, close}, for a procedure -which can close file descriptors. -@end deffn - -@deffn {Scheme Procedure} port-closed? port -@deffnx {C Function} scm_port_closed_p (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 {Scheme Procedure} seek fd_port offset whence -@deffnx {C Function} scm_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 {Scheme Procedure} ftell fd_port -@deffnx {C Function} scm_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 {Scheme Procedure} truncate-file object [length] -@deffnx {C Function} scm_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 {Scheme 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 {Scheme 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 {Scheme 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 {Scheme 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 {Scheme Procedure} write-line obj [port] -@deffnx {C Function} scm_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 {Scheme Procedure} %read-delimited! delims str gobble [port [start [end]]] -@deffnx {C Function} scm_read_delimited_x (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 {Scheme Procedure} %read-line [port] -@deffnx {C Function} scm_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 {Scheme Procedure} read-string!/partial str [port_or_fdes [start [end]]] -@deffnx {C Function} scm_read_string_x_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 {Scheme Procedure} write-string/partial str [port_or_fdes [start [end]]] -@deffnx {C Function} scm_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 {Scheme Procedure} current-input-port -@deffnx {C Function} scm_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 {Scheme Procedure} current-output-port -@deffnx {C Function} scm_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 {Scheme Procedure} current-error-port -@deffnx {C Function} scm_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 {Scheme Procedure} set-current-input-port port -@deffnx {Scheme Procedure} set-current-output-port port -@deffnx {Scheme Procedure} set-current-error-port port -@deffnx {C Function} scm_set_current_input_port (port) -@deffnx {C Function} scm_set_current_output_port (port) -@deffnx {C Function} scm_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 - -@deftypefn {C Function} void scm_frame_current_input_port (SCM port) -@deftypefnx {C Function} void scm_frame_current_output_port (SCM port) -@deftypefnx {C Function} void scm_frame_current_error_port (SCM port) -These functions must be used inside a pair of calls to -@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}). -During the dynamic extent of the frame, the indicated port is set to -@var{port}. - -More precisely, the current port is swapped with a `backup' value -whenever the frame is entered or left. The backup value is -initialized with the @var{port} argument. -@end deftypefn - -@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. - -Most systems have limits on how many files can be open, so it's -strongly recommended that file ports be closed explicitly when no -longer required (@pxref{Ports}). - -@deffn {Scheme Procedure} open-file filename mode -@deffnx {C Function} scm_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 {Scheme 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 {Scheme Procedure} open-output-file filename -Open @var{filename} for output. Equivalent to -@smalllisp -(open-file @var{filename} "w") -@end smalllisp -@end deffn - -@deffn {Scheme Procedure} call-with-input-file filename proc -@deffnx {Scheme Procedure} call-with-output-file filename proc -@rnindex call-with-input-file -@rnindex call-with-output-file -Open @var{filename} for input or output, and call @code{(@var{proc} -port)} with the resulting port. Return the value returned by -@var{proc}. @var{filename} is opened as per @code{open-input-file} or -@code{open-output-file} respectively, and an error is signalled if it -cannot be opened. - -When @var{proc} returns, the port is closed. If @var{proc} does not -return (eg.@: if it throws an error), then the port might not be -closed automatically, though it will be garbage collected in the usual -way if not otherwise referenced. -@end deffn - -@deffn {Scheme Procedure} with-input-from-file filename thunk -@deffnx {Scheme Procedure} with-output-to-file filename thunk -@deffnx {Scheme Procedure} with-error-to-file filename thunk -@rnindex with-input-from-file -@rnindex with-output-to-file -Open @var{filename} and call @code{(@var{thunk})} with the new port -setup as respectively the @code{current-input-port}, -@code{current-output-port}, or @code{current-error-port}. Return the -value returned by @var{thunk}. @var{filename} is opened as per -@code{open-input-file} or @code{open-output-file} respectively, and an -error is signalled if it cannot be opened. - -When @var{thunk} returns, the port is closed and the previous setting -of the respective current port is restored. - -The current port setting is managed with @code{dynamic-wind}, so the -previous value is restored no matter how @var{thunk} exits (eg.@: an -exception), and if @var{thunk} is re-entered (via a captured -continuation) then it's set again to the @var{FILENAME} port. - -The port is closed when @var{thunk} returns normally, but not when -exited via an exception or new continuation. This ensures it's still -ready for use if @var{thunk} is re-entered by a captured continuation. -Of course the port is always garbage collected and closed in the usual -way when no longer referenced anywhere. -@end deffn - -@deffn {Scheme Procedure} port-mode port -@deffnx {C Function} scm_port_mode (port) -Return 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 {Scheme Procedure} port-filename port -@deffnx {C Function} scm_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 {Scheme Procedure} set-port-filename! port filename -@deffnx {C Function} scm_set_port_filename_x (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 {Scheme Procedure} file-port? obj -@deffnx {C Function} scm_file_port_p (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 {Scheme Procedure} call-with-output-string proc -@deffnx {C Function} scm_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. @var{proc} should not close the port. -@end deffn - -@deffn {Scheme Procedure} call-with-input-string string proc -@deffnx {C Function} scm_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 {Scheme 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 {Scheme 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 {Scheme Procedure} open-input-string str -@deffnx {C Function} scm_open_input_string (str) -Take a string and return an input port that delivers characters -from the string. The port can be closed by -@code{close-input-port}, though its storage will be reclaimed -by the garbage collector if it becomes inaccessible. -@end deffn - -@deffn {Scheme Procedure} open-output-string -@deffnx {C Function} scm_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 {Scheme Procedure} get-output-string port -@deffnx {C Function} scm_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. - -@code{get-output-string} must be used before closing @var{port}, once -closed the string cannot be obtained. -@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 {Scheme Procedure} make-soft-port pv modes -@deffnx {C Function} scm_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 or 6. 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) -@item -(if present and not @code{#f}) thunk for computing the number of -characters that can be read from the port without blocking. -@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 {Scheme Procedure} %make-void-port mode -@deffnx {C Function} scm_sys_make_void_port (mode) -Create and return a new void port. A void port acts like -@file{/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 - - -@node I/O Extensions -@section 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 -@subsection C Port Interface - -This section describes how to use Scheme ports from C. - -@subsubsection 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. - -@subsubsection 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. - -@subsubsection 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 -implementation 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. - -@subsubsection 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 - -@subsubsection 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 - -@subsubsection 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 -@subsection 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} initializes three elements of the structure -(@code{name}, @code{fill_input} and @code{write}) from its arguments. -The remaining elements are initialized 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 synchronization 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 - - -@c Local Variables: -@c TeX-master: "guile.texi" -@c End: diff --git a/doc/ref/scheme-memory.texi b/doc/ref/scheme-memory.texi index 64fcf7b43..e69de29bb 100644 --- a/doc/ref/scheme-memory.texi +++ b/doc/ref/scheme-memory.texi @@ -1,540 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@page -@node Memory Management -@chapter Memory Management and Garbage Collection - -Guile uses a @emph{garbage collector} to manage most of its objects. -This means that the memory used to store a Scheme string, say, is -automatically reclaimed when no one is using this string any longer. -This can work because Guile knows enough about its objects at run-time -to be able to trace all references between them. Thus, it can find all -'live' objects (objects that are still in use) by starting from a known -set of 'root' objects and following the links that these objects have to -other objects, and so on. The objects that are not reached by this -recursive process can be considered 'dead' and their memory can be -reused for new objects. - -@menu -* Garbage Collection:: -* Memory Blocks:: -* Weak References:: -* Guardians:: -@end menu - - -@node Garbage Collection -@section Garbage Collection - -The general process of collecting dead objects outlined above relies on -the fact that the garbage collector is able to find all references to -SCM objects that might be used by the program in the future. When you -are programming in Scheme, you don't need to worry about this: The -collector is automatically aware of all objects in use by Scheme code. - -When programming in C, you must help the garbage collector a bit so that -it can find all objects that are accessible from C. You do this when -writing a SMOB mark function, for example. By calling this function, -the garbage collector learns about all references that your SMOB has to -other SCM objects. - -Other references to SCM objects, such as global variables of type SCM or -other random data structures in the heap that contain fields of type -SCM, can be made visible to the garbage collector by calling the -functions @code{scm_gc_protect} or @code{scm_permanent_object}. You -normally use these funtions for long lived objects such as a hash table -that is stored in a global variable. For temporary references in local -variables or function arguments, using these functions would be too -expensive. - -These references are handled differently: Local variables (and function -arguments) of type SCM are automatically visible to the garbage -collector. This works because the collector scans the stack for -potential references to SCM objects and considers all referenced objects -to be alive. The scanning considers each and every word of the stack, -regardless of what it is actually used for, and then decides whether it -could possible be a reference to a SCM object. Thus, the scanning is -guaranteed to find all actual references, but it might also find words -that only accidentally look like references. These `false positives' -might keep SCM objects alive that would otherwise be considered dead. -While this might waste memory, keeping an object around longer than it -strictly needs to is harmless. This is why this technique is called -``conservative garbage collection''. In practice, the wasted memory -seems to be no problem. - -The stack of every thread is scanned in this way and the registers of -the CPU and all other memory locations where local variables or function -parameters might show up are included in this scan as well. - -The consequence of the conservative scanning is that you can just -declare local variables and function parameters of type SCM and be sure -that the garbage collector will not free the corresponding objects. - -However, a local variable or function parameter is only protected as -long as it is really on the stack (or in some register). As an -optimization, the C compiler might reuse its location for some other -value and the SCM object would no longer be protected. Normally, this -leads to exactly the right behabvior: the compiler will only overwrite a -reference when it is no longer needed and thus the object becomes -unprotected precisely when the reference disappears, just as wanted. - -There are situations, however, where a SCM object needs to be around -longer than its reference from a local variable or function parameter. -This happens, for example, when you retrieve the array of characters -from a Scheme string and work on that array directly. The reference to -the SCM string object might be dead after the character array has been -retrieved, but the array itself is still in use and thus the string -object must be protected. The compiler does not know about this -connection and might overwrite the SCM reference too early. - -To get around this problem, you can use @code{scm_remember_upto_here_1} -and its cousins. It will keep the compiler from overwriting the -reference. For an example of its use, see @ref{Remembering During -Operations}. - -@deffn {Scheme Procedure} gc -@deffnx {C Function} scm_gc () -Scans all of SCM objects and reclaims for further use those that are -no longer accessible. You normally don't need to call this function -explicitly. It is called automatically when appropriate. -@end deffn - -@deftypefn {C Function} SCM scm_gc_protect_object (SCM @var{obj}) -Protects @var{obj} from being freed by the garbage collector, when it -otherwise might be. When you are done with the object, call -@code{scm_gc_unprotect_object} on the object. Calls to -@code{scm_gc_protect}/@code{scm_gc_unprotect_object} can be nested, and -the object remains protected until it has been unprotected as many times -as it was protected. It is an error to unprotect an object more times -than it has been protected. Returns the SCM object it was passed. -@end deftypefn - -@deftypefn {C Function} SCM scm_gc_unprotect_object (SCM @var{obj}) - -Unprotects an object from the garbage collector which was protected by -@code{scm_gc_unprotect_object}. Returns the SCM object it was passed. -@end deftypefn - -@deftypefn {C Function} SCM scm_permanent_object (SCM @var{obj}) - -Similar to @code{scm_gc_protect_object} in that it causes the -collector to always mark the object, except that it should not be -nested (only call @code{scm_permanent_object} on an object once), and -it has no corresponding unpermanent function. Once an object is -declared permanent, it will never be freed. Returns the SCM object it -was passed. -@end deftypefn - -@c NOTE: The varargs scm_remember_upto_here is deliberately not -@c documented, because we don't think it can be implemented as a nice -@c inline compiler directive or asm block. New _3, _4 or whatever -@c forms could certainly be added though, if needed. - -@deftypefn {C Macro} void scm_remember_upto_here_1 (SCM obj) -@deftypefnx {C Macro} void scm_remember_upto_here_2 (SCM obj1, SCM obj2) -Create a reference to the given object or objects, so they're certain -to be present on the stack or in a register and hence will not be -freed by the garbage collector before this point. - -Note that these functions can only be applied to ordinary C local -variables (ie.@: ``automatics''). Objects held in global or static -variables or some malloced block or the like cannot be protected with -this mechanism. -@end deftypefn - -@deffn {Scheme Procedure} gc-stats -@deffnx {C Function} scm_gc_stats () -Return an association list of statistics about Guile's current -use of storage. - -@end deffn - - -@node Memory Blocks -@section Memory Blocks - -In C programs, dynamic management of memory blocks is normally done -with the functions malloc, realloc, and free. Guile has additional -functions for dynamic memory allocation that are integrated into the -garbage collector and the error reporting system. - -Memory blocks that are associated with Scheme objects (for example a -smob) should be allocated and freed with @code{scm_gc_malloc} and -@code{scm_gc_free}. The function @code{scm_gc_malloc} will either -return a valid pointer or signal an error. It will also assume that -the new memory can be freed by a garbage collection. The garbage -collector uses this information to decide when to try to actually -collect some garbage. Memory blocks allocated with -@code{scm_gc_malloc} must be freed with @code{scm_gc_free}. - -For memory that is not associated with a Scheme object, you can use -@code{scm_malloc} instead of @code{malloc}. Like -@code{scm_gc_malloc}, it will either return a valid pointer or signal -an error. However, it will not assume that the new memory block can -be freed by a garbage collection. The memory can be freed with -@code{free}. - -There is also @code{scm_gc_realloc} and @code{scm_realloc}, to be used -in place of @code{realloc} when appropriate, @code{scm_gc_calloc} and -@code{scm_calloc}, to be used in place of @code{calloc} when -appropriate. - -For really specialized needs, take at look at -@code{scm_gc_register_collectable_memory} and -@code{scm_gc_unregister_collectable_memory}. - -@deftypefn {C Function} {void *} scm_malloc (size_t @var{size}) -@deftypefnx {C Function} {void *} scm_calloc (size_t @var{size}) -Allocate @var{size} bytes of memory and return a pointer to it. When -@var{size} is 0, return @code{NULL}. When not enough memory is -available, signal an error. This function runs the GC to free up some -memory when it deems it appropriate. - -The memory is allocated by the libc @code{malloc} function and can be -freed with @code{free}. There is no @code{scm_free} function to go -with @code{scm_malloc} to make it easier to pass memory back and forth -between different modules. - -The function @code{scm_calloc} is similar to @code{scm_malloc}, but -initializes the block of memory to zero as well. -@end deftypefn - -@deftypefn {C Function} {void *} scm_realloc (void *@var{mem}, size_t @var{new_size}) -Change the size of the memory block at @var{mem} to @var{new_size} and -return its new location. When @var{new_size} is 0, this is the same -as calling @code{free} on @var{mem} and @code{NULL} is returned. When -@var{mem} is @code{NULL}, this function behaves like @code{scm_malloc} -and allocates a new block of size @var{new_size}. - -When not enough memory is available, signal an error. This function -runs the GC to free up some memory when it deems it appropriate. -@end deftypefn - - - - -@deftypefn {C Function} void scm_gc_register_collectable_memory (void *@var{mem}, size_t @var{size}, const char *@var{what}) -Informs the GC that the memory at @var{mem} of size @var{size} can -potentially be freed during a GC. That is, announce that @var{mem} is -part of a GC controlled object and when the GC happens to free that -object, @var{size} bytes will be freed along with it. The GC will -@strong{not} free the memory itself, it will just know that so-and-so -much bytes of memory are associated with GC controlled objects and the -memory system figures this into its decisions when to run a GC. - -@var{mem} does not need to come from @code{scm_malloc}. You can only -call this function once for every memory block. - -The @var{what} argument is used for statistical purposes. It should -describe the type of object that the memory will be used for so that -users can identify just what strange objects are eating up their -memory. -@end deftypefn - -@deftypefn {C Function} void scm_gc_unregister_collectable_memory (void *@var{mem}, size_t @var{size}) -Informs the GC that the memory at @var{mem} of size @var{size} is no -longer associated with a GC controlled object. You must take care to -match up every call to @code{scm_gc_register_collectable_memory} with -a call to @code{scm_gc_unregister_collectable_memory}. If you don't do -this, the GC might have a wrong impression of what is going on and run -much less efficiently than it could. -@end deftypefn - -@deftypefn {C Function} {void *} scm_gc_malloc (size_t @var{size}, const char *@var{what}) -@deftypefnx {C Function} {void *} scm_gc_realloc (void *@var{mem}, size_t @var{old_size}, size_t @var{new_size}, const char *@var{what}); -@deftypefnx {C Function} {void *} scm_gc_calloc (size_t @var{size}, const char *@var{what}) -Like @code{scm_malloc}, @code{scm_realloc} or @code{scm_calloc}, but -also call @code{scm_gc_register_collectable_memory}. Note that you -need to pass the old size of a reallocated memory block as well. See -below for a motivation. -@end deftypefn - - -@deftypefn {C Function} void scm_gc_free (void *@var{mem}, size_t @var{size}, const char *@var{what}) -Like @code{free}, but also call @code{scm_gc_unregister_collectable_memory}. - -Note that you need to explicitely pass the @var{size} parameter. This -is done since it should normally be easy to provide this parameter -(for memory that is associated with GC controlled objects) and this -frees us from tracking this value in the GC itself, which will keep -the memory management overhead very low. -@end deftypefn - -@deffn {Scheme Procedure} malloc-stats -Return an alist ((@var{what} . @var{n}) ...) describing number -of malloced objects. -@var{what} is the second argument to @code{scm_gc_malloc}, -@var{n} is the number of objects of that type currently -allocated. -@end deffn - - -@subsection Upgrading from scm_must_malloc et al. - -Version 1.6 of Guile and earlier did not have the functions from the -previous section. In their place, it had the functions -@code{scm_must_malloc}, @code{scm_must_realloc} and -@code{scm_must_free}. This section explains why we want you to stop -using them, and how to do this. - -@findex scm_must_malloc -@findex scm_must_realloc -@findex scm_must_calloc -@findex scm_must_free -The functions @code{scm_must_malloc} and @code{scm_must_realloc} -behaved like @code{scm_gc_malloc} and @code{scm_gc_realloc} do now, -respectively. They would inform the GC about the newly allocated -memory via the internal equivalent of -@code{scm_gc_register_collectable_memory}. However, -@code{scm_must_free} did not unregister the memory it was about to -free. The usual way to unregister memory was to return its size from -a smob free function. - -This disconnectedness of the actual freeing of memory and reporting -this to the GC proved to be bad in practice. It was easy to make -mistakes and report the wrong size because allocating and freeing was -not done with symmetric code, and because it is cumbersome to compute -the total size of nested data structures that were freed with multiple -calls to @code{scm_must_free}. Additionally, there was no equivalent -to @code{scm_malloc}, and it was tempting to just use -@code{scm_must_malloc} and never to tell the GC that the memory has -been freed. - -The effect was that the internal statistics kept by the GC drifted out -of sync with reality and could even overflow in long running programs. -When this happened, the result was a dramatic increase in (senseless) -GC activity which would effectively stop the program dead. - -@findex scm_done_malloc -@findex scm_done_free -The functions @code{scm_done_malloc} and @code{scm_done_free} were -introduced to help restore balance to the force, but existing bugs did -not magically disappear, of course. - -Therefore we decided to force everybody to review their code by -deprecating the existing functions and introducing new ones in their -place that are hopefully easier to use correctly. - -For every use of @code{scm_must_malloc} you need to decide whether to -use @code{scm_malloc} or @code{scm_gc_malloc} in its place. When the -memory block is not part of a smob or some other Scheme object whose -lifetime is ultimately managed by the garbage collector, use -@code{scm_malloc} and @code{free}. When it is part of a smob, use -@code{scm_gc_malloc} and change the smob free function to use -@code{scm_gc_free} instead of @code{scm_must_free} or @code{free} and -make it return zero. - -The important thing is to always pair @code{scm_malloc} with -@code{free}; and to always pair @code{scm_gc_malloc} with -@code{scm_gc_free}. - -The same reasoning applies to @code{scm_must_realloc} and -@code{scm_realloc} versus @code{scm_gc_realloc}. - - -@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 -referenced from anywhere else. For weak value hashes, the same happens -as soon as the value is no longer in use. Entries in a doubly weak hash -disappear when either the key or the value are not used anywhere else -anymore. - -Object properties offer the same kind of functionality as weak key -hashes in many situations. (@pxref{Object Properties}) - -Here's an example (a little bit strained perhaps, but one of the -examples is actually used in Guile): - -Assume that you're implementing a debugging system where you want to -associate information about filename and position of source code -expressions with the expressions themselves. - -Hashtables can be used for that, but if you use ordinary hash tables -it will be impossible for the scheme interpreter to "forget" old -source when, for example, a file is reloaded. - -To implement the mapping from source code expressions to positional -information it is necessary to use weak-key tables since we don't want -the expressions to be remembered just because they are in our table. - -To implement a mapping from source file line numbers to source code -expressions you would use a weak-value table. - -To implement a mapping from source code expressions to the procedures -they constitute a doubly-weak table has to be used. - -@menu -* Weak key hashes:: -* Weak vectors:: -@end menu - - -@node Weak key hashes -@subsection Weak key hashes - -@deffn {Scheme Procedure} make-weak-key-hash-table size -@deffnx {Scheme Procedure} make-weak-value-hash-table size -@deffnx {Scheme Procedure} make-doubly-weak-hash-table size -@deffnx {C Function} scm_make_weak_key_hash_table (size) -@deffnx {C Function} scm_make_weak_value_hash_table (size) -@deffnx {C Function} scm_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 {Scheme Procedure} weak-key-hash-table? obj -@deffnx {Scheme Procedure} weak-value-hash-table? obj -@deffnx {Scheme Procedure} doubly-weak-hash-table? obj -@deffnx {C Function} scm_weak_key_hash_table_p (obj) -@deffnx {C Function} scm_weak_value_hash_table_p (obj) -@deffnx {C Function} scm_doubly_weak_hash_table_p (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 {Scheme Procedure} make-weak-value-hash-table k -@end deffn - -@deffn {Scheme Procedure} weak-value-hash-table? x -@end deffn - -@deffn {Scheme Procedure} make-doubly-weak-hash-table k -@end deffn - -@deffn {Scheme Procedure} 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 {Scheme Procedure} make-weak-vector size [fill] -@deffnx {C Function} scm_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 {Scheme Procedure} weak-vector . l -@deffnx {Scheme Procedure} list->weak-vector l -@deffnx {C Function} scm_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 {Scheme Procedure} weak-vector? obj -@deffnx {C Function} scm_weak_vector_p (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 {Scheme Procedure} make-guardian [greedy?] -@deffnx {C Function} scm_make_guardian (greedy_p) -Create a new guardian. -A guardian protects a set of objects from garbage collection, -allowing a program to apply cleanup or other actions. - -@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 {Scheme Procedure} destroy-guardian! guardian -@deffnx {C Function} scm_destroy_guardian_x (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 {Scheme Procedure} guardian-greedy? guardian -@deffnx {C Function} scm_guardian_greedy_p (guardian) -Return @code{#t} if @var{guardian} is a greedy guardian, otherwise @code{#f}. -@end deffn - -@deffn {Scheme Procedure} guardian-destroyed? guardian -@deffnx {C Function} scm_guardian_destroyed_p (guardian) -Return @code{#t} if @var{guardian} has been destroyed, otherwise @code{#f}. -@end deffn - - -@page -@node Objects -@chapter Objects - -@deffn {Scheme Procedure} entity? obj -@deffnx {C Function} scm_entity_p (obj) -Return @code{#t} if @var{obj} is an entity. -@end deffn - -@deffn {Scheme Procedure} operator? obj -@deffnx {C Function} scm_operator_p (obj) -Return @code{#t} if @var{obj} is an operator. -@end deffn - -@deffn {Scheme Procedure} set-object-procedure! obj proc -@deffnx {C Function} scm_set_object_procedure_x (obj, proc) -Set the object procedure of @var{obj} to @var{proc}. -@var{obj} must be either an entity or an operator. -@end deffn - -@deffn {Scheme Procedure} make-class-object metaclass layout -@deffnx {C Function} scm_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 {Scheme Procedure} make-subclass-object class layout -@deffnx {C Function} scm_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: diff --git a/doc/ref/scheme-modules.texi b/doc/ref/scheme-modules.texi index 3923ed05e..e69de29bb 100644 --- a/doc/ref/scheme-modules.texi +++ b/doc/ref/scheme-modules.texi @@ -1,1042 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@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 - -In addition, Guile offers variables as first-class objects. They can -be used for interacting with the module system. - -@menu -* provide and require:: The SLIB feature mechanism. -* Environments:: R5RS top-level environments. -* The Guile module system:: How Guile does it. -* Dynamic Libraries:: Loading libraries of compiled code at run time. -* Variables:: First-class variables. -@end menu - -@node provide and require -@section provide and require - -Aubrey Jaffer, mostly to support his portable Scheme library SLIB, -implemented a provide/require mechanism for many Scheme implementations. -Library files in SLIB @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. - -When SLIB is used with Guile, provide and require can be used to access -its facilities. - -@node Environments -@section Environments -@cindex environment - -Scheme, as defined in R5RS, does @emph{not} have a full module system. -However it does define the concept of a top-level @dfn{environment}. -Such an environment maps identifiers (symbols) to Scheme objects such -as procedures and lists: @ref{About Closure}. In other words, it -implements a set of @dfn{bindings}. - -Environments in R5RS can be passed as the second argument to -@code{eval} (@pxref{Fly Evaluation}). Three procedures are defined to -return environments: @code{scheme-report-environment}, -@code{null-environment} and @code{interaction-environment} (@pxref{Fly -Evaluation}). - -In addition, in Guile any module can be used as an R5RS environment, -i.e., passed as the second argument to @code{eval}. - -Note: the following two procedures are available only when the -@code{(ice-9 r5rs)} module is loaded: - -@smalllisp -(use-modules (ice-9 r5rs)) -@end smalllisp - -@deffn {Scheme Procedure} scheme-report-environment version -@deffnx {Scheme Procedure} null-environment version -@var{version} must be the exact integer `5', corresponding to revision -5 of the Scheme report (the Revised^5 Report on Scheme). -@code{scheme-report-environment} returns a specifier for an -environment that is empty except for all bindings defined in the -report that are either required or both optional and supported by the -implementation. @code{null-environment} returns a specifier for an -environment that is empty except for the (syntactic) bindings for all -syntactic keywords defined in the report that are either required or -both optional and supported by the implementation. - -Currently Guile does not support values of @var{version} for other -revisions of the report. - -The effect of assigning (through the use of @code{eval}) a variable -bound in a @code{scheme-report-environment} (for example @code{car}) -is unspecified. Currently the environments specified by -@code{scheme-report-environment} are not immutable in Guile. -@end deffn - -@node The Guile module system -@section The Guile module system - -The Guile module system extends the concept of environments, discussed -in the previous section, with mechanisms to define, use and customise -sets of bindings. - -In 1996 Tom Lord implemented a full-featured module system for Guile which -allows loading Scheme source files into a private name space. This system has -been in available since at least Guile version 1.1. - -For Guile version 1.5.0 and later, the system has been improved to have better -integration from C code, more fine-grained user control over interfaces, and -documentation. - -Although it is anticipated that the module system implementation will -change in the future, the Scheme programming interface described in this -manual should be considered stable. The C programming interface is -considered relatively stable, although at the time of this writing, -there is still some flux. - -@menu -* General Information about Modules:: Guile module basics. -* Using Guile Modules:: How to use existing modules. -* Creating Guile Modules:: How to package your code into modules. -* Module System Quirks:: Strange things to be aware of. -* Included Guile Modules:: Which modules come with Guile? -* Accessing Modules from C:: How to work with modules with C code. -@end menu - -@node General Information about Modules -@subsection General Information about Modules - -A Guile module can be thought of as a collection of named procedures, -variables and macros. More precisely, it is a set of @dfn{bindings} -of symbols (names) to Scheme objects. - -An environment is a mapping from identifiers (or symbols) to locations, -i.e., a set of bindings. -There are top-level environments and lexical environments. -The environment in which a lambda is executed is remembered as part of its -definition. - -Within a module, all bindings are visible. Certain bindings -can be declared @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} (@pxref{Loading}). The resulting file name is -then searched in all directories in the variable @code{%load-path} -(@pxref{Build Config}). For example, the @code{(ice-9 popen)} module -would result in the filename @code{ice-9/popen.scm} and searched in the -installation directories 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, following %load-path (@pxref{Build -Config}). - -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) - :renamer (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}. - -You can also directly refer to bindings in a module by using the -@code{@@} syntax. For example, instead of using the -@code{use-modules} statement from above and writing -@code{unixy:pipe-open} to refer to the @code{pipe-open} from the -@code{(ice-9 popen)}, you could also write @code{(@@ (ice-9 popen) -open-pipe)}. Thus an alternative to the complete @code{use-modules} -statement would be - -@smalllisp -(define unixy:pipe-open (@@ (ice-9 popen) open-pipe)) -(define unixy:close-pipe (@@ (ice-9 popen) close-pipe)) -@end smalllisp - -There is also @code{@@@@}, which can be used like @code{@@}, but does -not check whether the variable that is being accessed is actually -exported. Thus, @code{@@@@} can be thought of as the impolite version -of @code{@@} and should only be used as a last resort or for -debugging, for example. - -Note that just as with a @code{use-modules} statement, any module that -has not yet been loaded yet will be loaded when referenced by a -@code{@@} or @code{@@@@} form. - -You can also use the @code{@@} and @code{@@@@} syntaxes as the target -of a @code{set!} when the binding refers to a variable. - -@c begin (scm-doc-string "boot-9.scm" "symbol-prefix-proc") -@deffn {Scheme 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] [:renamer 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{:renamer} 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 - -@deffn syntax @@ module-name binding-name -Refer to the binding named @var{binding-name} in module -@var{module-name}. The binding must have been exported by the module. -@end deffn - -@deffn syntax @@@@ module-name binding-name -Refer to the binding named @var{binding-name} in module -@var{module-name}. The binding must not have been exported by the -module. This syntax is only intended for debugging purposes or as a -last resort. -@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 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{Debugging Features}). - -@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 (srfi srfi-26) -Convenient syntax for partial application (@pxref{SRFI-26}) - -@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 -package Jacal from Guile (@pxref{JACAL}). -@end table - - -@node Accessing Modules from C -@subsection Accessing Modules from C - -The last sections have described how modules are used in Scheme code, -which is the recommended way of creating and accessing modules. You -can also work with modules from C, but it is more cumbersome. - -The following procedures are available. - -@deftypefn {C Procedure} SCM scm_current_module () -Return the module that is the @emph{current module}. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_set_current_module (SCM @var{module}) -Set the current module to @var{module} and return the previous current -module. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_call_with_current_module (SCM @var{module}, SCM (*@var{func})(void *), void *@var{data}) -Call @var{func} and make @var{module} the current module during the -call. The argument @var{data} is passed to @var{func}. The return -value of @code{scm_c_call_with_current_module} is the return value of -@var{func}. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_lookup (const char *@var{name}) -Return the variable bound to the symbol indicated by @var{name} in the -current module. If there is no such binding or the symbol is not -bound to a variable, signal an error. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_lookup (SCM @var{name}) -Like @code{scm_c_lookup}, but the symbol is specified directly. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_module_lookup (SCM @var{module}, const char *@var{name}) -@deftypefnx {C Procedure} SCM scm_module_lookup (SCM @var{module}, SCM @var{name}) -Like @code{scm_c_lookup} and @code{scm_lookup}, but the specified -module is used instead of the current one. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_define (const char *@var{name}, SCM @var{val}) -Bind the symbol indicated by @var{name} to a variable in the current -module and set that variable to @var{val}. When @var{name} is already -bound to a variable, use that. Else create a new variable. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_define (SCM @var{name}, SCM @var{val}) -Like @code{scm_c_define}, but the symbol is specified directly. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_module_define (SCM @var{module}, const char *@var{name}, SCM @var{val}) -@deftypefnx {C Procedure} SCM scm_module_define (SCM @var{module}, SCM @var{name}, SCM @var{val}) -Like @code{scm_c_define} and @code{scm_define}, but the specified -module is used instead of the current one. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_module_reverse_lookup (SCM @var{module}, SCM @var{variable}) -Find the symbol that is bound to @var{variable} in @var{module}. When no such binding is found, return @var{#f}. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_define_module (const char *@var{name}, void (*@var{init})(void *), void *@var{data}) -Define a new module named @var{name} and make it current while -@var{init} is called, passing it @var{data}. Return the module. - -The parameter @var{name} is a string with the symbols that make up -the module name, separated by spaces. For example, @samp{"foo bar"} names -the module @samp{(foo bar)}. - -When there already exists a module named @var{name}, it is used -unchanged, otherwise, an empty module is created. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_resolve_module (const char *@var{name}) -Find the module name @var{name} and return it. When it has not -already been defined, try to auto-load it. When it can't be found -that way either, create an empty module. The name is interpreted as -for @code{scm_c_define_module}. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_resolve_module (SCM @var{name}) -Like @code{scm_c_resolve_module}, but the name is given as a real list -of symbols. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_use_module (const char *@var{name}) -Add the module named @var{name} to the uses list of the current -module, as with @code{(use-modules @var{name})}. The name is -interpreted as for @code{scm_c_define_module}. -@end deftypefn - -@deftypefn {C Procedure} SCM scm_c_export (const char *@var{name}, ...) -Add the bindings designated by @var{name}, ... to the public interface -of the current module. The list of names is terminated by -@code{NULL}. -@end deftypefn - -@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 gets done -with it. - -@deffn {Scheme Procedure} dynamic-link library -@deffnx {C Function} scm_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 {Scheme Procedure} dynamic-object? obj -@deffnx {C Function} scm_dynamic_object_p (obj) -Return @code{#t} if @var{obj} is a dynamic library handle, or @code{#f} -otherwise. -@end deffn - -@deffn {Scheme Procedure} dynamic-unlink dobj -@deffnx {C Function} scm_dynamic_unlink (dobj) -Unlink the indicated object file from the application. The -argument @var{dobj} must have been obtained by a call to -@code{dynamic-link}. After @code{dynamic-unlink} has been -called on @var{dobj}, its content is no longer accessible. -@end deffn - -@deffn {Scheme Procedure} dynamic-func name dobj -@deffnx {C Function} scm_dynamic_func (name, dobj) -Search the dynamic object @var{dobj} for the C function -indicated by the string @var{name} and return some Scheme -handle that can later be used with @code{dynamic-call} to -actually call the function. - -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 {Scheme Procedure} dynamic-call func dobj -@deffnx {C Function} scm_dynamic_call (func, dobj) -Call the C function indicated by @var{func} and @var{dobj}. -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{dobj}. -When @var{func} is a string , look it up in @var{dynobj}; this -is equivalent to -@smallexample -(dynamic-call (dynamic-func @var{func} @var{dobj}) #f) -@end smallexample - -Interrupts are deferred while the C function is executing (with -@code{SCM_DEFER_INTS}/@code{SCM_ALLOW_INTS}). -@end deffn - -@deffn {Scheme Procedure} dynamic-args-call func dobj args -@deffnx {C Function} scm_dynamic_args_call (func, dobj, args) -Call the C function indicated by @var{func} and @var{dobj}, -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 - -The new primitives that you add to Guile with -@code{scm_c_define_gsubr} (@pxref{Primitive Procedures}) or with any -of the other mechanisms are placed into the @code{(guile-user)} module -by default. However, it is also possible to put new primitives into -other modules. - -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{scm_c_define_gsubr} 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{scm_c_define_gsubr} for our new primitives. - -@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. - -@c FIXME::martin: Change all gh_ references to their scm_ equivalents. - -@smallexample -#include <math.h> -#include <libguile.h> - -SCM -j0_wrapper (SCM x) -@{ - return scm_double2num (j0 (scm_num2dbl (x, "j0"))); -@} - -void -init_math_bessel () -@{ - scm_c_define_gsubr ("j0", 1, 0, 0, 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{} (guile-user): 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{scm_c_define_gsubr} is called. - -A compiled module should have 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 replace @code{init_math_bessel} with the following code in -@file{bessel.c}: - -@smallexample -void -init_math_bessel (void *unused) -@{ - scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper); - scm_c_export ("j0", NULL); -@} - -void -scm_init_math_bessel_module () -@{ - scm_c_define_module ("math bessel", init_math_bessel, NULL); -@} -@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}. - -After @file{libbessel.so} has been rebuilt, we need to place the shared -library into the right place. - -Once the module has been correctly installed, it should be possible to -use it like this: - -@smallexample -guile> (load-extension "./libbessel.so" "scm_init_math_bessel_module") -guile> (use-modules (math bessel)) -guile> (j0 2) -0.223890779141236 -guile> (apropos "j0") -@print{} (math bessel): j0 #<primitive-procedure j0> -@end smallexample - -That's it! - -@node Variables -@section Variables -@tpindex Variables - -Each module has its own hash table, sometimes known as an @dfn{obarray}, -that maps the names defined in that module to their corresponding -variable objects. - -A variable is a box-like object that can hold any Scheme value. It is -said to be @dfn{undefined} if its box holds a special Scheme value that -denotes undefined-ness (which is different from all other Scheme values, -including for example @code{#f}); otherwise the variable is -@dfn{defined}. - -On its own, a variable object is anonymous. A variable is said to be -@dfn{bound} when it is associated with a name in some way, usually a -symbol in a module obarray. When this happens, the relationship is -mutual: the variable is bound to the name (in that module), and the name -(in that module) is bound to the variable. - -(That's the theory, anyway. In practice, defined-ness and bound-ness -sometimes get confused, because Lisp and Scheme implementations have -often conflated --- or deliberately drawn no distinction between --- a -name that is unbound and a name that is bound to a variable whose value -is undefined. We will try to be clear about the difference and explain -any confusion where it is unavoidable.) - -Variables do not have a read syntax. Most commonly they are created and -bound implicitly by @code{define} expressions: a top-level @code{define} -expression of the form - -@lisp -(define @var{name} @var{value}) -@end lisp - -@noindent -creates a variable with initial value @var{value} and binds it to the -name @var{name} in the current module. But they can also be created -dynamically by calling one of the constructor procedures -@code{make-variable} and @code{make-undefined-variable}. - -First-class variables are especially useful for interacting with the -current module system (@pxref{The Guile module system}). - -@deffn {Scheme Procedure} make-undefined-variable -@deffnx {C Function} scm_make_undefined_variable () -Return a variable that is initially unbound. -@end deffn - -@deffn {Scheme Procedure} make-variable init -@deffnx {C Function} scm_make_variable (init) -Return a variable initialized to value @var{init}. -@end deffn - -@deffn {Scheme Procedure} variable-bound? var -@deffnx {C Function} scm_variable_bound_p (var) -Return @code{#t} iff @var{var} is bound to a value. -Throws an error if @var{var} is not a variable object. -@end deffn - -@deffn {Scheme Procedure} variable-ref var -@deffnx {C Function} scm_variable_ref (var) -Dereference @var{var} and return its value. -@var{var} must be a variable object; see @code{make-variable} -and @code{make-undefined-variable}. -@end deffn - -@deffn {Scheme Procedure} variable-set! var val -@deffnx {C Function} scm_variable_set_x (var, val) -Set the value of the variable @var{var} to @var{val}. -@var{var} must be a variable object, @var{val} can be any -value. Return an unspecified value. -@end deffn - -@deffn {Scheme Procedure} variable? obj -@deffnx {C Function} scm_variable_p (obj) -Return @code{#t} iff @var{obj} is a variable object, else -return @code{#f}. -@end deffn - - -@c Local Variables: -@c TeX-master: "guile.texi" -@c End: diff --git a/doc/ref/scheme-options.texi b/doc/ref/scheme-options.texi index c8f5a4d41..e69de29bb 100644 --- a/doc/ref/scheme-options.texi +++ b/doc/ref/scheme-options.texi @@ -1,731 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@page -@node Options and Config -@chapter Configuration, Features and Runtime Options - -Why is my Guile different from your Guile? There are three kinds of -possible variation: - -@itemize @bullet -@item -build differences --- different versions of the Guile source code, -installation directories, configuration flags that control pieces of -functionality being included or left out, etc. - -@item -differences in dynamically loaded code --- behaviour and features -provided by modules that can be dynamically loaded into a running Guile - -@item -different runtime options --- some of the options that are provided for -controlling Guile's behaviour may be set differently. -@end itemize - -Guile provides ``introspective'' variables and procedures to query all -of these possible variations at runtime. For runtime options, it also -provides procedures to change the settings of options and to obtain -documentation on what the options mean. - -@menu -* Build Config:: Build and installation configuration. -* Feature Tracking:: Available features in the Guile process. -* Runtime Options:: Controlling Guile's runtime behaviour. -@end menu - - -@node Build Config -@section Configuration, Build and Installation - -The following procedures and variables provide information about how -Guile was configured, built and installed on your system. - -@deffn {Scheme Procedure} version -@deffnx {Scheme Procedure} effective-version -@deffnx {Scheme Procedure} major-version -@deffnx {Scheme Procedure} minor-version -@deffnx {Scheme Procedure} micro-version -@deffnx {C Function} scm_version () -@deffnx {C Function} scm_effective_version () -@deffnx {C Function} scm_major_version () -@deffnx {C Function} scm_minor_version () -@deffnx {C Function} scm_micro_version () -Return a string describing Guile's full version number, effective -version number, major, minor or micro version number, respectively. -The @code{effective-version} function returns the version name that -should remain unchanged during a stable series. Currently that means -that it omits the micro version. The effective version should be used -for items like the versioned share directory name -i.e. @file{/usr/share/guile/1.6/} - -@lisp -(version) @result{} "1.6.0" -(effective-version) @result{} "1.6" -(major-version) @result{} "1" -(minor-version) @result{} "6" -(micro-version) @result{} "0" -@end lisp -@end deffn - -@deffn {Scheme Procedure} %package-data-dir -@deffnx {C Function} scm_sys_package_data_dir () -Return the name of the directory under which Guile Scheme files in -general are stored. On Unix-like systems, this is usually -@file{/usr/local/share/guile} or @file{/usr/share/guile}. -@end deffn - -@deffn {Scheme Procedure} %library-dir -@deffnx {C Function} scm_sys_library_dir () -Return the name of the directory where the Guile Scheme files that -belong to the core Guile installation (as opposed to files from a 3rd -party package) are installed. On Unix-like systems, this is usually -@file{/usr/local/share/guile/<GUILE_EFFECTIVE_VERSION>} or -@file{/usr/share/guile/<GUILE_EFFECTIVE_VERSION>}, for example: -@file{/usr/local/share/guile/1.6}. -@end deffn - -@deffn {Scheme Procedure} %site-dir -@deffnx {C Function} scm_sys_site_dir () -Return the name of the directory where Guile Scheme files specific to -your site should be installed. On Unix-like systems, this is usually -@file{/usr/local/share/guile/site} or @file{/usr/share/guile/site}. -@end deffn - -@cindex GUILE_LOAD_PATH -@defvar %load-path -List of directories which should be searched for Scheme modules and -libraries. @code{%load-path} is initialized when Guile starts up to -@code{(list (%site-dir) (%library-dir) (%package-data-dir) ".")}, -prepended with the contents of the GUILE_LOAD_PATH environment variable, -if it is set. -@end defvar - -@deffn {Scheme Procedure} parse-path path [tail] -@deffnx {C Function} scm_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 {Scheme Procedure} search-path path filename [extensions] -@deffnx {C Function} scm_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 %guile-build-info -Alist of information collected during the building of a particular -Guile. Entries can be grouped into one of several categories: -directories, env vars, and versioning info. - -Briefly, here are the keys in @code{%guile-build-info}, by group: - -@cindex @code{srcdir} -@cindex @code{top_srcdir} -@cindex @code{prefix} -@cindex @code{exec_prefix} -@cindex @code{bindir} -@cindex @code{sbindir} -@cindex @code{libexecdir} -@cindex @code{datadir} -@cindex @code{sysconfdir} -@cindex @code{sharedstatedir} -@cindex @code{localstatedir} -@cindex @code{libdir} -@cindex @code{infodir} -@cindex @code{mandir} -@cindex @code{includedir} -@cindex @code{pkgdatadir} -@cindex @code{pkglibdir} -@cindex @code{pkgincludedir} -@table @asis -@item directories -srcdir, top_srcdir, prefix, exec_prefix, bindir, sbindir, libexecdir, -datadir, sysconfdir, sharedstatedir, localstatedir, libdir, infodir, -mandir, includedir, pkgdatadir, pkglibdir, pkgincludedir -@cindex @code{LIBS} -@item env vars -LIBS -@cindex @code{guileversion} -@cindex @code{libguileinterface} -@cindex @code{buildstamp} -@item versioning info -guileversion, libguileinterface, buildstamp -@end table - -Values are all strings. The value for @code{LIBS} is typically found -also as a part of "guile-config link" output. The value for -@code{guileversion} has form X.Y.Z, and should be the same as returned -by @code{(version)}. The value for @code{libguileinterface} is libtool -compatible and has form CURRENT:REVISION:AGE. The value for -@code{buildstamp} is the output of the date(1) command. - -In the source, @code{%guile-build-info} is initialized from -libguile/libpath.h, which is completely generated, so deleting this file -before a build guarantees up-to-date values for that build. -@end defvar - - -@node Feature Tracking -@section Feature Tracking - -Guile has a Scheme level variable @code{*features*} that keeps track to -some extent of the features that are available in a running Guile. -@code{*features*} is a list of symbols, for example @code{threads}, each -of which describes a feature of the running Guile process. - -@defvar *features* -A list of symbols describing available features of the Guile process. -@end defvar - -You shouldn't modify the @code{*features*} variable directly using -@code{set!}. Instead, see the procedures that are provided for this -purpose in the following subsection. - -@menu -* Feature Manipulation:: Checking for and advertising features. -* Common Feature Symbols:: Commonly available features. -@end menu - - -@node Feature Manipulation -@subsection Feature Manipulation - -To check whether a particular feature is available, use the -@code{provided?} procedure: - -@deffn {Scheme Procedure} provided? feature -@deffnx {Deprecated Scheme Procedure} feature? feature -Return @code{#t} if the specified @var{feature} is available, otherwise -@code{#f}. -@end deffn - -To advertise a feature from your own Scheme code, you can use the -@code{provide} procedure: - -@deffn {Scheme Procedure} provide feature -Add @var{feature} to the list of available features in this Guile -process. -@end deffn - -For C code, the equivalent function takes its feature name as a -@code{char *} argument for convenience: - -@deftypefn {C Function} void scm_add_feature (const char *str) -Add a symbol with name @var{str} to the list of available features in -this Guile process. -@end deftypefn - - -@node Common Feature Symbols -@subsection Common Feature Symbols - -In general, a particular feature may be available for one of two -reasons. Either because the Guile library was configured and compiled -with that feature enabled --- i.e. the feature is built into the library -on your system. Or because some C or Scheme code that was dynamically -loaded by Guile has added that feature to the list. - -In the first category, here are the features that the current version of -Guile may define (depending on how it is built), and what they mean. - -@table @code -@item array -Indicates support for arrays (@pxref{Arrays}). - -@item array-for-each -Indicates availability of @code{array-for-each} and other array mapping -procedures (@pxref{Array Mapping}). - -@item char-ready? -Indicates that the @code{char-ready?} function is available -(@pxref{Reading}). - -@item complex -Indicates support for complex numbers. - -@item current-time -Indicates availability of time-related functions: @code{times}, -@code{get-internal-run-time} and so on (@pxref{Time}). - -@item debug-extensions -Indicates that the debugging evaluator is available, together with the -options for controlling it. - -@item delay -Indicates support for promises (@pxref{Delayed Evaluation}). - -@item EIDs -Indicates that the @code{geteuid} and @code{getegid} really return -effective user and group IDs (@pxref{Processes}). - -@item inexact -Indicates support for inexact numbers. - -@item i/o-extensions -Indicates availability of the following extended I/O procedures: -@code{ftell}, @code{redirect-port}, @code{dup->fdes}, @code{dup2}, -@code{fileno}, @code{isatty?}, @code{fdopen}, -@code{primitive-move->fdes} and @code{fdes->ports} (@pxref{Ports and -File Descriptors}). - -@item net-db -Indicates availability of network database functions: -@code{scm_gethost}, @code{scm_getnet}, @code{scm_getproto}, -@code{scm_getserv}, @code{scm_sethost}, @code{scm_setnet}, @code{scm_setproto}, -@code{scm_setserv}, and their `byXXX' variants (@pxref{Network -Databases}). - -@item posix -Indicates support for POSIX functions: @code{pipe}, @code{getgroups}, -@code{kill}, @code{execl} and so on (@pxref{POSIX}). - -@item random -Indicates availability of random number generation functions: -@code{random}, @code{copy-random-state}, @code{random-uniform} and so on -(@pxref{Random}). - -@item reckless -Indicates that Guile was built with important checks omitted --- you -should never see this! - -@item regex -Indicates support for POSIX regular expressions using -@code{make-regexp}, @code{regexp-exec} and friends (@pxref{Regexp -Functions}). - -@item socket -Indicates availability of socket-related functions: @code{socket}, -@code{bind}, @code{connect} and so on (@pxref{Network Sockets and -Communication}). - -@item sort -Indicates availability of sorting and merging functions -(@pxref{Sorting}). - -@item system -Indicates that the @code{system} function is available -(@pxref{Processes}). - -@item threads -Indicates support for multithreading (@pxref{Threads}). - -@item values -Indicates support for multiple return values using @code{values} and -@code{call-with-values} (@pxref{Multiple Values}). -@end table - -Available features in the second category depend, by definition, on what -additional code your Guile process has loaded in. The following table -lists features that you might encounter for this reason. - -@table @code -@item defmacro -Indicates that the @code{defmacro} macro is available (@pxref{Macros}). - -@item describe -Indicates that the @code{(oop goops describe)} module has been loaded, -which provides a procedure for describing the contents of GOOPS -instances. - -@item readline -Indicates that Guile has loaded in Readline support, for command line -editing (@pxref{Readline Support}). - -@item record -Indicates support for record definition using @code{make-record-type} -and friends (@pxref{Records}). -@end table - -Although these tables may seem exhaustive, it is probably unwise in -practice to rely on them, as the correspondences between feature symbols -and available procedures/behaviour are not strictly defined. If you are -writing code that needs to check for the existence of some procedure, it -is probably safer to do so directly using the @code{defined?} procedure -than to test for the corresponding feature using @code{provided?}. - - -@node Runtime Options -@section Runtime Options - -Guile's runtime behaviour can be modified by setting options. For -example, is the language that Guile accepts case sensitive, or should -the debugger automatically show a backtrace on error? - -Guile has two levels of interface for managing options: a low-level -control interface, and a user-level interface which allows the enabling -or disabling of options. - -Moreover, the options are classified in groups according to whether they -configure @emph{reading}, @emph{printing}, @emph{debugging} or -@emph{evaluating}. - -@menu -* Low level options interfaces:: -* User level options interfaces:: -* Reader options:: -* Printing options:: -* Debugger options:: -* Evaluator options:: -* Evaluator trap options:: -* Examples of option use:: -@end menu - - -@node Low level options interfaces -@subsection Low Level Options Interfaces - -@deffn {Scheme Procedure} read-options-interface [setting] -@deffnx {Scheme Procedure} eval-options-interface [setting] -@deffnx {Scheme Procedure} print-options-interface [setting] -@deffnx {Scheme Procedure} debug-options-interface [setting] -@deffnx {Scheme Procedure} evaluator-traps-interface [setting] -@deffnx {C Function} scm_read_options (setting) -@deffnx {C Function} scm_eval_options_interface (setting) -@deffnx {C Function} scm_print_options (setting) -@deffnx {C Function} scm_debug_options (setting) -@deffnx {C Function} scm_evaluator_traps (setting) -If one of these procedures is called with no arguments (or with -@code{setting == SCM_UNDEFINED} in C code), it returns a list describing -the current setting of the read, eval, print, debug or evaluator traps -options respectively. The setting of a boolean option is indicated -simply by the presence or absence of the option symbol in the list. The -setting of a non-boolean option is indicated by the presence of the -option symbol immediately followed by the option's current value. - -If called with a list argument, these procedures interpret the list as -an option setting and modify the relevant options accordingly. [FIXME ---- this glosses over a lot of details!] - -If called with any other argument, such as @code{'help}, these -procedures return a list of entries like @code{(@var{OPTION-SYMBOL} -@var{DEFAULT-VALUE} @var{DOC-STRING})}, with each entry giving the -default value and documentation for each option symbol in the relevant -set of options. -@end deffn - - -@node User level options interfaces -@subsection User Level Options Interfaces - -@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 {Scheme Procedure} <group>-options [arg] -@deffnx {Scheme Procedure} read-options [arg] -@deffnx {Scheme Procedure} print-options [arg] -@deffnx {Scheme Procedure} debug-options [arg] -@deffnx {Scheme 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 {Scheme Procedure} <group>-enable option-symbol -@deffnx {Scheme Procedure} read-enable option-symbol -@deffnx {Scheme Procedure} print-enable option-symbol -@deffnx {Scheme Procedure} debug-enable option-symbol -@deffnx {Scheme 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 {Scheme Procedure} <group>-disable option-symbol -@deffnx {Scheme Procedure} read-disable option-symbol -@deffnx {Scheme Procedure} print-disable option-symbol -@deffnx {Scheme Procedure} debug-disable option-symbol -@deffnx {Scheme 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 -@subsection 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 -@subsection 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 -@subsection 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 -@subsection 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 -@subsection 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 - -@subsubsection Stack overflow - -@cindex overflow, stack -@cindex stack overflow -Stack overflow errors are caused by a computation trying to use more -stack space than has been enabled by the @code{stack} option. They are -reported like this: - -@lisp -(non-tail-recursive-factorial 500) -@print{} -ERROR: Stack overflow -ABORT: (stack-overflow) -@end lisp - -If you get an error like this, you can either try rewriting your code to -use less stack space, or increase the maximum stack size. To increase -the maximum stack size, use @code{debug-set!}, for example: - -@lisp -(debug-set! stack 200000) -@result{} -(show-file-name #t stack 200000 debug backtrace depth 20 maxdepth 1000 frames 3 indent 10 width 79 procnames cheap) - -(non-tail-recursive-factorial 500) -@result{} -122013682599111006870123878542304692625357434@dots{} -@end lisp - -If you prefer to try rewriting your code, you may be able to save stack -space by making some of your procedures @dfn{tail recursive}. For a -description of what this means, see @ref{Proper tail -recursion,,,r5rs,The Revised^5 Report on Scheme}. - - -@node Examples of option use -@subsection 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 - - -@c Local Variables: -@c TeX-master: "guile.texi" -@c End: diff --git a/doc/ref/scheme-procedures.texi b/doc/ref/scheme-procedures.texi index 0cf418843..e69de29bb 100644 --- a/doc/ref/scheme-procedures.texi +++ b/doc/ref/scheme-procedures.texi @@ -1,859 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@page -@node Procedures and Macros -@chapter Procedures and Macros - -@menu -* Lambda:: Basic procedure creation using lambda. -* Primitive Procedures:: Procedures defined in C. -* Optional Arguments:: Handling keyword, optional and rest arguments. -* Procedure Properties:: Procedure properties and meta-information. -* 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 -@cindex lambda - -@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 variables 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 - -The list in @var{variable} or @var{variablen+1} is always newly -created and the procedure can modify it if desired. This is the case -even when the procedure is invoked via @code{apply}, the required part -of the list argument there will be copied (@pxref{Fly Evaluation,, -Procedures for On the Fly Evaluation}). - -@var{body} is a sequence of Scheme expressions which are evaluated in -order when the procedure is invoked. -@end deffn - -@node Primitive Procedures -@section Primitive Procedures -@cindex primitives -@cindex primitive procedures - -Procedures written in C can be registered for use from Scheme, -provided they take only arguments of type @code{SCM} and return -@code{SCM} values. @code{scm_c_define_gsubr} is likely to be the most -useful mechanism, combining the process of registration -(@code{scm_c_make_gsubr}) and definition (@code{scm_define}). - -@deftypefun SCM scm_c_make_gsubr (const char *name, int req, int opt, int rst, fcn) -Register a C procedure @var{FCN} as a ``subr'' --- a primitive -subroutine that can be called from Scheme. It will be associated with -the given @var{name} but no environment binding will be created. The -arguments @var{req}, @var{opt} and @var{rst} specify the number of -required, optional and ``rest'' arguments respectively. The total -number of these arguments should match the actual number of arguments -to @var{fcn}. The number of rest arguments should be 0 or 1. -@code{scm_c_make_gsubr} returns a value of type @code{SCM} which is a -``handle'' for the procedure. -@end deftypefun - -@deftypefun SCM scm_c_define_gsubr (const char *name, int req, int opt, int rst, fcn) -Register a C procedure @var{FCN}, as for @code{scm_c_make_gsubr} -above, and additionally create a top-level Scheme binding for the -procedure in the ``current environment'' using @code{scm_define}. -@code{scm_c_define_gsubr} returns a handle for the procedure in the -same way as @code{scm_c_make_gsubr}, which is usually not further -required. -@end deftypefun - -@code{scm_c_make_gsubr} and @code{scm_c_define_gsubr} automatically -use @code{scm_c_make_subr} and also @code{scm_makcclo} if necessary. -It is advisable to use the gsubr variants since they provide a -slightly higher-level abstraction of the Guile implementation. - -@node Optional Arguments -@section Optional Arguments - -@c FIXME::martin: Review me! - -Scheme procedures, as defined in R5RS, can either 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: - -@cindex @code{optargs} -@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 {library 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 -@code{#f} 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 occurrences, one or more occurrences, and one -or zero occurrences. - -@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 -parameter 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 -bound to @code{#f}. - -@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 - - -@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 -argument @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 parameter 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 Meta-information - -@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 meta-information 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 {Scheme Procedure} procedure? obj -@deffnx {C Function} scm_procedure_p (obj) -Return @code{#t} if @var{obj} is a procedure. -@end deffn - -@deffn {Scheme Procedure} closure? obj -@deffnx {C Function} scm_closure_p (obj) -Return @code{#t} if @var{obj} is a closure. -@end deffn - -@deffn {Scheme Procedure} thunk? obj -@deffnx {C Function} scm_thunk_p (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 {Scheme Procedure} procedure-name proc -@deffnx {C Function} scm_procedure_name (proc) -Return the name of the procedure @var{proc} -@end deffn - -@deffn {Scheme Procedure} procedure-source proc -@deffnx {C Function} scm_procedure_source (proc) -Return the source of the procedure @var{proc}. -@end deffn - -@deffn {Scheme Procedure} procedure-environment proc -@deffnx {C Function} scm_procedure_environment (proc) -Return the environment of the procedure @var{proc}. -@end deffn - -@deffn {Scheme Procedure} procedure-properties proc -@deffnx {C Function} scm_procedure_properties (proc) -Return @var{obj}'s property list. -@end deffn - -@deffn {Scheme Procedure} procedure-property obj key -@deffnx {C Function} scm_procedure_property (obj, key) -Return the property of @var{obj} with name @var{key}. -@end deffn - -@deffn {Scheme Procedure} set-procedure-properties! proc alist -@deffnx {C Function} scm_set_procedure_properties_x (proc, alist) -Set @var{obj}'s property list to @var{alist}. -@end deffn - -@deffn {Scheme Procedure} set-procedure-property! obj key value -@deffnx {C Function} scm_set_procedure_property_x (obj, key, value) -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 {Scheme Procedure} procedure-documentation proc -@deffnx {C Function} scm_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 {Scheme Procedure} set-source-properties! obj plist -@deffnx {C Function} scm_set_source_properties_x (obj, plist) -Install the association list @var{plist} as the source property -list for @var{obj}. -@end deffn - -@deffn {Scheme Procedure} set-source-property! obj key datum -@deffnx {C Function} scm_set_source_property_x (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 {Scheme Procedure} source-properties obj -@deffnx {C Function} scm_source_properties (obj) -Return the source property association list of @var{obj}. -@end deffn - - -@deffn {Scheme Procedure} source-property obj key -@deffnx {C Function} scm_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 accessor 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 {Scheme Procedure} make-procedure-with-setter procedure setter -@deffnx {C Function} scm_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 {Scheme Procedure} procedure-with-setter? obj -@deffnx {C Function} scm_procedure_with_setter_p (obj) -Return @code{#t} if @var{obj} is a procedure with an -associated setter procedure. -@end deffn - -@deffn {Scheme Procedure} procedure proc -@deffnx {C Function} scm_procedure (proc) -Return the procedure of @var{proc}, which must be either a -procedure with setter, or an operator struct. -@end deffn - -@deffn {Scheme Procedure} 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 -@cindex R5RS 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 - -@cindex @code{syncase} -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-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 include the form -@code{#:use-syntax (ice-9 syncase)} 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 flavors of macros. The three -flavors 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 flavor 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 {Scheme Procedure} procedure->syntax code -@deffnx {C Function} scm_makacro (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 {Scheme Procedure} procedure->macro code -@deffnx {C Function} scm_makmacro (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 {Scheme Procedure} procedure->memoizing-macro code -@deffnx {C Function} scm_makmmacro (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} flavor macros are referred to -as @dfn{syntax transformers}. - -@deffn {Scheme Procedure} macro? obj -@deffnx {C Function} scm_macro_p (obj) -Return @code{#t} if @var{obj} is a regular macro, a memoizing macro or a -syntax transformer. -@end deffn - -@deffn {Scheme Procedure} macro-type m -@deffnx {C Function} scm_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 {Scheme Procedure} macro-name m -@deffnx {C Function} scm_macro_name (m) -Return the name of the macro @var{m}. -@end deffn - -@deffn {Scheme Procedure} macro-transformer m -@deffnx {C Function} scm_macro_transformer (m) -Return the transformer of the macro @var{m}. -@end deffn - -@deffn {Scheme Procedure} cons-source xorig x y -@deffnx {C Function} scm_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: diff --git a/doc/ref/scheme-reading.texi b/doc/ref/scheme-reading.texi index 16ef72cca..8b0e434db 100644 --- a/doc/ref/scheme-reading.texi +++ b/doc/ref/scheme-reading.texi @@ -6,7 +6,7 @@ @page @node Further Reading -@chapter Further Reading +@section Further Reading @itemize @bullet diff --git a/doc/ref/scheme-scheduling.texi b/doc/ref/scheme-scheduling.texi index 351945660..e69de29bb 100644 --- a/doc/ref/scheme-scheduling.texi +++ b/doc/ref/scheme-scheduling.texi @@ -1,863 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@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:: Thread-local variables. -* Futures:: Delayed execution in new threads. -* Parallel Forms:: Parallel execution of forms. -@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 {Scheme Procedure} make-arbiter name -@deffnx {C Function} scm_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 {Scheme Procedure} try-arbiter arb -@deffnx {C Function} scm_try_arbiter (arb) -Return @code{#t} and lock the arbiter @var{arb} if the arbiter -was unlocked. Otherwise, return @code{#f}. -@end deffn - -@deffn {Scheme Procedure} release-arbiter arb -@deffnx {C Function} scm_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 user asyncs -@cindex system asyncs - -Asyncs are a means of deferring the excution of Scheme code until it is -safe to do so. - -Guile provides two kinds of asyncs that share the basic concept but are -otherwise quite different: system asyncs and user asyncs. System asyncs -are integrated into the core of Guile and are executed automatically -when the system is in a state to allow the execution of Scheme code. -For example, it is not possible to execute Scheme code in a POSIX signal -handler, but such a signal handler can queue a system async to be -executed in the near future, when it is safe to do so. - -System asyncs can also be queued for threads other than the current one. -This way, you can cause threads to asynchronously execute arbitrary -code. - -User asyncs offer a convenient means of queueing procedures for future -execution and triggering this execution. They will not be executed -automatically. - -@menu -* System asyncs:: -* User asyncs:: -@end menu - -@node System asyncs -@subsection System asyncs - -To cause the future asynchronous execution of a procedure in a given -thread, use @code{system-async-mark}. - -Automatic invocation of system asyncs can be temporarily disabled by -calling @code{call-with-blocked-asyncs}. This function works by -temporarily increasing the @emph{async blocking level} of the current -thread while a given procedure is running. The blocking level starts -out at zero, and whenever a safe point is reached, a blocking level -greater than zero will prevent the execution of queued asyncs. - -Analogously, the procedure @code{call-with-unblocked-asyncs} will -temporarily decrease the blocking level of the current thread. You -can use it when you want to disable asyncs by default and only allow -them temporarily. - -In addition to the C versions of @code{call-with-blocked-asyncs} and -@code{call-with-unblocked-asyncs}, C code can use -@code{scm_with_blocked_asyncs} and @code{scm_with_unblocked_asyncs} -inside a @dfn{frame} (@pxref{Frames}) to block or unblock system asyncs -temporarily. - -@deffn {Scheme Procedure} system-async-mark proc [thread] -@deffnx {C Function} scm_system_async_mark (proc) -@deffnx {C Function} scm_system_async_mark_for_thread (proc, thread) -Mark @var{proc} (a procedure with zero arguments) for future execution -in @var{thread}. When @var{proc} has already been marked for -@var{thread} but has not been executed yet, this call has no effect. -When @var{thread} is omitted, the thread that called -@code{system-async-mark} is used. - -This procedure is not safe to be called from signal handlers. Use -@code{scm_sigaction} or @code{scm_sigaction_for_thread} to install -signal handlers. -@end deffn - -@c FIXME: The use of @deffnx for scm_c_call_with_blocked_asyncs and -@c scm_c_call_with_unblocked_asyncs puts "void" into the function -@c index. Would prefer to use @deftypefnx if makeinfo allowed that, -@c or a @deftypefn with an empty return type argument if it didn't -@c introduce an extra space. - -@deffn {Scheme Procedure} call-with-blocked-asyncs proc -@deffnx {C Function} scm_call_with_blocked_asyncs (proc) -@deffnx {C Function} void *scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data) -@findex scm_c_call_with_blocked_asyncs -Call @var{proc} and block the execution of system asyncs by one level -for the current thread while it is running. Return the value returned -by @var{proc}. For the first two variants, call @var{proc} with no -arguments; for the third, call it with @var{data}. -@end deffn - -@deffn {Scheme Procedure} call-with-unblocked-asyncs proc -@deffnx {C Function} scm_call_with_unblocked_asyncs (proc) -@deffnx {C Function} void *scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d) -@findex scm_c_call_with_unblocked_asyncs -Call @var{proc} and unblock the execution of system asyncs by one -level for the current thread while it is running. Return the value -returned by @var{proc}. For the first two variants, call @var{proc} -with no arguments; for the third, call it with @var{data}. -@end deffn - -@deftypefn {C Function} void scm_frame_block_asyncs () -This function must be used inside a pair of calls to -@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}). -During the dynamic extent of the frame, asyncs are blocked by one level. -@end deftypefn - -@deftypefn {C Function} void scm_frame_unblock_asyncs () -This function must be used inside a pair of calls to -@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}). -During the dynamic extent of the frame, asyncs are unblocked by one -level. -@end deftypefn - -@node User asyncs -@subsection User asyncs - -A user async is a pair of a thunk (a parameterless procedure) and a -mark. Setting the mark on a user async will cause the thunk to be -executed when the user async is passed to @code{run-asyncs}. Setting -the mark more than once is satisfied by one execution of the thunk. - -User asyncs are created with @code{async}. They are marked with -@code{async-mark}. - -@deffn {Scheme Procedure} async thunk -@deffnx {C Function} scm_async (thunk) -Create a new user async for the procedure @var{thunk}. -@end deffn - -@deffn {Scheme Procedure} async-mark a -@deffnx {C Function} scm_async_mark (a) -Mark the user async @var{a} for future execution. -@end deffn - -@deffn {Scheme Procedure} run-asyncs list_of_a -@deffnx {C Function} scm_run_asyncs (list_of_a) -Execute all thunks from the marked asyncs of the list @var{list_of_a}. -@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 {Scheme Procedure} call-with-dynamic-root thunk handler -@deffnx {C Function} scm_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 {Scheme Procedure} dynamic-root -@deffnx {C Function} scm_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 {Scheme 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 {Scheme 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 {Scheme 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 -@cindex POSIX threads - -Guile threads are implemented using POSIX threads, they run -pre-emptively and concurrently through both Scheme code and system -calls. The only exception is for garbage collection, where all -threads must rendezvous. - -@menu -* Low level thread primitives:: -* Higher level thread procedures:: -* C level thread interface:: -@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 {Scheme Procedure} 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. 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 {Scheme Procedure} 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 {Scheme Procedure} yield -If one or more threads are waiting to execute, calling yield forces an -immediate context switch to one of them. Otherwise, yield has no effect. -@end deffn - -@c begin (texi-doc-string "guile" "make-mutex") -@deffn {Scheme Procedure} make-mutex -Create a new mutex object. -@end deffn - -@c begin (texi-doc-string "guile" "lock-mutex") -@deffn {Scheme Procedure} 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}. Locking a mutex that -a thread already owns will succeed right away and will not block the -thread. That is, Guile's mutexes are @emph{recursive}. - -When a system async is activated for a thread that is blocked in a -call to @code{lock-mutex}, the waiting is interrupted and the async is -executed. When the async returns, the waiting is resumed. -@end deffn - -@deffn {Scheme Procedure} try-mutex mutex -Try to lock @var{mutex}. If the mutex is already locked by someone -else, return @code{#f}. Else lock the mutex and return @code{#t}. -@end deffn - -@c begin (texi-doc-string "guile" "unlock-mutex") -@deffn {Scheme Procedure} 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. Every call to @code{lock-mutex} by this thread must be matched -with a call to @code{unlock-mutex}. Only the last call to -@code{unlock-mutex} will actually unlock the mutex. -@end deffn - -@c begin (texi-doc-string "guile" "make-condition-variable") -@deffn {Scheme Procedure} make-condition-variable -Make a new condition variable. -@end deffn - -@c begin (texi-doc-string "guile" "wait-condition-variable") -@deffn {Scheme Procedure} wait-condition-variable cond-var mutex [time] -Wait until @var{cond-var} has been signalled. While waiting, -@var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and -is locked again when this function returns. When @var{time} is given, -it specifies a point in time where the waiting should be aborted. It -can be either a integer as returned by @code{current-time} or a pair -as returned by @code{gettimeofday}. When the waiting is aborted, -@code{#f} is returned. When the condition variable has in fact been -signalled, @code{#t} is returned. The mutex is re-locked in any case -before @code{wait-condition-variable} returns. - -When a system async is activated for a thread that is blocked in a -call to @code{wait-condition-variable}, the waiting is interrupted, -the mutex is locked, and the async is executed. When the async -returns, the mutex is unlocked again and the waiting is resumed. -@end deffn - -@c begin (texi-doc-string "guile" "signal-condition-variable") -@deffn {Scheme Procedure} signal-condition-variable cond-var -Wake up one thread that is waiting for @var{cv}. -@end deffn - -@c begin (texi-doc-string "guile" "broadcast-condition-variable") -@deffn {Scheme Procedure} broadcast-condition-variable cond-var -Wake up all threads that are waiting for @var{cv}. -@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 macro make-thread proc [args@dots{}] -Apply @var{proc} to @var{args} in a new thread formed by -@code{call-with-new-thread} using a default error handler that display -the error to the current error port. -@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 a default error handler that display -the error to the current error port. -@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 body@dots{} -Evaluate @var{body}, with a mutex locked so only one thread can -execute that code at any one time. Each @code{monitor} form has its -own private mutex and the locking is done as per @code{with-mutex} -above. The return value is the return from the last form in -@var{body}. - -The term ``monitor'' comes from operating system theory, where it -means a particular bit of code managing access to some resource and -which only ever executes on behalf of one process at any one time. -@end deffn - -@node C level thread interface -@subsection C level thread interface - -You can create and manage threads, mutexes, and condition variables -with the C versions of the primitives above. For example, you can -create a mutex with @code{scm_make_mutex} and lock it with -@code{scm_lock_mutex}. In addition to these primitives there is also -a second set of primitives for threading related things. These -functions and data types are only available from C and can not be -mixed with the first set from above. However, they might be more -efficient and can be used in situations where Scheme data types are -not allowed or are inconvenient to use. - -Furthermore, they are the primitives that Guile relies on for its own -higher level threads. By reimplementing them, you can adapt Guile to -different low-level thread implementations. - -C code in a thread must call a libguile function periodically. When -one thread finds garbage collection is required, it waits for all -threads to rendezvous before doing that GC. Such a rendezvous is -checked within libguile functions. If C code wants to sleep or block -in a thread it should use one of the libguile functions provided. - -Only threads created by Guile can use the libguile functions. Threads -created directly with say @code{pthread_create} are unknown to Guile -and they cannot call libguile. The stack in such foreign threads is -not scanned during GC, so @code{SCM} values generally cannot be held -there. - -@c FIXME: -@c -@c Describe SCM_TICK which can be called if no other libguile -@c function is being used by a C function. -@c -@c Describe "Guile mode", which a thread can enter and exit. There -@c are no functions for doing this yet. -@c -@c When in guile mode a thread can call libguile, is subject to the -@c tick rule, and its stack is scanned. When not in guile mode it -@c cannot call libguile, it doesn't have to tick, and its stack is -@c not scanned. The strange guile control flow things like -@c exceptions, continuations and asyncs only occur when in guile -@c mode. -@c -@c When guile mode is exited, the portion of the stack allocated -@c while it was in guile mode is still scanned. This portion may not -@c be modified when outside guile mode. The stack ends up -@c partitioned into alternating guile and non-guile regions. -@c -@c Leaving guile mode is convenient when running an extended -@c calculation not involving guile, since one doesn't need to worry -@c about SCM_TICK calls. - - -@deftp {C Data Type} scm_t_thread -This data type represents a thread, to be used with scm_thread_create, -etc. -@end deftp - -@deftypefn {C Function} int scm_thread_create (scm_t_thread *t, void (*proc)(void *), void *data) -Create a new thread that will start by calling @var{proc}, passing it -@var{data}. A handle for the new thread is stored in @var{t}, which -must be non-NULL. The thread terminated when @var{proc} returns. -When the thread has not been detached, its handle remains valid after -is has terminated so that it can be used with @var{scm_thread_join}, -for example. When it has been detached, the handle becomes invalid as -soon as the thread terminates. -@end deftypefn - -@deftypefn {C Function} void scm_thread_detach (scm_t_thread t) -Detach the thread @var{t}. See @code{scm_thread_create}. -@end deftypefn - -@deftypefn {C Function} void scm_thread_join (scm_t_thread t) -Wait for thread @var{t} to terminate. The thread must not have been -detached at the time that @code{scm_thread_join} is called, but it -might have been detached by the time it terminates. -@end deftypefn - -@deftypefn {C Function} scm_t_thread scm_thread_self () -Return the handle of the calling thread. -@end deftypefn - -@deftp {C Data Type} scm_t_mutex -This data type represents a mutex, to be used with scm_mutex_init, -etc. -@end deftp - -@deftypefn {C Function} void scm_mutex_init (scm_t_mutex *m) -Initialize the mutex structure pointed to by @var{m}. -@end deftypefn - -@deftypefn {C Function} void scm_mutex_destroy (scm_t_mutex *m) -Deallocate all resources associated with @var{m}. -@end deftypefn - -@deftypefn {C Function} void scm_mutex_lock (scm_t_mutex *m) -Lock the mutex @var{m}. When it is already locked by a different -thread, wait until it becomes available. Locking a mutex that is -already locked by the current threads is not allowd and results in -undefined behavior. The mutices are not guaranteed to be fair. That -is, a thread that attempts a lock after yourself might be granted it -before you. -@end deftypefn - -@deftypefn {C Function} int scm_mutex_trylock (scm_t_mutex *m) -Lock @var{m} as with @code{scm_mutex_lock} but don't wait when this -does succeed immediately. Returns non-zero when the mutex could in -fact be locked , and zero when it is already locked by some other -thread. -@end deftypefn - -@deftypefn {C Function} void scm_mutex_unlock (scm_t_mutex *m) -Unlock the mutex @var{m}. The mutex must have been locked by the -current thread, else the behavior is undefined. -@end deftypefn - -@deftp {C Data Type} scm_t_cond -This data type represents a condition variable, to be used with -scm_cond_init, etc. -@end deftp - -@deftypefn {C Function} void scm_cond_init (scm_t_cond *c) -Initialize the mutex structure pointed to by @var{c}. -@end deftypefn - -@deftypefn {C Function} void scm_cond_destroy (scm_t_cond *c) -Deallocate all resources associated with @var{c}. -@end deftypefn - -@deftypefn {C Function} void scm_cond_wait (scm_t_cond *c, scm_t_mutex *m) -Wait for @var{c} to be signalled. While waiting @var{m} is unlocked -and locked again before @code{scm_cond_wait} returns. -@end deftypefn - -@deftypefn {C Function} void scm_cond_timedwait (scm_t_cond *c, scm_t_mutex *m, timespec *abstime) -Wait for @var{c} to be signalled as with @code{scm_cond_wait} but -don't wait longer than the point in time specified by @var{abstime}. -when the waiting is aborted, zero is returned; non-zero else. -@end deftypefn - -@deftypefn {C Function} void scm_cond_signal (scm_t_cond *c) -Signal the condition variable @var{c}. When one or more threads are -waiting for it to be signalled, select one arbitrarily and let its -wait succeed. -@end deftypefn - -@deftypefn {C Function} void scm_cond_broadcast (scm_t_cond *c) -Signal the condition variable @var{c}. When there are threads waiting -for it to be signalled, wake them all up and make all their waits -succeed. -@end deftypefn - -@deftp {C Type} scm_t_key -This type represents a key for a thread-specific value. -@end deftp - -@deftypefn {C Function} void scm_key_create (scm_t_key *keyp) -Create a new key for a thread-specific value. Each thread has its own -value associated to such a handle. The new handle is stored into -@var{keyp}, which must be non-NULL. -@end deftypefn - -@deftypefn {C Function} void scm_key_delete (scm_t_key key) -This function makes @var{key} invalid as a key for thread-specific data. -@end deftypefn - -@deftypefn {C Function} void scm_key_setspecific (scm_t_key key, const void *value) -Associate @var{value} with @var{key} in the calling thread. -@end deftypefn - -@deftypefn {C Function} int scm_key_getspecific (scm_t_key key) -Return the value currently associated with @var{key} in the calling -thread. When @code{scm_key_setspecific} has not yet been called in -this thread with this key, @code{NULL} is returned. -@end deftypefn - -@deftypefn {C Function} int scm_thread_select (...) -This function does the same thing as the system's @code{select} -function, but in a way that is friendly to the thread implementation. -You should call it in preference to the system @code{select}. -@end deftypefn - -@node Fluids -@section Fluids - -@cindex fluids - -Fluids are objects to store values in. They have a few properties -which make them useful in certain situations: Fluids can have one -value per dynamic root (@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 the desirable effects of dynamically -scoped variables. Dynamically scoped variables are useful when you -want to set a variable to a value during some dynamic extent in the -execution of your program and have them revert to their original value -when the control flow is outside of this dynamic extent. 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. The values -stored in a fluid can be accessed with @code{fluid-ref} and -@code{fluid-set!}. - -@deffn {Scheme Procedure} make-fluid -@deffnx {C Function} scm_make_fluid () -Return a newly created fluid. -Fluids are objects of a certain type (a smob) that can hold one SCM -value per dynamic root. That is, modifications to this value are -only visible to code that executes within the same dynamic root as -the modifying code. When a new dynamic root is constructed, it -inherits the values from its parent. Because each thread executes -in its own dynamic root, you can use fluids for thread local storage. -@end deffn - -@deffn {Scheme Procedure} fluid? obj -@deffnx {C Function} scm_fluid_p (obj) -Return @code{#t} iff @var{obj} is a fluid; otherwise, return -@code{#f}. -@end deffn - -@deffn {Scheme Procedure} fluid-ref fluid -@deffnx {C Function} scm_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 {Scheme Procedure} fluid-set! fluid value -@deffnx {C Function} scm_fluid_set_x (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 {Scheme Procedure} with-fluids* fluids values thunk -@deffnx {C Function} scm_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 -in the order given. @var{thunk} must be a procedure with no argument. -it is called inside a @code{dynamic-wind} and the fluids are -set/restored when control enter or leaves the established dynamic -extent. -@end deffn - -@deffn {Scheme Macro} with-fluids ((fluid value) ...) body... -Execute @var{body...} while each @var{fluid} is set to the -corresponding @var{value}. Both @var{fluid} and @var{value} are -evaluated and @var{fluid} must yield a fluid. @var{body...} is -executed inside a @code{dynamic-wind} and the fluids are set/restored -when control enter or leaves the established dynamic extent. -@end deffn - -@deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data) -@deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data) -The function @code{scm_c_with_fluids} is like @code{scm_with_fluids} -except that it takes a C function to call instead of a Scheme thunk. - -The function @code{scm_c_with_fluid} is similar but only allows one -fluid to be set instead of a list. -@end deftypefn - -@deftypefn {C Function} void scm_frame_fluid (SCM fluid, SCM val) -This function must be used inside a pair of calls to -@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}). -During the dynamic extent of the frame, the fluid @var{fluid} is set -to @var{val}. - -More precisely, the value of the fluid is swapped with a `backup' -value whenever the frame is entered or left. The backup value is -initialized with the @var{val} argument. -@end deftypefn - -@node Futures -@section Futures -@cindex futures - -Futures are a convenient way to run a calculation in a new thread, and -only wait for the result when it's actually needed. - -Futures are similar to promises (@pxref{Delayed Evaluation}), in that -they allow mainline code to continue immediately. But @code{delay} -doesn't evaluate at all until forced, whereas @code{future} starts -immediately in a new thread. - -@deffn {syntax} future expr -Begin evaluating @var{expr} in a new thread, and return a ``future'' -object representing the calculation. -@end deffn - -@deffn {Scheme Procedure} make-future thunk -@deffnx {C Function} scm_make_future (thunk) -Begin evaluating the call @code{(@var{thunk})} in a new thread, and -return a ``future'' object representing the calculation. -@end deffn - -@deffn {Scheme Procedure} future-ref f -@deffnx {C Function} scm_future_ref (f) -Return the value computed by the future @var{f}. If @var{f} has not -yet finished executing then wait for it to do so. -@end deffn - - -@node Parallel Forms -@section Parallel forms -@cindex parallel forms - -The functions described in this section are available from - -@example -(use-modules (ice-9 threads)) -@end example - -@deffn syntax parallel expr1 @dots{} exprN -Evaluate each @var{expr} expression in parallel, each in a new thread. -Return the results as a set of @var{N} multiple values -(@pxref{Multiple Values}). -@end deffn - -@deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{} -Evaluate each @var{expr} in parallel, each in a new thread, then bind -the results to the corresponding @var{var} variables and evaluate -@var{body}. - -@code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the -expressions for the bindings are evaluated in parallel. -@end deffn - -@deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN -@deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN -Call @var{proc} on the elements of the given lists. @code{par-map} -returns a list comprising the return values from @var{proc}. -@code{par-for-each} returns an unspecified value, but waits for all -calls to complete. - -The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{} -@var{elemN})}, where each @var{elem} is from the corresponding -@var{lst}. Each @var{lst} must be the same length. The calls are -made in parallel, each in a new thread. - -These functions are like @code{map} and @code{for-each} (@pxref{List -Mapping}), but make their @var{proc} calls in parallel. -@end deffn - -@deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN -@deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN -Call @var{proc} on the elements of the given lists, in the same way as -@code{par-map} and @code{par-for-each} above, but use no more than -@var{n} new threads at any one time. The order in which calls are -initiated within that threads limit is unspecified. - -These functions are good for controlling resource consumption if -@var{proc} calls might be costly, or if there are many to be made. On -a dual-CPU system for instance @math{@var{n}=4} might be enough to -keep the CPUs utilized, and not consume too much memory. -@end deffn - -@deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN -Apply @var{pproc} to the elements of the given lists, and apply -@var{sproc} to each result returned by @var{pproc}. The final return -value is unspecified, but all calls will have been completed before -returning. - -The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{} -@var{elemN}))}, where each @var{elem} is from the corresponding -@var{lst}. Each @var{lst} must have the same number of elements. - -The @var{pproc} calls are made in parallel, in new threads. No more -than @var{n} new threads are used at any one time. The order in which -@var{pproc} calls are initiated within that limit is unspecified. - -The @var{sproc} calls are made serially, in list element order, one at -a time. @var{pproc} calls on later elements may execute in parallel -with the @var{sproc} calls. Exactly which thread makes each -@var{sproc} call is unspecified. - -This function is designed for individual calculations that can be done -in parallel, but with results needing to be handled serially, for -instance to write them to a file. The @var{n} limit on threads -controls system resource usage when there are many calculations or -when they might be costly. - -It will be seen that @code{n-for-each-par-map} is like a combination -of @code{n-par-map} and @code{for-each}, - -@example -(for-each sproc (n-par-map pproc lst1 ... lstN)) -@end example - -@noindent -But the actual implementation is more efficient since each @var{sproc} -call, in turn, can be initiated once the relevant @var{pproc} call has -completed, it doesn't need to wait for all to finish. -@end deffn - - -@c Local Variables: -@c TeX-master: "guile.texi" -@c End: diff --git a/doc/ref/scheme-scm.texi b/doc/ref/scheme-scm.texi new file mode 100644 index 000000000..97b5bc97a --- /dev/null +++ b/doc/ref/scheme-scm.texi @@ -0,0 +1,45 @@ +@c -*-texinfo-*- +@c This is part of the GNU Guile Reference Manual. +@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 +@c Free Software Foundation, Inc. +@c See the file guile.texi for copying conditions. + + +@node The @code{SCM} Type +@section The @code{SCM} Type + +Guile represents all Scheme values with the single C type @code{SCM}. +For an introduction to this topic, @xref{Dynamic Types}. + +@deftp {C Type} SCM +@code{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 @code{SCM}, so you should only use macros and functions to work +with @code{SCM} values. Values are converted between C data types and +the @code{SCM} type with utility functions and macros. +@end deftp +@cindex SCM data type + +@deftp {C Type} scm_t_bits +@code{scm_t_bits} is an unsigned 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 mostly used to +implement Guile's internals, the use of this type is also necessary to +write certain kinds of extensions to Guile. +@end deftp + +@deftp {C Type} scm_t_signed_bits +This is a signed integral type of the same size as @code{scm_t_bits}. +@end deftp + +@deftypefn {C Macro} scm_t_bits SCM_UNPACK (SCM @var{x}) +Transforms the @code{SCM} value @var{x} into its representation as an +integral type. Only after applying @code{SCM_UNPACK} it is possible to +access the bits and contents of the @code{SCM} value. +@end deftypefn + +@deftypefn {C Macro} SCM SCM_PACK (scm_t_bits @var{x}) +Takes a valid integral representation of a Scheme object and transforms +it into its representation as a @code{SCM} value. +@end deftypefn diff --git a/doc/ref/scheme-smobs.texi b/doc/ref/scheme-smobs.texi new file mode 100644 index 000000000..a5ffe4308 --- /dev/null +++ b/doc/ref/scheme-smobs.texi @@ -0,0 +1,147 @@ +@c -*-texinfo-*- +@c This is part of the GNU Guile Reference Manual. +@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 +@c Free Software Foundation, Inc. +@c See the file guile.texi for copying conditions. + +@page +@node Smobs +@section Smobs + +This chapter contains reference information related to defining and +working with smobs. See @ref{Defining New Types (Smobs)} for a +tutorial-like introduction to smobs. + +@deftypefun scm_t_bits scm_make_smob_type (const char *name, size_t size) +This function adds a new smob type, named @var{name}, with instance size +@var{size}, to the system. The return value is a tag that is used in +creating instances of the type. + +If @var{size} is 0, the default @emph{free} function will do nothing. + +If @var{size} is not 0, the default @emph{free} function will +deallocate the memory block pointed to by @code{SCM_SMOB_DATA} with +@code{scm_gc_free}. The @var{WHAT} parameter in the call to +@code{scm_gc_free} will be @var{NAME}. + +Default values are provided for the @emph{mark}, @emph{free}, +@emph{print}, and @emph{equalp} functions, as described in +@ref{Defining New Types (Smobs)}. If you want to customize any of +these functions, the call to @code{scm_make_smob_type} should be +immediately followed by calls to one or several of +@code{scm_set_smob_mark}, @code{scm_set_smob_free}, +@code{scm_set_smob_print}, and/or @code{scm_set_smob_equalp}. +@end deftypefun + +@deftypefn {C Function} void scm_set_smob_mark (scm_t_bits tc, SCM (*mark) (SCM obj)) +This function sets the smob marking procedure for the smob type specified by +the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}. + +The @var{mark} procedure must cause @code{scm_gc_mark} to be called +for every @code{SCM} value that is directly referenced by the smob +instance @var{obj}. One of these @code{SCM} values can be returned +from the procedure and Guile will call @code{scm_gc_mark} for it. +This can be used to avoid deep recursions for smob instances that form +a list. +@end deftypefn + +@deftypefn {C Function} void scm_set_smob_free (scm_t_bits tc, size_t (*free) (SCM obj)) +This function sets the smob freeing procedure for the smob type +specified by the tag @var{tc}. @var{tc} is the tag returned by +@code{scm_make_smob_type}. + +The @var{free} procedure must deallocate all resources that are +directly associated with the smob instance @var{OBJ}. It must assume +that all @code{SCM} values that it references have already been freed +and are thus invalid. + +The @var{free} procedure must return 0. +@end deftypefn + +@deftypefn {C Function} void scm_set_smob_print (scm_t_bits tc, int (*print) (SCM obj, SCM port, scm_print_state* pstate)) +This function sets the smob printing procedure for the smob type +specified by the tag @var{tc}. @var{tc} is the tag returned by +@code{scm_make_smob_type}. + +The @var{print} procedure should output a textual representation of +the smob instance @var{obj} to @var{port}, using information in +@var{pstate}. + +The textual representation should be of the form @code{#<name ...>}. +This ensures that @code{read} will not interpret it as some other +Scheme value. + +It is often best to ignore @var{pstate} and just print to @var{port} +with @code{scm_display}, @code{scm_write}, @code{scm_simple_format}, +and @code{scm_puts}. +@end deftypefn + +@deftypefn {C Function} void scm_set_smob_equalp (scm_t_bits tc, SCM (*equalp) (SCM obj1, SCM obj1)) +This function sets the smob equality-testing predicate for the smob +type specified by the tag @var{tc}. @var{tc} is the tag returned by +@code{scm_make_smob_type}. + +The @var{equalp} procedure should return @code{SCM_BOOL_T} when +@var{obj1} is @code{equal?} to @var{obj2}. Else it should return +@var{SCM_BOOL_F}. Both @var{obj1} and @var{obj2} are instances of the +smob type @var{tc}. +@end deftypefn + + +@deftypefn {C Macro} void SCM_NEWSMOB (SCM value, scm_t_bits tag, void *data) +@deftypefnx {C Macro} void SCM_NEWSMOB2 (SCM value, scm_t_bits tag, void *data, void *data2) +@deftypefnx {C Macro} void SCM_NEWSMOB3 (SCM value, scm_t_bits tag, void *data, void *data2, void *data3) +Make @var{value} contain a smob instance of the type with tag +@var{tag} and smob data @var{data}, @var{data2}, and @var{data3}, as +appropriate. + +The @var{tag} is what has been returned by @code{scm_make_smob_type}. +The initial values @var{data}, @var{data2}, and @var{data3} are of +type @code{scm_t_bits}; when you want to use them for @code{SCM} +values, these values need to be converted to a @code{scm_t_bits} first +by using @code{SCM_UNPACK}. +@end deftypefn + +Since it is often the case (e.g., in smob constructors) that you will +create a smob instance and return it, there is also a slightly specialized +macro for this situation: + +@deftypefn {C Macro} {} SCM_RETURN_NEWSMOB (scm_t_bits tag, void *data) +@deftypefnx {C Macro} {} SCM_RETURN_NEWSMOB2 (scm_t_bits tag, void *data1, void *data2) +@deftypefnx {C Macro} {} SCM_RETURN_NEWSMOB3 (scm_t_bits tag, void *data1, void *data2, void *data3) +This macro expands to a block of code that creates a smob instance of +the type with tag @var{tag} and smob data @var{data}, @var{data2}, and +@var{data3}, as with @code{SCM_NEWSMOB}, etc., and causes the +surrounding function to return that @code{SCM} value. It should be +the last piece of code in a block. +@end deftypefn + +@deftypefn {C Macro} scm_t_bits SCM_SMOB_DATA (SCM obj) +@deftypefnx {C Macro} scm_t_bits SCM_SMOB_DATA2 (SCM obj) +@deftypefnx {C Macro} scm_t_bits SCM_SMOB_DATA3 (SCM obj) +Return the first (second, third) immediate word of the smob @var{obj}. +When the word contains a @code{SCM} value, it must be converted with +@code{SCM_PACK}. +@end deftypefn + +@deftypefn {C Macro} scm_t_bits SCM_SET_SMOB_DATA (SCM obj, scm_t_bits val) +@deftypefnx {C Macro} scm_t_bits SCM_SET_SMOB_DATA2 (SCM obj, scm_t_bits val) +@deftypefnx {C Macro} scm_t_bits SCM_SET_SMOB_DATA3 (SCM obj, scm_t_bits val) +Set the first (second, third) immediate word of the smob @var{obj} to +@var{val}. When the word should be set to a @code{SCM} value, that +value must be converted with @code{SCM_UNPACK} first. +@end deftypefn + +@deftypefn {C Macro} scm_t_bits SCM_SMOB_FLAGS (SCM obj) +Return the 16 extra bits of the smob @var{obj}. No meaning is +predefined for these bits, you can use them freely. +@end deftypefn + +@deftypefn {C Macro} scm_t_bits SCM_SET_SMOB_FLAGS (SCM obj, scm_t_bits flags) +Set the 16 extra bits of the smob @var{obj} to @var{flags}. No +meaning is predefined for these bits, you can use them freely. +@end deftypefn + +@c Local Variables: +@c TeX-master: "guile.texi" +@c End: diff --git a/doc/ref/scheme-snarf.texi b/doc/ref/scheme-snarf.texi new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/doc/ref/scheme-snarf.texi diff --git a/doc/ref/scheme-translation.texi b/doc/ref/scheme-translation.texi index e7a411ba6..e69de29bb 100644 --- a/doc/ref/scheme-translation.texi +++ b/doc/ref/scheme-translation.texi @@ -1,54 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@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 {Scheme Procedure} nil-car x -@deffnx {C Function} scm_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 {Scheme Procedure} nil-cdr x -@deffnx {C Function} scm_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 {Scheme Procedure} nil-cons x y -@deffnx {C Function} scm_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 {Scheme Procedure} 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 {Scheme Procedure} null x -@deffnx {C Function} scm_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: diff --git a/doc/ref/scheme-utility.texi b/doc/ref/scheme-utility.texi index ec567f994..4528d8266 100644 --- a/doc/ref/scheme-utility.texi +++ b/doc/ref/scheme-utility.texi @@ -6,7 +6,7 @@ @page @node Utility Functions -@chapter General Utility Functions +@section General Utility Functions @c FIXME::martin: Review me! @@ -25,7 +25,7 @@ applications, they are collected in a @dfn{utility} chapter. @node Equality -@section Equality +@subsection Equality @c FIXME::martin: Review me! @@ -81,7 +81,7 @@ terminate if its arguments are circular data structures. @node Object Properties -@section Object Properties +@subsection Object Properties It's often useful to associate a piece of additional information with a Scheme object even though that object does not have a dedicated slot @@ -151,7 +151,7 @@ protected by the table. @node Property Primitives -@subsection Low Level Property Implementation. +@subsubsection Low Level Property Implementation. @deffn {Scheme Procedure} primitive-make-property not-found-proc @deffnx {C Function} scm_primitive_make_property (not_found_proc) @@ -184,7 +184,7 @@ Remove any value associated with @var{prop} and @var{obj}. @node Old-fashioned Properties -@subsection An Older Approach to Properties +@subsubsection An Older Approach to Properties Traditionally, Lisp systems provide a different object property interface to that provided by @code{make-object-property}, in which the @@ -219,7 +219,7 @@ to @var{value}. @node Sorting -@section Sorting +@subsection Sorting @c FIXME::martin: Review me! @@ -334,7 +334,7 @@ is not specified. @node Copying -@section Copying Deep Structures +@subsection Copying Deep Structures @c FIXME::martin: Review me! @@ -355,7 +355,7 @@ any other object. @node General Conversion -@section General String Conversion +@subsection General String Conversion @c FIXME::martin: Review me! @@ -380,7 +380,7 @@ argument @var{printer} (default: @code{write}). @node Hooks -@section Hooks +@subsection Hooks @tpindex Hooks A hook is a list of procedures to be called at well defined points in @@ -409,12 +409,13 @@ using @code{run-hook}. * Hook Example:: Hook usage by example. * Hook Reference:: Reference of all hook procedures. * C Hooks:: Hooks for use from C code. -* Guile Hooks:: Hooks provided by Guile. +* GC Hooks:: Garbage collection hooks. +* REPL Hooks:: Hooks into the Guile REPL. @end menu @node Hook Example -@subsection Hook Usage by Example +@subsubsection Hook Usage by Example Hook usage is shown by some examples in this section. First, we will define a hook of arity 2 --- that is, the procedures stored in the hook @@ -476,7 +477,7 @@ procedure to the @emph{end} of the list instead by providing a third @node Hook Reference -@subsection Hook Reference +@subsubsection Hook Reference When you create a hook with @code{make-hook}, you must specify the arity of the procedures which can be added to the hook. If the arity is not @@ -569,7 +570,7 @@ Return 1 if @var{x} is a Scheme-level hook, 0 otherwise. @end deftypefn -@subsection Handling Scheme-level hooks from C code +@subsubsection Handling Scheme-level hooks from C code Here is an example of how to handle Scheme-level hooks from C code using the above functions. @@ -584,7 +585,7 @@ else @node C Hooks -@subsection Hooks For C Code. +@subsubsection Hooks For C Code. The hooks already described are intended to be populated by Scheme-level procedures. In addition to this, the Guile library provides an @@ -685,15 +686,6 @@ function to be called. @end deftypefn -@node Guile Hooks -@subsection Hooks Provided by Guile - -@menu -* GC Hooks:: Garbage collection hooks. -* REPL Hooks:: Hooks into the Guile REPL. -@end menu - - @node GC Hooks @subsubsection Hooks for Garbage Collection diff --git a/doc/ref/scm.texi b/doc/ref/scm.texi index fb1dc8955..c0e386c05 100644 --- a/doc/ref/scm.texi +++ b/doc/ref/scm.texi @@ -6,79 +6,21 @@ @page @node API Overview -@chapter Overview of the Guile API +@section Overview of the Guile API Guile's application programming interface (@dfn{API}) makes functionality available that an application developer can use in either C or Scheme programming. The interface consists of @dfn{elements} that may be macros, functions or variables in C, and procedures, variables, -syntax or other types of object in Scheme. Broadly speaking, the -interface as a whole can be divided into three groups. +syntax or other types of object in Scheme. -@enumerate -@item -Elements that are available equivalently as C functions or Scheme -procedures. - -@item -Elements that are only available as macros, functions or variables for C -programming. - -@item -Elements that are only available as procedures or other objects in -Scheme. -@end enumerate - -Functions/procedures in the first group are often known as -@dfn{primitives}, @dfn{subrs} or @dfn{builtins}. An example is the -@code{assq} Scheme procedure, which is also available as @code{scm_assq} -in C. - -Elements in the second and third groups exist because they provide -additional language-specific benefits in either Scheme or C. Examples -are the C macro @code{SCM_CONSP}, which is faster and more convenient in -C programming than the primitive @code{scm_pair_p}, and the -procedure-with-setter @code{make-object-property}, which provides a -more convenient property handling interface in Scheme than the -primitives on which it is based. - -@menu -* Primitives:: Identical function for Scheme and C. -* C Only:: Elements only available in C. -* Scheme Only:: Elements only available in Scheme. -* Reference Layout:: The layout of this part of the manual. -@end menu - - -@node Primitives -@section Identical Function in both Scheme and C - -They form the majority of the API, and allow both C and Scheme -programmers to perform identical operations. +Many elements are available to both Scheme and C, in a form that is +appropriate. For example, the @code{assq} Scheme procedure is also +available as @code{scm_assq} to C code. These elements are documented +only once, addressing both the Scheme and C aspects of them. -@c @node Scheme Primitives -@c @chapter Writing Scheme primitives in C -@c - according to the menu in guile.texi - NJ 2001/1/26 -@c @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 -@subsection Transforming Scheme name to C name +The Scheme name of an element is related to its C name in a regular +way. Also, a C function takes its parameters in a systematic way. Normally, the name of a C function can be derived given its Scheme name, using some simple textual transformations: @@ -89,99 +31,82 @@ using some simple textual transformations: 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_". +Replace @code{?} (question mark) with @code{_p}. @item -Replace @code{<=} (less than or equal) with "_leq". +Replace @code{!} (exclamation point) with @code{_x}. @item -Replace @code{>=} (greater than or equal) with "_geq". +Replace internal @code{->} with @code{_to_}. @item -Replace @code{<} (less than) with "_less". +Replace @code{<=} (less than or equal) with @code{_leq}. @item -Replace @code{>} (greater than) with "_gr". +Replace @code{>=} (greater than or equal) with @code{_geq}. @item -Replace @code{@@} with "at". [Omit?] +Replace @code{<} (less than) with @code{_less}. @item -Prefix with "gh_" (or "scm_" if you are ignoring the gh interface). +Replace @code{>} (greater than) with @code{gr}. @item -[Anything else? --ttn, 2000/01/16 15:17:28] +Prefix with @code{scm_}. @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 -@subsection Structuring argument lists for C functions - -The C function's arguments will be all of the Scheme procedure's -arguments, 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}. - - -@node C Only -@section Elements Available Only in C - -For C this is usually a matter of better performance (e.g. the -@code{SCM_CONSP} macro) or of accepting C language types rather than the -generic @code{SCM}. - - -@node Scheme Only -@section Elements Available Only in Scheme - - -@node Reference Layout -@section Reference Material 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 quick way of identifying the parts of Guile that implement -R5RS-compliant features, see the R5RS index: @ref{R5RS Index}. +@c Here is an Emacs Lisp command that prompts for a Scheme function name and +@c inserts the corresponding C function name into the buffer. + +@c @example +@c (defun insert-scheme-to-C (name &optional use-gh) +@c "Transforms Scheme NAME, a string, to its C counterpart, and inserts it. +@c Prefix arg non-nil means use \"gh_\" prefix, otherwise use \"scm_\" prefix." +@c (interactive "sScheme name: \nP") +@c (let ((transforms '(("-" . "_") +@c ("?" . "_p") +@c ("!" . "_x") +@c ("->" . "_to_") +@c ("<=" . "_leq") +@c (">=" . "_geq") +@c ("<" . "_less") +@c (">" . "_gr") +@c ("@@" . "at")))) +@c (while transforms +@c (let ((trigger (concat "\\(.*\\)" +@c (regexp-quote (caar transforms)) +@c "\\(.*\\)")) +@c (sub (cdar transforms)) +@c (m nil)) +@c (while (setq m (string-match trigger name)) +@c (setq name (concat (match-string 1 name) +@c sub +@c (match-string 2 name))))) +@c (setq transforms (cdr transforms)))) +@c (insert (if use-gh "gh_" "scm_") name)) +@c @end example + +A C function always takes a fixed number of arguments of type +@code{SCM}, even when the corresponding Scheme function takes a +variable number. + +For some Scheme functions, some last arguments are optional; the +corresponding C function must always be invoked with all optional +arguments specified. To get the effect as if an argument has not been +specified, pass @code{SCM_UNDEFINED} as its value. You can not do +this for an argument in the middle; when one argument is +@code{SCM_UNDEFINED} all the ones following it must be +@code{SCM_UNDEFINED} as well. + +Some Scheme functions take an arbitrary number of @emph{rest} +arguments; the corresponding C function must be invoked with a list of +all these arguments. This list is always the last argument of the C +function. + +These two variants can also be combined. + +The type of the return value of a C function that corresponds to a +Scheme function is always @code{SCM}. In the descriptions below, +types are therefore often omitted bot for the return value and for the +arguments. diff --git a/doc/ref/script-getopt.texi b/doc/ref/script-getopt.texi index 274c79912..af1eb7d9c 100644 --- a/doc/ref/script-getopt.texi +++ b/doc/ref/script-getopt.texi @@ -6,7 +6,7 @@ @page @node Command Line Handling -@chapter Handling Command Line Options and Arguments +@section Handling Command Line Options and Arguments @c This chapter was written and contributed by Martin Grabmueller. @@ -18,15 +18,6 @@ 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. @@ -91,350 +82,12 @@ 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 {Scheme 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 {Scheme 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. - +which is distributed with Guile, @xref{getopt-long}. @c Local Variables: @c TeX-master: "guile.texi" diff --git a/doc/ref/scripts.texi b/doc/ref/scripts.texi index 358f065b0..e69de29bb 100644 --- a/doc/ref/scripts.texi +++ b/doc/ref/scripts.texi @@ -1,236 +0,0 @@ -@c -*-texinfo-*- -@c This is part of the GNU Guile Reference Manual. -@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004 -@c Free Software Foundation, Inc. -@c See the file guile.texi for copying conditions. - -@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. - -The @var{function} is most often a simple symbol that names a function -that is defined in the script. It can also be of the form @code{(@@ -@var{module-name} @var{symbol}} and in that case, the symbol is -looked up in the module named @var{module-name}. - -@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 --debug -Start with the debugging evaluator and enable backtraces. Using the -debugging evaluator will give you better error messages but it will -slow down execution. By default, the debugging evaluator is only used -when entering an interactive session. When executing a script with -@code{-s} or @code{-c}, the normal, faster evaluator is used by default. - -@vnew{1.8} -@item --no-debug -Do not use the debugging evaluator, even when entering an interactive -session. - -@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 diff --git a/doc/ref/scsh.texi b/doc/ref/scsh.texi index a03c390ed..0f869ecd7 100644 --- a/doc/ref/scsh.texi +++ b/doc/ref/scsh.texi @@ -6,7 +6,7 @@ @page @node The Scheme shell (scsh) -@chapter The Scheme shell (scsh) +@section The Scheme shell (scsh) @cindex SCSH @cindex Scheme Shell diff --git a/doc/ref/slib.texi b/doc/ref/slib.texi index 596fd94ec..1fe3847df 100644 --- a/doc/ref/slib.texi +++ b/doc/ref/slib.texi @@ -6,7 +6,7 @@ @page @node SLIB -@chapter SLIB +@section SLIB @cindex SLIB Before the SLIB facilities can be used, the following Scheme expression @@ -39,7 +39,7 @@ Manual}). @end menu @node SLIB installation -@section SLIB installation +@subsection SLIB installation The following seems to work (e.g., with slib versions 2c7 and 2d2): @@ -89,15 +89,14 @@ install-info slib.info /usr/local/info/dir @end enumerate @node JACAL -@section JACAL +@subsection JACAL @cindex 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}). +Jacal is a symbolic math package written in Scheme by Aubrey Jaffer. +It is usually installed as an extra package in SLIB. You can use Guile's interface to SLIB to invoke Jacal: diff --git a/doc/ref/srfi-modules.texi b/doc/ref/srfi-modules.texi index 1215a0a93..255a5ed1a 100644 --- a/doc/ref/srfi-modules.texi +++ b/doc/ref/srfi-modules.texi @@ -6,7 +6,7 @@ @page @node SRFI Support -@chapter SRFI Support Modules +@section SRFI Support Modules @cindex SRFI SRFI is an acronym for Scheme Request For Implementation. The SRFI @@ -40,7 +40,7 @@ get the relevant SRFI documents from the SRFI home page @node About SRFI Usage -@section About SRFI Usage +@subsection About SRFI Usage @c FIXME::martin: Review me! @@ -74,7 +74,7 @@ automatically (@pxref{Invoking Guile}). @node SRFI-0 -@section SRFI-0 - cond-expand +@subsection SRFI-0 - cond-expand @cindex SRFI-0 @findex cond-expand @@ -173,7 +173,7 @@ the following snippet will expand to @code{'hooray}. @node SRFI-1 -@section SRFI-1 - List library +@subsection SRFI-1 - List library @cindex SRFI-1 @c FIXME::martin: Review me! @@ -203,7 +203,7 @@ processing procedure, you should also have a look at the sections @end menu @node SRFI-1 Constructors -@subsection Constructors +@subsubsection Constructors @c FIXME::martin: Review me! @@ -252,7 +252,7 @@ APL language. @node SRFI-1 Predicates -@subsection Predicates +@subsubsection Predicates @c FIXME::martin: Review me! @@ -299,7 +299,7 @@ equality predicate @var{elt=}. If no or only one list is given, @node SRFI-1 Selectors -@subsection Selectors +@subsubsection Selectors @c FIXME::martin: Review me! @@ -361,7 +361,7 @@ Return the last element of the non-empty, finite list @var{lst}. @node SRFI-1 Length Append etc -@subsection Length, Append, Concatenate, etc. +@subsubsection Length, Append, Concatenate, etc. @c FIXME::martin: Review me! @@ -422,7 +422,7 @@ one list must be non-circular. @node SRFI-1 Fold and Map -@subsection Fold, Unfold & Map +@subsubsection Fold, Unfold & Map @c FIXME::martin: Review me! @@ -592,7 +592,7 @@ which are true are saved in the result list. @node SRFI-1 Filtering and Partitioning -@subsection Filtering and Partitioning +@subsubsection Filtering and Partitioning @c FIXME::martin: Review me! @@ -635,7 +635,7 @@ the input list. @node SRFI-1 Searching -@subsection Searching +@subsubsection Searching @c FIXME::martin: Review me! @@ -715,7 +715,7 @@ predicate. (@pxref{List Searching}) @node SRFI-1 Deleting -@subsection Deleting +@subsubsection Deleting @c FIXME::martin: Review me! @@ -768,7 +768,7 @@ is more efficient to sort and then compare only adjacent elements. @node SRFI-1 Association Lists -@subsection Association Lists +@subsubsection Association Lists @c FIXME::martin: Review me! @@ -821,7 +821,7 @@ the list structure of @var{alist} to construct its return. @node SRFI-1 Set Operations -@subsection Set Operations on Lists +@subsubsection Set Operations on Lists @c FIXME::martin: Review me! @@ -904,7 +904,7 @@ procedures return (@pxref{Multiple Values}). @node SRFI-2 -@section SRFI-2 - and-let* +@subsection SRFI-2 - and-let* @cindex SRFI-2 @noindent @@ -973,7 +973,7 @@ from separate @code{and} and @code{let*}, or from @code{cond} with @node SRFI-4 -@section SRFI-4 - Homogeneous numeric vector datatypes +@subsection SRFI-4 - Homogeneous numeric vector datatypes @cindex SRFI-4 @c FIXME::martin: Review me! @@ -1133,7 +1133,7 @@ initialized with the elements of the list @var{lst}. @node SRFI-6 -@section SRFI-6 - Basic String Ports +@subsection SRFI-6 - Basic String Ports @cindex SRFI-6 SRFI-6 defines the procedures @code{open-input-string}, @@ -1144,7 +1144,7 @@ SRFI-6 will be factored out of the core library in the future, so using this module does not hurt, after all. @node SRFI-8 -@section SRFI-8 - receive +@subsection SRFI-8 - receive @cindex SRFI-8 @code{receive} is a syntax for making the handling of multiple-value @@ -1152,7 +1152,7 @@ procedures easier. It is documented in @xref{Multiple Values}. @node SRFI-9 -@section SRFI-9 - define-record-type +@subsection SRFI-9 - define-record-type @cindex SRFI-9 This SRFI is a syntax for defining new record types and creating @@ -1229,7 +1229,7 @@ desired, exported from a module, etc. @node SRFI-10 -@section SRFI-10 - Hash-Comma Reader Extension +@subsection SRFI-10 - Hash-Comma Reader Extension @cindex SRFI-10 @cindex hash-comma @@ -1271,7 +1271,7 @@ read in. The result of @var{proc} is returned by the Scheme reader. @node SRFI-11 -@section SRFI-11 - let-values +@subsection SRFI-11 - let-values @cindex SRFI-11 @findex let-values @@ -1300,7 +1300,7 @@ expressions. @node SRFI-13 -@section SRFI-13 - String Library +@subsection SRFI-13 - String Library @cindex SRFI-13 In this section, we will describe all procedures defined in SRFI-13 @@ -1347,7 +1347,7 @@ soon as possible. @node Loading SRFI-13 -@subsection Loading SRFI-13 +@subsubsection Loading SRFI-13 When Guile is properly installed, SRFI-13 support can be loaded into a running Guile by using the @code{(srfi srfi-13)} module. @@ -1377,7 +1377,7 @@ guile> (string-concatenate '("Hello" " " "World!")) @end example @node SRFI-13 Predicates -@subsection Predicates +@subsubsection Predicates In addition to the primitives @code{string?} and @code{string-null?}, which are already in the Guile core, the string predicates @@ -1403,7 +1403,7 @@ application of @var{pred} to the last character of @var{s}. @c =================================================================== @node SRFI-13 Constructors -@subsection Constructors +@subsubsection Constructors SRFI-13 defines several procedures for constructing new strings. In addition to @code{make-string} and @code{string} (available in the Guile @@ -1420,7 +1420,7 @@ produce the corresponding string element. The order in which @c =================================================================== @node SRFI-13 List/String Conversion -@subsection List/String Conversion +@subsubsection List/String Conversion The procedure @code{string->list} is extended by SRFI-13, that is why it is included in @code{(srfi srfi-13)}. The other procedures are new. @@ -1469,7 +1469,7 @@ Insert the separator before each list element. @c =================================================================== @node SRFI-13 Selection -@subsection Selection +@subsubsection Selection These procedures are called @dfn{selectors}, because they access information about the string or select pieces of a given string. @@ -1547,7 +1547,7 @@ trimmed. @c =================================================================== @node SRFI-13 Modification -@subsection Modification +@subsubsection Modification The procedure @code{string-fill!} is extended from R5RS because it accepts optional start/end indices. This bindings shadows the procedure @@ -1564,7 +1564,7 @@ returns an unspecified value. @c =================================================================== @node SRFI-13 Comparison -@subsection Comparison +@subsubsection Comparison The procedures in this section are used for comparing strings in different ways. The comparison predicates differ from those in R5RS in @@ -1617,7 +1617,7 @@ Return a hash value of the string @var{s} in the range 0 @dots{} @c =================================================================== @node SRFI-13 Prefixes/Suffixes -@subsection Prefixes/Suffixes +@subsubsection Prefixes/Suffixes Using these procedures you can determine whether a given string is a prefix or suffix of another string or how long a common prefix/suffix @@ -1644,7 +1644,7 @@ Is @var{s1} a prefix/suffix of @var{s2}. @code{string-prefix-ci?} and @c =================================================================== @node SRFI-13 Searching -@subsection Searching +@subsubsection Searching Use these procedures to find out whether a string contains a given character or a given substring, or a character from a set of characters. @@ -1715,7 +1715,7 @@ indicated substrings. @c =================================================================== @node SRFI-13 Case Mapping -@subsection Alphabetic Case Mapping +@subsubsection Alphabetic Case Mapping These procedures convert the alphabetic case of strings. They are similar to the procedures in the Guile core, but are extended to handle @@ -1744,7 +1744,7 @@ variant. @c =================================================================== @node SRFI-13 Reverse/Append -@subsection Reverse/Append +@subsubsection Reverse/Append One appending procedure, @code{string-append} is the same in R5RS and in SRFI-13, so it is not redefined. @@ -1800,7 +1800,7 @@ share memory with the the strings in the @var{ls} arguments. @c =================================================================== @node SRFI-13 Fold/Unfold/Map -@subsection Fold/Unfold/Map +@subsubsection Fold/Unfold/Map @code{string-map}, @code{string-for-each} etc. are for iterating over the characters a string is composed of. The fold and unfold procedures @@ -1858,7 +1858,7 @@ return value is not specified. @c =================================================================== @node SRFI-13 Replicate/Rotate -@subsection Replicate/Rotate +@subsubsection Replicate/Rotate These procedures are special substring procedures, which can also be used for replicating strings. They are a bit tricky to use, but @@ -1896,7 +1896,7 @@ cannot copy a string on top of itself. @c =================================================================== @node SRFI-13 Miscellaneous -@subsection Miscellaneous +@subsubsection Miscellaneous @code{string-replace} is for replacing a portion of a string with another string and @code{string-tokenize} splits a string into a list of @@ -1924,7 +1924,7 @@ operating on the indicated substring of @var{s}. @c =================================================================== @node SRFI-13 Filtering/Deleting -@subsection Filtering/Deleting +@subsubsection Filtering/Deleting @dfn{Filtering} means to remove all characters from a string which do not match a given criteria, @dfn{deleting} means the opposite. @@ -1947,7 +1947,7 @@ character set, it is tested for membership. @node SRFI-14 -@section SRFI-14 - Character-set Library +@subsection SRFI-14 - Character-set Library @cindex SRFI-14 SRFI-14 defines the data type @dfn{character set}, and also defines a @@ -1971,7 +1971,7 @@ the module @code{(srfi srfi-14)}, as well as the standard variables @node Loading SRFI-14 -@subsection Loading SRFI-14 +@subsubsection Loading SRFI-14 When Guile is properly installed, SRFI-14 support can be loaded into a running Guile by using the @code{(srfi srfi-14)} module. @@ -1986,7 +1986,7 @@ guile> @node SRFI-14 Character Set Data Type -@subsection Character Set Data Type +@subsubsection Character Set Data Type The data type @dfn{charset} implements sets of characters (@pxref{Characters}). Because the internal representation of character @@ -2007,7 +2007,7 @@ don't rely on these ``features''. @c =================================================================== @node SRFI-14 Predicates/Comparison -@subsection Predicates/Comparison +@subsubsection Predicates/Comparison Use these procedures for testing whether an object is a character set, or whether several character sets are equal or subsets of each other. @@ -2038,7 +2038,7 @@ returned value to the range 0 @dots{} @var{bound - 1}. @c =================================================================== @node SRFI-14 Iterating Over Character Sets -@subsection Iterating Over Character Sets +@subsubsection Iterating Over Character Sets Character set cursors are a means for iterating over the members of a character sets. After creating a character set cursor with @@ -2107,7 +2107,7 @@ Map the procedure @var{proc} over every character in @var{cs}. @c =================================================================== @node SRFI-14 Creating Character Sets -@subsection Creating Character Sets +@subsubsection Creating Character Sets New character sets are produced with these procedures. @@ -2174,7 +2174,7 @@ character or a character set. @c =================================================================== @node SRFI-14 Querying Character Sets -@subsection Querying Character Sets +@subsubsection Querying Character Sets Access the elements and other information of a character set with these procedures. @@ -2218,7 +2218,7 @@ Return a true value if any character in the character set @c =================================================================== @node SRFI-14 Character-Set Algebra -@subsection Character-Set Algebra +@subsubsection Character-Set Algebra Character sets can be manipulated with the common set algebra operation, such as union, complement, intersection etc. All of these procedures @@ -2272,7 +2272,7 @@ character sets. @c =================================================================== @node SRFI-14 Standard Character Sets -@subsection Standard Character Sets +@subsubsection Standard Character Sets In order to make the use of the character set data type and procedures useful, several predefined character set variables exist. @@ -2348,7 +2348,7 @@ This character set contains all possible characters. @end defvar @node SRFI-16 -@section SRFI-16 - case-lambda +@subsection SRFI-16 - case-lambda @cindex SRFI-16 @c FIXME::martin: Review me! @@ -2413,7 +2413,7 @@ applied to zero arguments, yields 1. @node SRFI-17 -@section SRFI-17 - Generalized set! +@subsection SRFI-17 - Generalized set! @cindex SRFI-17 This is an implementation of SRFI-17: Generalized set! @@ -2437,7 +2437,7 @@ specified in the SRFI. Using it avoids the described problems. @node SRFI-19 -@section SRFI-19 - Time/Date Library +@subsection SRFI-19 - Time/Date Library @cindex SRFI-19 This is an implementation of the SRFI-19 time/date library. The @@ -2457,7 +2457,7 @@ functions and variables described here are provided by @end menu @node SRFI-19 Introduction -@subsection SRFI-19 Introduction +@subsubsection SRFI-19 Introduction @cindex universal time @cindex atomic time @@ -2511,7 +2511,7 @@ from 1858-11-17T00:00:00Z, ie.@: midnight 17 November 1858 UTC. @node SRFI-19 Time -@subsection SRFI-19 Time +@subsubsection SRFI-19 Time @cindex time A @dfn{time} object has type, seconds and nanoseconds fields @@ -2633,7 +2633,7 @@ the given @var{time} to form their return. @node SRFI-19 Date -@subsection SRFI-19 Date +@subsubsection SRFI-19 Date @cindex date A @dfn{date} object represents a date in the Gregorian calendar and a @@ -2729,7 +2729,7 @@ Return the current Modified Julian Day. @node SRFI-19 Time/Date conversions -@subsection SRFI-19 Time/Date conversions +@subsubsection SRFI-19 Time/Date conversions @defun date->julian-day date @defunx date->modified-julian-day date @@ -2781,7 +2781,7 @@ their return. The plain functions create a new object. @end defun @node SRFI-19 Date to string -@subsection SRFI-19 Date to string +@subsubsection SRFI-19 Date to string @cindex date to string @defun date->string date [format] @@ -2871,7 +2871,7 @@ the future. @node SRFI-19 String to date -@subsection SRFI-19 String to date +@subsubsection SRFI-19 String to date @cindex string to date @c FIXME: Can we say what happens when an incomplete date is @@ -2994,7 +2994,7 @@ change in the future. @node SRFI-26 -@section SRFI-26 - specializing parameters +@subsection SRFI-26 - specializing parameters @cindex SRFI-26 This SRFI provides a syntax for conveniently specializing selected |