*** empty log message ***
[bpt/guile.git] / doc / ref / api-modules.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
7@page
8@node Modules
9@section Modules
10@cindex modules
11
12When programs become large, naming conflicts can occur when a function
13or global variable defined in one file has the same name as a function
14or global variable in another file. Even just a @emph{similarity}
15between function names can cause hard-to-find bugs, since a programmer
16might type the wrong function name.
17
18The approach used to tackle this problem is called @emph{information
19encapsulation}, which consists of packaging functional units into a
20given name space that is clearly separated from other name spaces.
21@cindex encapsulation
22@cindex information encapsulation
23@cindex name space
24
25The language features that allow this are usually called @emph{the
26module system} because programs are broken up into modules that are
27compiled separately (or loaded separately in an interpreter).
28
29Older languages, like C, have limited support for name space
30manipulation and protection. In C a variable or function is public by
31default, and can be made local to a module with the @code{static}
32keyword. But you cannot reference public variables and functions from
33another module with different names.
34
35More advanced module systems have become a common feature in recently
36designed languages: ML, Python, Perl, and Modula 3 all allow the
37@emph{renaming} of objects from a foreign module, so they will not
38clutter the global name space.
39@cindex name space - private
40
41In addition, Guile offers variables as first-class objects. They can
42be used for interacting with the module system.
43
44@menu
45* provide and require:: The SLIB feature mechanism.
46* Environments:: R5RS top-level environments.
47* The Guile module system:: How Guile does it.
48* Dynamic Libraries:: Loading libraries of compiled code at run time.
49* Variables:: First-class variables.
50@end menu
51
52@node provide and require
53@subsection provide and require
54
55Aubrey Jaffer, mostly to support his portable Scheme library SLIB,
56implemented a provide/require mechanism for many Scheme implementations.
57Library files in SLIB @emph{provide} a feature, and when user programs
58@emph{require} that feature, the library file is loaded in.
59
60For example, the file @file{random.scm} in the SLIB package contains the
61line
62
63@smalllisp
64(provide 'random)
65@end smalllisp
66
67so to use its procedures, a user would type
68
69@smalllisp
70(require 'random)
71@end smalllisp
72
73and they would magically become available, @emph{but still have the same
74names!} So this method is nice, but not as good as a full-featured
75module system.
76
77When SLIB is used with Guile, provide and require can be used to access
78its facilities.
79
80@node Environments
81@subsection Environments
82@cindex environment
83
84Scheme, as defined in R5RS, does @emph{not} have a full module system.
85However it does define the concept of a top-level @dfn{environment}.
86Such an environment maps identifiers (symbols) to Scheme objects such
87as procedures and lists: @ref{About Closure}. In other words, it
88implements a set of @dfn{bindings}.
89
90Environments in R5RS can be passed as the second argument to
91@code{eval} (@pxref{Fly Evaluation}). Three procedures are defined to
92return environments: @code{scheme-report-environment},
93@code{null-environment} and @code{interaction-environment} (@pxref{Fly
94Evaluation}).
95
96In addition, in Guile any module can be used as an R5RS environment,
97i.e., passed as the second argument to @code{eval}.
98
99Note: the following two procedures are available only when the
100@code{(ice-9 r5rs)} module is loaded:
101
102@smalllisp
103(use-modules (ice-9 r5rs))
104@end smalllisp
105
106@deffn {Scheme Procedure} scheme-report-environment version
107@deffnx {Scheme Procedure} null-environment version
108@var{version} must be the exact integer `5', corresponding to revision
1095 of the Scheme report (the Revised^5 Report on Scheme).
110@code{scheme-report-environment} returns a specifier for an
111environment that is empty except for all bindings defined in the
112report that are either required or both optional and supported by the
113implementation. @code{null-environment} returns a specifier for an
114environment that is empty except for the (syntactic) bindings for all
115syntactic keywords defined in the report that are either required or
116both optional and supported by the implementation.
117
118Currently Guile does not support values of @var{version} for other
119revisions of the report.
120
121The effect of assigning (through the use of @code{eval}) a variable
122bound in a @code{scheme-report-environment} (for example @code{car})
123is unspecified. Currently the environments specified by
124@code{scheme-report-environment} are not immutable in Guile.
125@end deffn
126
127@node The Guile module system
128@subsection The Guile module system
129
130The Guile module system extends the concept of environments, discussed
131in the previous section, with mechanisms to define, use and customise
132sets of bindings.
133
134In 1996 Tom Lord implemented a full-featured module system for Guile which
135allows loading Scheme source files into a private name space. This system has
136been in available since at least Guile version 1.1.
137
138For Guile version 1.5.0 and later, the system has been improved to have better
139integration from C code, more fine-grained user control over interfaces, and
140documentation.
141
142Although it is anticipated that the module system implementation will
143change in the future, the Scheme programming interface described in this
144manual should be considered stable. The C programming interface is
145considered relatively stable, although at the time of this writing,
146there is still some flux.
147
148@menu
149* General Information about Modules:: Guile module basics.
150* Using Guile Modules:: How to use existing modules.
151* Creating Guile Modules:: How to package your code into modules.
cdf1ad3b 152* Module System Reflection:: Accessing module objects at run-time.
07d83abe
MV
153* Module System Quirks:: Strange things to be aware of.
154* Included Guile Modules:: Which modules come with Guile?
155* Accessing Modules from C:: How to work with modules with C code.
156@end menu
157
158@node General Information about Modules
159@subsubsection General Information about Modules
160
161A Guile module can be thought of as a collection of named procedures,
162variables and macros. More precisely, it is a set of @dfn{bindings}
163of symbols (names) to Scheme objects.
164
165An environment is a mapping from identifiers (or symbols) to locations,
166i.e., a set of bindings.
167There are top-level environments and lexical environments.
168The environment in which a lambda is executed is remembered as part of its
169definition.
170
171Within a module, all bindings are visible. Certain bindings
172can be declared @dfn{public}, in which case they are added to the
173module's so-called @dfn{export list}; this set of public bindings is
174called the module's @dfn{public interface} (@pxref{Creating Guile
175Modules}).
176
177A client module @dfn{uses} a providing module's bindings by either
178accessing the providing module's public interface, or by building a
179custom interface (and then accessing that). In a custom interface, the
180client module can @dfn{select} which bindings to access and can also
181algorithmically @dfn{rename} bindings. In contrast, when using the
182providing module's public interface, the entire export list is available
183without renaming (@pxref{Using Guile Modules}).
184
185To use a module, it must be found and loaded. All Guile modules have a
186unique @dfn{module name}, which is a list of one or more symbols.
187Examples are @code{(ice-9 popen)} or @code{(srfi srfi-11)}. When Guile
188searches for the code of a module, it constructs the name of the file to
189load by concatenating the name elements with slashes between the
190elements and appending a number of file name extensions from the list
191@code{%load-extensions} (@pxref{Loading}). The resulting file name is
192then searched in all directories in the variable @code{%load-path}
193(@pxref{Build Config}). For example, the @code{(ice-9 popen)} module
194would result in the filename @code{ice-9/popen.scm} and searched in the
195installation directories of Guile and in all other directories in the
196load path.
197
198@c FIXME::martin: Not sure about this, maybe someone knows better?
199Every module has a so-called syntax transformer associated with it.
200This is a procedure which performs all syntax transformation for the
201time the module is read in and evaluated. When working with modules,
202you can manipulate the current syntax transformer using the
203@code{use-syntax} syntactic form or the @code{#:use-syntax} module
204definition option (@pxref{Creating Guile Modules}).
205
206Please note that there are some problems with the current module system
207you should keep in mind (@pxref{Module System Quirks}). We hope to
208address these eventually.
209
210
211@node Using Guile Modules
212@subsubsection Using Guile Modules
213
214To use a Guile module is to access either its public interface or a
215custom interface (@pxref{General Information about Modules}). Both
216types of access are handled by the syntactic form @code{use-modules},
217which accepts one or more interface specifications and, upon evaluation,
218arranges for those interfaces to be available to the current module.
219This process may include locating and loading code for a given module if
5c132e68 220that code has not yet been loaded, following @code{%load-path} (@pxref{Build
07d83abe
MV
221Config}).
222
223An @dfn{interface specification} has one of two forms. The first
224variation is simply to name the module, in which case its public
225interface is the one accessed. For example:
226
227@smalllisp
228(use-modules (ice-9 popen))
229@end smalllisp
230
231Here, the interface specification is @code{(ice-9 popen)}, and the
232result is that the current module now has access to @code{open-pipe},
233@code{close-pipe}, @code{open-input-pipe}, and so on (@pxref{Included
234Guile Modules}).
235
236Note in the previous example that if the current module had already
237defined @code{open-pipe}, that definition would be overwritten by the
238definition in @code{(ice-9 popen)}. For this reason (and others), there
239is a second variation of interface specification that not only names a
240module to be accessed, but also selects bindings from it and renames
241them to suit the current module's needs. For example:
242
46bb559d 243@cindex binding renamer
07d83abe
MV
244@smalllisp
245(use-modules ((ice-9 popen)
246 :select ((open-pipe . pipe-open) close-pipe)
247 :renamer (symbol-prefix-proc 'unixy:)))
248@end smalllisp
249
250Here, the interface specification is more complex than before, and the
251result is that a custom interface with only two bindings is created and
252subsequently accessed by the current module. The mapping of old to new
253names is as follows:
254
255@c Use `smallexample' since `table' is ugly. --ttn
256@smallexample
257(ice-9 popen) sees: current module sees:
258open-pipe unixy:pipe-open
259close-pipe unixy:close-pipe
260@end smallexample
261
262This example also shows how to use the convenience procedure
263@code{symbol-prefix-proc}.
264
265You can also directly refer to bindings in a module by using the
266@code{@@} syntax. For example, instead of using the
267@code{use-modules} statement from above and writing
268@code{unixy:pipe-open} to refer to the @code{pipe-open} from the
269@code{(ice-9 popen)}, you could also write @code{(@@ (ice-9 popen)
270open-pipe)}. Thus an alternative to the complete @code{use-modules}
271statement would be
272
273@smalllisp
274(define unixy:pipe-open (@@ (ice-9 popen) open-pipe))
275(define unixy:close-pipe (@@ (ice-9 popen) close-pipe))
276@end smalllisp
277
278There is also @code{@@@@}, which can be used like @code{@@}, but does
279not check whether the variable that is being accessed is actually
280exported. Thus, @code{@@@@} can be thought of as the impolite version
281of @code{@@} and should only be used as a last resort or for
282debugging, for example.
283
284Note that just as with a @code{use-modules} statement, any module that
285has not yet been loaded yet will be loaded when referenced by a
286@code{@@} or @code{@@@@} form.
287
288You can also use the @code{@@} and @code{@@@@} syntaxes as the target
289of a @code{set!} when the binding refers to a variable.
290
291@c begin (scm-doc-string "boot-9.scm" "symbol-prefix-proc")
292@deffn {Scheme Procedure} symbol-prefix-proc prefix-sym
293Return a procedure that prefixes its arg (a symbol) with
294@var{prefix-sym}.
295@c Insert gratuitous C++ slam here. --ttn
296@end deffn
297
298@c begin (scm-doc-string "boot-9.scm" "use-modules")
299@deffn syntax use-modules spec @dots{}
300Resolve each interface specification @var{spec} into an interface and
301arrange for these to be accessible by the current module. The return
302value is unspecified.
303
304@var{spec} can be a list of symbols, in which case it names a module
305whose public interface is found and used.
306
307@var{spec} can also be of the form:
308
46bb559d 309@cindex binding renamer
07d83abe
MV
310@smalllisp
311 (MODULE-NAME [:select SELECTION] [:renamer RENAMER])
312@end smalllisp
313
314in which case a custom interface is newly created and used.
315@var{module-name} is a list of symbols, as above; @var{selection} is a
316list of selection-specs; and @var{renamer} is a procedure that takes a
317symbol and returns its new name. A selection-spec is either a symbol or
318a pair of symbols @code{(ORIG . SEEN)}, where @var{orig} is the name in
319the used module and @var{seen} is the name in the using module. Note
320that @var{seen} is also passed through @var{renamer}.
321
322The @code{:select} and @code{:renamer} clauses are optional. If both are
323omitted, the returned interface has no bindings. If the @code{:select}
324clause is omitted, @var{renamer} operates on the used module's public
325interface.
326
327Signal error if module name is not resolvable.
328@end deffn
329
330
331@c FIXME::martin: Is this correct, and is there more to say?
332@c FIXME::martin: Define term and concept `system transformer' somewhere.
333
334@deffn syntax use-syntax module-name
335Load the module @code{module-name} and use its system
336transformer as the system transformer for the currently defined module,
337as well as installing it as the current system transformer.
338@end deffn
339
340@deffn syntax @@ module-name binding-name
341Refer to the binding named @var{binding-name} in module
342@var{module-name}. The binding must have been exported by the module.
343@end deffn
344
345@deffn syntax @@@@ module-name binding-name
346Refer to the binding named @var{binding-name} in module
347@var{module-name}. The binding must not have been exported by the
348module. This syntax is only intended for debugging purposes or as a
349last resort.
350@end deffn
351
352@node Creating Guile Modules
353@subsubsection Creating Guile Modules
354
355When you want to create your own modules, you have to take the following
356steps:
357
358@itemize @bullet
359@item
360Create a Scheme source file and add all variables and procedures you wish
361to export, or which are required by the exported procedures.
362
363@item
364Add a @code{define-module} form at the beginning.
365
366@item
367Export all bindings which should be in the public interface, either
368by using @code{define-public} or @code{export} (both documented below).
369@end itemize
370
371@c begin (scm-doc-string "boot-9.scm" "define-module")
372@deffn syntax define-module module-name [options @dots{}]
373@var{module-name} is of the form @code{(hierarchy file)}. One
374example of this is
375
376@smalllisp
377(define-module (ice-9 popen))
378@end smalllisp
379
380@code{define-module} makes this module available to Guile programs under
381the given @var{module-name}.
382
383The @var{options} are keyword/value pairs which specify more about the
384defined module. The recognized options and their meaning is shown in
385the following table.
386
387@c fixme: Should we use "#:" or ":"?
388
389@table @code
390@item #:use-module @var{interface-specification}
391Equivalent to a @code{(use-modules @var{interface-specification})}
392(@pxref{Using Guile Modules}).
393
394@item #:use-syntax @var{module}
395Use @var{module} when loading the currently defined module, and install
396it as the syntax transformer.
397
950f97ac 398@item #:autoload @var{module} @var{symbol-list}
65f1345f 399@cindex autoload
950f97ac
KR
400Load @var{module} when any of @var{symbol-list} are accessed. For
401example,
402
403@example
404(define-module (my mod)
405 #:autoload (srfi srfi-1) (partition delete-duplicates))
406...
407(if something
408 (set! foo (delete-duplicates ...)))
409@end example
410
a236df75 411When a module is autoloaded, all its bindings become available.
950f97ac
KR
412@var{symbol-list} is just those that will first trigger the load.
413
414An autoload is a good way to put off loading a big module until it's
415really needed, for instance for faster startup or if it will only be
416needed in certain circumstances.
417
418@code{@@} can do a similar thing (@pxref{Using Guile Modules}), but in
419that case an @code{@@} form must be written every time a binding from
420the module is used.
07d83abe
MV
421
422@item #:export @var{list}
65f1345f 423@cindex export
46bb559d 424Export all identifiers in @var{list} which must be a list of symbols.
07d83abe
MV
425This is equivalent to @code{(export @var{list})} in the module body.
426
46bb559d
KR
427@item #:re-export @var{list}
428@cindex re-export
429Re-export all identifiers in @var{list} which must be a list of
430symbols. The symbols in @var{list} must be imported by the current
431module from other modules. This is equivalent to @code{re-export}
432below.
433
434@item #:export-syntax @var{list}
435@cindex export-syntax
436Export all identifiers in @var{list} which must be a list of symbols.
437The identifiers in @var{list} must refer to macros (@pxref{Macros})
438defined in the current module. This is equivalent to
439@code{(export-syntax @var{list})} in the module body.
440
441@item #:re-export-syntax @var{list}
442@cindex re-export-syntax
443Re-export all identifiers in @var{list} which must be a list of
444symbols. The symbols in @var{list} must refer to macros imported by
445the current module from other modules. This is equivalent to
446@code{(re-export-syntax @var{list})} in the module body.
447
448@item #:replace @var{list}
449@cindex replace
450@cindex replacing binding
451@cindex overriding binding
452@cindex duplicate binding
453Export all identifiers in @var{list} (a list of symbols) and mark them
454as @dfn{replacing bindings}. In the module user's name space, this
455will have the effect of replacing any binding with the same name that
456is not also ``replacing''. Normally a replacement results in an
457``override'' warning message, @code{#:replace} avoids that.
458
459This can be used by a module extending a core function in an upwardly
460compatible way, like SRFI-39 @code{current-input-port}
461(@pxref{SRFI-39}).
462
463Or it can be used by a module which is intentionally producing a new
464special kind of environment and should override any core or other
465bindings already in scope. For example perhaps a logic processing
466environment where @code{<=} is an inference instead of a comparison.
467
468@code{#:duplicates} below provides fine-grain control about duplicate
469binding handling on the module-user side.
470
471@item #:duplicates @var{list}
472@cindex duplicate binding handlers
473@cindex duplicate binding
474@cindex overriding binding
475Tell Guile to handle duplicate bindings for the bindings imported by
476the current module according to the policy defined by @var{list}, a
477list of symbols. @var{list} must contain symbols representing a
478duplicate binding handling policy chosen among the following:
479
480@table @code
481@item check
482Raises an error when a binding is imported from more than one place.
483@item warn
484Issue a warning when a binding is imported from more than one place
485and leave the responsibility of actually handling the duplication to
486the next duplicate binding handler.
487@item replace
488When a new binding is imported that has the same name as a previously
489imported binding, then do the following:
490
491@enumerate
492@item
493@cindex replacing binding
494If the old binding was said to be @dfn{replacing} (via the
495@code{#:replace} option above) and the new binding is not replacing,
496the keep the old binding.
497@item
498If the old binding was not said to be replacing and the new binding is
499replacing, then replace the old binding with the new one.
500@item
501If neither the old nor the new binding is replacing, then keep the old
502one.
503@end enumerate
504
505@item warn-override-core
506Issue a warning when a core binding is being overwritten and actually
507override the core binding with the new one.
508@item first
509In case of duplicate bindings, the firstly imported binding is always
510the one which is kept.
511@item last
512In case of duplicate bindings, the lastly imported binding is always
513the one which is kept.
514@item noop
515In case of duplicate bindings, leave the responsibility to the next
516duplicate handler.
517@end table
518
519If @var{list} contains more than one symbol, then the duplicate
520binding handlers which appear first will be used first when resolving
521a duplicate binding situation. As mentioned above, some resolution
522policies may explicitly leave the responsibility of handling the
523duplication to the next handler in @var{list}.
524
525@findex default-duplicate-binding-handler
526The default duplicate binding resolution policy is given by the
527@code{default-duplicate-binding-handler} procedure, and is
528
529@smalllisp
530(replace warn-override-core warn last)
531@end smalllisp
532
07d83abe 533@item #:no-backtrace
65f1345f 534@cindex no backtrace
07d83abe
MV
535Tell Guile not to record information for procedure backtraces when
536executing the procedures in this module.
537
538@item #:pure
65f1345f 539@cindex pure module
07d83abe
MV
540Create a @dfn{pure} module, that is a module which does not contain any
541of the standard procedure bindings except for the syntax forms. This is
542useful if you want to create @dfn{safe} modules, that is modules which
543do not know anything about dangerous procedures.
544@end table
545
546@end deffn
547@c end
548
549@deffn syntax export variable @dots{}
550Add all @var{variable}s (which must be symbols) to the list of exported
551bindings of the current module.
552@end deffn
553
554@c begin (scm-doc-string "boot-9.scm" "define-public")
555@deffn syntax define-public @dots{}
556Equivalent to @code{(begin (define foo ...) (export foo))}.
557@end deffn
558@c end
559
46bb559d
KR
560@deffn syntax re-export variable @dots{}
561Add all @var{variable}s (which must be symbols) to the list of
562re-exported bindings of the current module. Re-exported bindings must
563be imported by the current module from some other module.
564@end deffn
565
cdf1ad3b
MV
566@node Module System Reflection
567@subsubsection Module System Reflection
568
569The previous sections have described a declarative view of the module
570system. You can also work with it programmatically by accessing and
571modifying various parts of the Scheme objects that Guile uses to
572implement the module system.
573
574At any time, there is a @dfn{current module}. This module is the one
575where a top-level @code{define} and similar syntax will add new
576bindings. You can find other module objects with @code{resolve-module},
577for example.
578
579These module objects can be used as the second argument to @code{eval}.
580
581@deffn {Scheme Procedure} current-module
582Return the current module object.
583@end deffn
584
585@deffn {Scheme Procedure} set-current-module module
586Set the current module to @var{module} and return
587the previous current module.
588@end deffn
589
590@deffn {Scheme Procedure} resolve-module name
591Find the module named @var{name} and return it. When it has not already
592been defined, try to auto-load it. When it can't be found that way
593either, create an empty module. The name is a list of symbols.
594@end deffn
595
596@deffn {Scheme Procedure} resolve-interface name
597Find the module named @var{name} as with @code{resolve-module} and
598return its interface. The interface of a module is also a module
599object, but it contains only the exported bindings.
600@end deffn
601
602@deffn {Scheme Procedure} module-use! module interface
603Add @var{interface} to the front of the use-list of @var{module}. Both
604arguments should be module objects, and @var{interface} should very
605likely be a module returned by @code{resolve-interface}.
606@end deffn
07d83abe
MV
607
608@node Module System Quirks
609@subsubsection Module System Quirks
610
611Although the programming interfaces are relatively stable, the Guile
612module system itself is still evolving. Here are some situations where
613usage surpasses design.
614
615@itemize @bullet
616
617@item
618When using a module which exports a macro definition, the other module
619must export all bindings the macro expansion uses, too, because the
620expanded code would otherwise not be able to see these definitions and
621issue a ``variable unbound'' error, or worse, would use another binding
622which might be present in the scope of the expansion.
623
624@item
625When two or more used modules export bindings with the same names, the
626last accessed module wins, and the exported binding of that last module
627will silently be used. This might lead to hard-to-find errors because
628wrong procedures or variables are used. To avoid this kind of
629@dfn{name-clash} situation, use a custom interface specification
630(@pxref{Using Guile Modules}). (We include this entry for the possible
631benefit of users of Guile versions previous to 1.5.0, when custom
632interfaces were added to the module system.)
633
634@item
635[Add other quirks here.]
636
637@end itemize
638
639
640@node Included Guile Modules
641@subsubsection Included Guile Modules
642
643@c FIXME::martin: Review me!
644
645Some modules are included in the Guile distribution; here are references
646to the entries in this manual which describe them in more detail:
647
648@table @strong
649@item boot-9
650boot-9 is Guile's initialization module, and it is always loaded when
651Guile starts up.
652
653@item (ice-9 debug)
654Mikael Djurfeldt's source-level debugging support for Guile
655(@pxref{Debugging Features}).
656
54a3c992
KR
657@item (ice-9 expect)
658Actions based on matching input from a port (@pxref{Expect}).
659
660@item (ice-9 format)
661Formatted output in the style of Common Lisp (@pxref{Formatted
662Output}).
663
664@item (ice-9 ftw)
665File tree walker (@pxref{File Tree Walk}).
666
667@item (ice-9 getopt-long)
668Command line option processing (@pxref{getopt-long}).
669
670@item (ice-9 history)
671Refer to previous interactive expressions (@pxref{Value History}).
672
673@item (ice-9 popen)
674Pipes to and from child processes (@pxref{Pipes}).
675
676@item (ice-9 pretty-print)
677Nicely formatted output of Scheme expressions and objects
678(@pxref{Pretty Printing}).
679
680@item (ice-9 q)
681First-in first-out queues (@pxref{Queues}).
682
07d83abe
MV
683@item (ice-9 rdelim)
684Line- and character-delimited input (@pxref{Line/Delimited}).
685
54a3c992
KR
686@item (ice-9 readline)
687@code{readline} interactive command line editing (@pxref{Readline
688Support}).
689
690@item (ice-9 receive)
691Multiple-value handling with @code{receive} (@pxref{Multiple Values}).
692
693@item (ice-9 regex)
694Regular expression matching (@pxref{Regular Expressions}).
695
07d83abe
MV
696@item (ice-9 rw)
697Block string input/output (@pxref{Block Reading and Writing}).
698
54a3c992
KR
699@item (ice-9 streams)
700Sequence of values calculated on-demand (@pxref{Streams}).
701
702@item (ice-9 syncase)
703R5RS @code{syntax-rules} macro system (@pxref{Syntax Rules}).
704
aca55ba9
KR
705@item (ice-9 threads)
706Guile's support for multi threaded execution (@pxref{Scheduling}).
707
07d83abe
MV
708@item (ice-9 documentation)
709Online documentation (REFFIXME).
710
711@item (srfi srfi-1)
712A library providing a lot of useful list and pair processing
713procedures (@pxref{SRFI-1}).
714
715@item (srfi srfi-2)
716Support for @code{and-let*} (@pxref{SRFI-2}).
717
718@item (srfi srfi-4)
719Support for homogeneous numeric vectors (@pxref{SRFI-4}).
720
721@item (srfi srfi-6)
722Support for some additional string port procedures (@pxref{SRFI-6}).
723
724@item (srfi srfi-8)
725Multiple-value handling with @code{receive} (@pxref{SRFI-8}).
726
727@item (srfi srfi-9)
728Record definition with @code{define-record-type} (@pxref{SRFI-9}).
729
730@item (srfi srfi-10)
731Read hash extension @code{#,()} (@pxref{SRFI-10}).
732
733@item (srfi srfi-11)
734Multiple-value handling with @code{let-values} and @code{let-values*}
735(@pxref{SRFI-11}).
736
737@item (srfi srfi-13)
738String library (@pxref{SRFI-13}).
739
740@item (srfi srfi-14)
741Character-set library (@pxref{SRFI-14}).
742
e376f9e5
KR
743@item (srfi srfi-16)
744@code{case-lambda} procedures of variable arity (@pxref{SRFI-16}).
745
07d83abe
MV
746@item (srfi srfi-17)
747Getter-with-setter support (@pxref{SRFI-17}).
748
e376f9e5
KR
749@item (srfi srfi-19)
750Time/Date library (@pxref{SRFI-19}).
751
07d83abe
MV
752@item (srfi srfi-26)
753Convenient syntax for partial application (@pxref{SRFI-26})
754
e376f9e5
KR
755@item (srfi srfi-31)
756@code{rec} convenient recursive expressions (@pxref{SRFI-31})
757
07d83abe
MV
758@item (ice-9 slib)
759This module contains hooks for using Aubrey Jaffer's portable Scheme
760library SLIB from Guile (@pxref{SLIB}).
07d83abe
MV
761@end table
762
763
764@node Accessing Modules from C
765@subsubsection Accessing Modules from C
766
767The last sections have described how modules are used in Scheme code,
768which is the recommended way of creating and accessing modules. You
769can also work with modules from C, but it is more cumbersome.
770
771The following procedures are available.
772
773@deftypefn {C Procedure} SCM scm_current_module ()
774Return the module that is the @emph{current module}.
775@end deftypefn
776
777@deftypefn {C Procedure} SCM scm_set_current_module (SCM @var{module})
778Set the current module to @var{module} and return the previous current
779module.
780@end deftypefn
781
782@deftypefn {C Procedure} SCM scm_c_call_with_current_module (SCM @var{module}, SCM (*@var{func})(void *), void *@var{data})
783Call @var{func} and make @var{module} the current module during the
784call. The argument @var{data} is passed to @var{func}. The return
785value of @code{scm_c_call_with_current_module} is the return value of
786@var{func}.
787@end deftypefn
788
789@deftypefn {C Procedure} SCM scm_c_lookup (const char *@var{name})
790Return the variable bound to the symbol indicated by @var{name} in the
791current module. If there is no such binding or the symbol is not
792bound to a variable, signal an error.
793@end deftypefn
794
795@deftypefn {C Procedure} SCM scm_lookup (SCM @var{name})
796Like @code{scm_c_lookup}, but the symbol is specified directly.
797@end deftypefn
798
799@deftypefn {C Procedure} SCM scm_c_module_lookup (SCM @var{module}, const char *@var{name})
800@deftypefnx {C Procedure} SCM scm_module_lookup (SCM @var{module}, SCM @var{name})
801Like @code{scm_c_lookup} and @code{scm_lookup}, but the specified
802module is used instead of the current one.
803@end deftypefn
804
805@deftypefn {C Procedure} SCM scm_c_define (const char *@var{name}, SCM @var{val})
806Bind the symbol indicated by @var{name} to a variable in the current
807module and set that variable to @var{val}. When @var{name} is already
808bound to a variable, use that. Else create a new variable.
809@end deftypefn
810
811@deftypefn {C Procedure} SCM scm_define (SCM @var{name}, SCM @var{val})
812Like @code{scm_c_define}, but the symbol is specified directly.
813@end deftypefn
814
815@deftypefn {C Procedure} SCM scm_c_module_define (SCM @var{module}, const char *@var{name}, SCM @var{val})
816@deftypefnx {C Procedure} SCM scm_module_define (SCM @var{module}, SCM @var{name}, SCM @var{val})
817Like @code{scm_c_define} and @code{scm_define}, but the specified
818module is used instead of the current one.
819@end deftypefn
820
821@deftypefn {C Procedure} SCM scm_module_reverse_lookup (SCM @var{module}, SCM @var{variable})
822Find the symbol that is bound to @var{variable} in @var{module}. When no such binding is found, return @var{#f}.
823@end deftypefn
824
825@deftypefn {C Procedure} SCM scm_c_define_module (const char *@var{name}, void (*@var{init})(void *), void *@var{data})
826Define a new module named @var{name} and make it current while
827@var{init} is called, passing it @var{data}. Return the module.
828
829The parameter @var{name} is a string with the symbols that make up
830the module name, separated by spaces. For example, @samp{"foo bar"} names
831the module @samp{(foo bar)}.
832
833When there already exists a module named @var{name}, it is used
834unchanged, otherwise, an empty module is created.
835@end deftypefn
836
837@deftypefn {C Procedure} SCM scm_c_resolve_module (const char *@var{name})
838Find the module name @var{name} and return it. When it has not
839already been defined, try to auto-load it. When it can't be found
840that way either, create an empty module. The name is interpreted as
841for @code{scm_c_define_module}.
842@end deftypefn
843
844@deftypefn {C Procedure} SCM scm_resolve_module (SCM @var{name})
845Like @code{scm_c_resolve_module}, but the name is given as a real list
846of symbols.
847@end deftypefn
848
849@deftypefn {C Procedure} SCM scm_c_use_module (const char *@var{name})
850Add the module named @var{name} to the uses list of the current
851module, as with @code{(use-modules @var{name})}. The name is
852interpreted as for @code{scm_c_define_module}.
853@end deftypefn
854
855@deftypefn {C Procedure} SCM scm_c_export (const char *@var{name}, ...)
856Add the bindings designated by @var{name}, ... to the public interface
857of the current module. The list of names is terminated by
858@code{NULL}.
859@end deftypefn
860
861@node Dynamic Libraries
862@subsection Dynamic Libraries
863
864Most modern Unices have something called @dfn{shared libraries}. This
865ordinarily means that they have the capability to share the executable
866image of a library between several running programs to save memory and
867disk space. But generally, shared libraries give a lot of additional
868flexibility compared to the traditional static libraries. In fact,
869calling them `dynamic' libraries is as correct as calling them `shared'.
870
871Shared libraries really give you a lot of flexibility in addition to the
872memory and disk space savings. When you link a program against a shared
873library, that library is not closely incorporated into the final
874executable. Instead, the executable of your program only contains
875enough information to find the needed shared libraries when the program
876is actually run. Only then, when the program is starting, is the final
877step of the linking process performed. This means that you need not
878recompile all programs when you install a new, only slightly modified
879version of a shared library. The programs will pick up the changes
880automatically the next time they are run.
881
882Now, when all the necessary machinery is there to perform part of the
883linking at run-time, why not take the next step and allow the programmer
884to explicitly take advantage of it from within his program? Of course,
885many operating systems that support shared libraries do just that, and
886chances are that Guile will allow you to access this feature from within
887your Scheme programs. As you might have guessed already, this feature
888is called @dfn{dynamic linking}.@footnote{Some people also refer to the
889final linking stage at program startup as `dynamic linking', so if you
890want to make yourself perfectly clear, it is probably best to use the
891more technical term @dfn{dlopening}, as suggested by Gordon Matzigkeit
892in his libtool documentation.}
893
894As with many aspects of Guile, there is a low-level way to access the
895dynamic linking apparatus, and a more high-level interface that
896integrates dynamically linked libraries into the module system.
897
898@menu
899* Low level dynamic linking::
900* Compiled Code Modules::
901* Dynamic Linking and Compiled Code Modules::
902@end menu
903
904@node Low level dynamic linking
905@subsubsection Low level dynamic linking
906
907When using the low level procedures to do your dynamic linking, you have
908complete control over which library is loaded when and what gets done
909with it.
910
911@deffn {Scheme Procedure} dynamic-link library
912@deffnx {C Function} scm_dynamic_link (library)
913Find the shared library denoted by @var{library} (a string) and link it
914into the running Guile application. When everything works out, return a
915Scheme object suitable for representing the linked object file.
916Otherwise an error is thrown. How object files are searched is system
917dependent.
918
919Normally, @var{library} is just the name of some shared library file
920that will be searched for in the places where shared libraries usually
921reside, such as in @file{/usr/lib} and @file{/usr/local/lib}.
922@end deffn
923
924@deffn {Scheme Procedure} dynamic-object? obj
925@deffnx {C Function} scm_dynamic_object_p (obj)
926Return @code{#t} if @var{obj} is a dynamic library handle, or @code{#f}
927otherwise.
928@end deffn
929
930@deffn {Scheme Procedure} dynamic-unlink dobj
931@deffnx {C Function} scm_dynamic_unlink (dobj)
932Unlink the indicated object file from the application. The
933argument @var{dobj} must have been obtained by a call to
934@code{dynamic-link}. After @code{dynamic-unlink} has been
935called on @var{dobj}, its content is no longer accessible.
936@end deffn
937
938@deffn {Scheme Procedure} dynamic-func name dobj
939@deffnx {C Function} scm_dynamic_func (name, dobj)
940Search the dynamic object @var{dobj} for the C function
941indicated by the string @var{name} and return some Scheme
942handle that can later be used with @code{dynamic-call} to
943actually call the function.
944
945Regardless whether your C compiler prepends an underscore @samp{_} to
946the global names in a program, you should @strong{not} include this
947underscore in @var{function}. Guile knows whether the underscore is
948needed or not and will add it when necessary.
949@end deffn
950
951@deffn {Scheme Procedure} dynamic-call func dobj
952@deffnx {C Function} scm_dynamic_call (func, dobj)
953Call the C function indicated by @var{func} and @var{dobj}.
954The function is passed no arguments and its return value is
955ignored. When @var{function} is something returned by
956@code{dynamic-func}, call that function and ignore @var{dobj}.
957When @var{func} is a string , look it up in @var{dynobj}; this
958is equivalent to
959@smallexample
960(dynamic-call (dynamic-func @var{func} @var{dobj}) #f)
961@end smallexample
962
963Interrupts are deferred while the C function is executing (with
964@code{SCM_DEFER_INTS}/@code{SCM_ALLOW_INTS}).
965@end deffn
966
967@deffn {Scheme Procedure} dynamic-args-call func dobj args
968@deffnx {C Function} scm_dynamic_args_call (func, dobj, args)
969Call the C function indicated by @var{func} and @var{dobj},
970just like @code{dynamic-call}, but pass it some arguments and
971return its return value. The C function is expected to take
972two arguments and return an @code{int}, just like @code{main}:
973@smallexample
974int c_func (int argc, char **argv);
975@end smallexample
976
977The parameter @var{args} must be a list of strings and is
978converted into an array of @code{char *}. The array is passed
979in @var{argv} and its size in @var{argc}. The return value is
980converted to a Scheme number and returned from the call to
981@code{dynamic-args-call}.
982@end deffn
983
984When dynamic linking is disabled or not supported on your system,
985the above functions throw errors, but they are still available.
986
987Here is a small example that works on GNU/Linux:
988
989@smallexample
990(define libc-obj (dynamic-link "libc.so"))
991libc-obj
992@result{} #<dynamic-object "libc.so">
993(dynamic-args-call 'rand libc-obj '())
994@result{} 269167349
995(dynamic-unlink libc-obj)
996libc-obj
997@result{} #<dynamic-object "libc.so" (unlinked)>
998@end smallexample
999
1000As you can see, after calling @code{dynamic-unlink} on a dynamically
1001linked library, it is marked as @samp{(unlinked)} and you are no longer
1002able to use it with @code{dynamic-call}, etc. Whether the library is
1003really removed from you program is system-dependent and will generally
1004not happen when some other parts of your program still use it. In the
1005example above, @code{libc} is almost certainly not removed from your
1006program because it is badly needed by almost everything.
1007
1008The functions to call a function from a dynamically linked library,
1009@code{dynamic-call} and @code{dynamic-args-call}, are not very powerful.
1010They are mostly intended to be used for calling specially written
1011initialization functions that will then add new primitives to Guile.
1012For example, we do not expect that you will dynamically link
1013@file{libX11} with @code{dynamic-link} and then construct a beautiful
1014graphical user interface just by using @code{dynamic-call} and
1015@code{dynamic-args-call}. Instead, the usual way would be to write a
1016special Guile<->X11 glue library that has intimate knowledge about both
1017Guile and X11 and does whatever is necessary to make them inter-operate
1018smoothly. This glue library could then be dynamically linked into a
1019vanilla Guile interpreter and activated by calling its initialization
1020function. That function would add all the new types and primitives to
1021the Guile interpreter that it has to offer.
1022
1023From this setup the next logical step is to integrate these glue
1024libraries into the module system of Guile so that you can load new
1025primitives into a running system just as you can load new Scheme code.
1026
1027There is, however, another possibility to get a more thorough access to
1028the functions contained in a dynamically linked library. Anthony Green
1029has written @file{libffi}, a library that implements a @dfn{foreign
1030function interface} for a number of different platforms. With it, you
1031can extend the Spartan functionality of @code{dynamic-call} and
1032@code{dynamic-args-call} considerably. There is glue code available in
1033the Guile contrib archive to make @file{libffi} accessible from Guile.
1034
1035@node Compiled Code Modules
1036@subsubsection Putting Compiled Code into Modules
1037
1038The new primitives that you add to Guile with
1039@code{scm_c_define_gsubr} (@pxref{Primitive Procedures}) or with any
1040of the other mechanisms are placed into the @code{(guile-user)} module
1041by default. However, it is also possible to put new primitives into
1042other modules.
1043
1044The mechanism for doing so is not very well thought out and is likely to
1045change when the module system of Guile itself is revised, but it is
1046simple and useful enough to document it as it stands.
1047
1048What @code{scm_c_define_gsubr} and the functions used by the snarfer
1049really do is to add the new primitives to whatever module is the
1050@emph{current module} when they are called. This is analogous to the
1051way Scheme code is put into modules: the @code{define-module} expression
1052at the top of a Scheme source file creates a new module and makes it the
1053current module while the rest of the file is evaluated. The
1054@code{define} expressions in that file then add their new definitions to
1055this current module.
1056
1057Therefore, all we need to do is to make sure that the right module is
1058current when calling @code{scm_c_define_gsubr} for our new primitives.
1059
1060@node Dynamic Linking and Compiled Code Modules
1061@subsubsection Dynamic Linking and Compiled Code Modules
1062
1063The most interesting application of dynamically linked libraries is
1064probably to use them for providing @emph{compiled code modules} to
1065Scheme programs. As much fun as programming in Scheme is, every now and
1066then comes the need to write some low-level C stuff to make Scheme even
1067more fun.
1068
1069Not only can you put these new primitives into their own module (see the
1070previous section), you can even put them into a shared library that is
1071only then linked to your running Guile image when it is actually
1072needed.
1073
1074An example will hopefully make everything clear. Suppose we want to
1075make the Bessel functions of the C library available to Scheme in the
1076module @samp{(math bessel)}. First we need to write the appropriate
1077glue code to convert the arguments and return values of the functions
1078from Scheme to C and back. Additionally, we need a function that will
1079add them to the set of Guile primitives. Because this is just an
1080example, we will only implement this for the @code{j0} function.
1081
1082@c FIXME::martin: Change all gh_ references to their scm_ equivalents.
1083
1084@smallexample
1085#include <math.h>
1086#include <libguile.h>
1087
1088SCM
1089j0_wrapper (SCM x)
1090@{
1091 return scm_double2num (j0 (scm_num2dbl (x, "j0")));
1092@}
1093
1094void
1095init_math_bessel ()
1096@{
1097 scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
1098@}
1099@end smallexample
1100
1101We can already try to bring this into action by manually calling the low
1102level functions for performing dynamic linking. The C source file needs
1103to be compiled into a shared library. Here is how to do it on
1104GNU/Linux, please refer to the @code{libtool} documentation for how to
1105create dynamically linkable libraries portably.
1106
1107@smallexample
1108gcc -shared -o libbessel.so -fPIC bessel.c
1109@end smallexample
1110
1111Now fire up Guile:
1112
1113@smalllisp
1114(define bessel-lib (dynamic-link "./libbessel.so"))
1115(dynamic-call "init_math_bessel" bessel-lib)
1116(j0 2)
1117@result{} 0.223890779141236
1118@end smalllisp
1119
1120The filename @file{./libbessel.so} should be pointing to the shared
1121library produced with the @code{gcc} command above, of course. The
1122second line of the Guile interaction will call the
1123@code{init_math_bessel} function which in turn will register the C
1124function @code{j0_wrapper} with the Guile interpreter under the name
1125@code{j0}. This function becomes immediately available and we can call
1126it from Scheme.
1127
1128Fun, isn't it? But we are only half way there. This is what
1129@code{apropos} has to say about @code{j0}:
1130
1131@smallexample
1132(apropos "j0")
1133@print{} (guile-user): j0 #<primitive-procedure j0>
1134@end smallexample
1135
1136As you can see, @code{j0} is contained in the root module, where all
1137the other Guile primitives like @code{display}, etc live. In general,
1138a primitive is put into whatever module is the @dfn{current module} at
1139the time @code{scm_c_define_gsubr} is called.
1140
1141A compiled module should have a specially named @dfn{module init
1142function}. Guile knows about this special name and will call that
1143function automatically after having linked in the shared library. For
1144our example, we replace @code{init_math_bessel} with the following code in
1145@file{bessel.c}:
1146
1147@smallexample
1148void
1149init_math_bessel (void *unused)
1150@{
1151 scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
1152 scm_c_export ("j0", NULL);
1153@}
1154
1155void
1156scm_init_math_bessel_module ()
1157@{
1158 scm_c_define_module ("math bessel", init_math_bessel, NULL);
1159@}
1160@end smallexample
1161
1162The general pattern for the name of a module init function is:
1163@samp{scm_init_}, followed by the name of the module where the
1164individual hierarchical components are concatenated with underscores,
1165followed by @samp{_module}.
1166
1167After @file{libbessel.so} has been rebuilt, we need to place the shared
1168library into the right place.
1169
1170Once the module has been correctly installed, it should be possible to
1171use it like this:
1172
1173@smallexample
1174guile> (load-extension "./libbessel.so" "scm_init_math_bessel_module")
1175guile> (use-modules (math bessel))
1176guile> (j0 2)
11770.223890779141236
1178guile> (apropos "j0")
1179@print{} (math bessel): j0 #<primitive-procedure j0>
1180@end smallexample
1181
1182That's it!
1183
cdf1ad3b
MV
1184@deffn {Scheme Procedure} load-extension lib init
1185@deffnx {C Function} scm_load_extension (lib, init)
1186Load and initialize the extension designated by LIB and INIT.
1187When there is no pre-registered function for LIB/INIT, this is
1188equivalent to
1189
1190@lisp
1191(dynamic-call INIT (dynamic-link LIB))
1192@end lisp
1193
1194When there is a pre-registered function, that function is called
1195instead.
1196
1197Normally, there is no pre-registered function. This option exists
1198only for situations where dynamic linking is unavailable or unwanted.
1199In that case, you would statically link your program with the desired
1200library, and register its init function right after Guile has been
1201initialized.
1202
1203LIB should be a string denoting a shared library without any file type
1204suffix such as ".so". The suffix is provided automatically. It
1205should also not contain any directory components. Libraries that
1206implement Guile Extensions should be put into the normal locations for
1207shared libraries. We recommend to use the naming convention
1208libguile-bla-blum for a extension related to a module `(bla blum)'.
1209
1210The normal way for a extension to be used is to write a small Scheme
1211file that defines a module, and to load the extension into this
1212module. When the module is auto-loaded, the extension is loaded as
1213well. For example,
1214
1215@lisp
1216(define-module (bla blum))
1217
1218(load-extension "libguile-bla-blum" "bla_init_blum")
1219@end lisp
1220@end deffn
1221
07d83abe
MV
1222@node Variables
1223@subsection Variables
1224@tpindex Variables
1225
1226Each module has its own hash table, sometimes known as an @dfn{obarray},
1227that maps the names defined in that module to their corresponding
1228variable objects.
1229
1230A variable is a box-like object that can hold any Scheme value. It is
1231said to be @dfn{undefined} if its box holds a special Scheme value that
1232denotes undefined-ness (which is different from all other Scheme values,
1233including for example @code{#f}); otherwise the variable is
1234@dfn{defined}.
1235
1236On its own, a variable object is anonymous. A variable is said to be
1237@dfn{bound} when it is associated with a name in some way, usually a
1238symbol in a module obarray. When this happens, the relationship is
1239mutual: the variable is bound to the name (in that module), and the name
1240(in that module) is bound to the variable.
1241
1242(That's the theory, anyway. In practice, defined-ness and bound-ness
1243sometimes get confused, because Lisp and Scheme implementations have
1244often conflated --- or deliberately drawn no distinction between --- a
1245name that is unbound and a name that is bound to a variable whose value
1246is undefined. We will try to be clear about the difference and explain
1247any confusion where it is unavoidable.)
1248
1249Variables do not have a read syntax. Most commonly they are created and
1250bound implicitly by @code{define} expressions: a top-level @code{define}
1251expression of the form
1252
1253@lisp
1254(define @var{name} @var{value})
1255@end lisp
1256
1257@noindent
1258creates a variable with initial value @var{value} and binds it to the
1259name @var{name} in the current module. But they can also be created
1260dynamically by calling one of the constructor procedures
1261@code{make-variable} and @code{make-undefined-variable}.
1262
1263First-class variables are especially useful for interacting with the
1264current module system (@pxref{The Guile module system}).
1265
1266@deffn {Scheme Procedure} make-undefined-variable
1267@deffnx {C Function} scm_make_undefined_variable ()
1268Return a variable that is initially unbound.
1269@end deffn
1270
1271@deffn {Scheme Procedure} make-variable init
1272@deffnx {C Function} scm_make_variable (init)
1273Return a variable initialized to value @var{init}.
1274@end deffn
1275
1276@deffn {Scheme Procedure} variable-bound? var
1277@deffnx {C Function} scm_variable_bound_p (var)
1278Return @code{#t} iff @var{var} is bound to a value.
1279Throws an error if @var{var} is not a variable object.
1280@end deffn
1281
1282@deffn {Scheme Procedure} variable-ref var
1283@deffnx {C Function} scm_variable_ref (var)
1284Dereference @var{var} and return its value.
1285@var{var} must be a variable object; see @code{make-variable}
1286and @code{make-undefined-variable}.
1287@end deffn
1288
1289@deffn {Scheme Procedure} variable-set! var val
1290@deffnx {C Function} scm_variable_set_x (var, val)
1291Set the value of the variable @var{var} to @var{val}.
1292@var{var} must be a variable object, @var{val} can be any
1293value. Return an unspecified value.
1294@end deffn
1295
1296@deffn {Scheme Procedure} variable? obj
1297@deffnx {C Function} scm_variable_p (obj)
1298Return @code{#t} iff @var{obj} is a variable object, else
1299return @code{#f}.
1300@end deffn
1301
1302
1303@c Local Variables:
1304@c TeX-master: "guile.texi"
1305@c End: