Merge commit '58147d67806e1f54c447d7eabac35b1a5086c3a6'
[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.
994d87be 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2008, 2009, 2010, 2011, 2012, 2013
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
07d83abe
MV
7@node Modules
8@section Modules
9@cindex modules
10
11When programs become large, naming conflicts can occur when a function
12or global variable defined in one file has the same name as a function
13or global variable in another file. Even just a @emph{similarity}
14between function names can cause hard-to-find bugs, since a programmer
15might type the wrong function name.
16
17The approach used to tackle this problem is called @emph{information
18encapsulation}, which consists of packaging functional units into a
19given name space that is clearly separated from other name spaces.
20@cindex encapsulation
21@cindex information encapsulation
22@cindex name space
23
24The language features that allow this are usually called @emph{the
25module system} because programs are broken up into modules that are
26compiled separately (or loaded separately in an interpreter).
27
28Older languages, like C, have limited support for name space
29manipulation and protection. In C a variable or function is public by
30default, and can be made local to a module with the @code{static}
31keyword. But you cannot reference public variables and functions from
32another module with different names.
33
34More advanced module systems have become a common feature in recently
35designed languages: ML, Python, Perl, and Modula 3 all allow the
36@emph{renaming} of objects from a foreign module, so they will not
37clutter the global name space.
38@cindex name space - private
39
40In addition, Guile offers variables as first-class objects. They can
41be used for interacting with the module system.
42
07d83abe
MV
43@menu
44* General Information about Modules:: Guile module basics.
45* Using Guile Modules:: How to use existing modules.
46* Creating Guile Modules:: How to package your code into modules.
992a3879 47* Modules and the File System:: Installing modules in the file system.
dca14012 48* R6RS Version References:: Using version numbers with modules.
71194485 49* R6RS Libraries:: The library and import forms.
726b8ba3 50* Variables:: First-class variables.
992a3879
AW
51* Module System Reflection:: First-class modules.
52* Accessing Modules from C:: How to work with modules with C code.
726b8ba3
AW
53* provide and require:: The SLIB feature mechanism.
54* Environments:: R5RS top-level environments.
07d83abe
MV
55@end menu
56
57@node General Information about Modules
726b8ba3 58@subsection General Information about Modules
07d83abe
MV
59
60A Guile module can be thought of as a collection of named procedures,
61variables and macros. More precisely, it is a set of @dfn{bindings}
62of symbols (names) to Scheme objects.
63
07d83abe
MV
64Within a module, all bindings are visible. Certain bindings
65can be declared @dfn{public}, in which case they are added to the
66module's so-called @dfn{export list}; this set of public bindings is
67called the module's @dfn{public interface} (@pxref{Creating Guile
68Modules}).
69
70A client module @dfn{uses} a providing module's bindings by either
71accessing the providing module's public interface, or by building a
72custom interface (and then accessing that). In a custom interface, the
73client module can @dfn{select} which bindings to access and can also
74algorithmically @dfn{rename} bindings. In contrast, when using the
75providing module's public interface, the entire export list is available
76without renaming (@pxref{Using Guile Modules}).
77
992a3879
AW
78All Guile modules have a unique @dfn{module name}, for example
79@code{(ice-9 popen)} or @code{(srfi srfi-11)}. Module names are lists
80of one or more symbols.
81
82When Guile goes to use an interface from a module, for example
83@code{(ice-9 popen)}, Guile first looks to see if it has loaded
84@code{(ice-9 popen)} for any reason. If the module has not been loaded
85yet, Guile searches a @dfn{load path} for a file that might define it,
86and loads that file.
07d83abe 87
992a3879
AW
88The following subsections go into more detail on using, creating,
89installing, and otherwise manipulating modules and the module system.
07d83abe
MV
90
91@node Using Guile Modules
726b8ba3 92@subsection Using Guile Modules
07d83abe
MV
93
94To use a Guile module is to access either its public interface or a
95custom interface (@pxref{General Information about Modules}). Both
96types of access are handled by the syntactic form @code{use-modules},
97which accepts one or more interface specifications and, upon evaluation,
98arranges for those interfaces to be available to the current module.
99This process may include locating and loading code for a given module if
0740cb49
AW
100that code has not yet been loaded, following @code{%load-path}
101(@pxref{Modules and the File System}).
07d83abe
MV
102
103An @dfn{interface specification} has one of two forms. The first
104variation is simply to name the module, in which case its public
105interface is the one accessed. For example:
106
aba0dff5 107@lisp
07d83abe 108(use-modules (ice-9 popen))
aba0dff5 109@end lisp
07d83abe
MV
110
111Here, the interface specification is @code{(ice-9 popen)}, and the
112result is that the current module now has access to @code{open-pipe},
254d313a 113@code{close-pipe}, @code{open-input-pipe}, and so on (@pxref{Pipes}).
07d83abe
MV
114
115Note in the previous example that if the current module had already
116defined @code{open-pipe}, that definition would be overwritten by the
117definition in @code{(ice-9 popen)}. For this reason (and others), there
118is a second variation of interface specification that not only names a
119module to be accessed, but also selects bindings from it and renames
120them to suit the current module's needs. For example:
121
46bb559d 122@cindex binding renamer
aba0dff5 123@lisp
07d83abe 124(use-modules ((ice-9 popen)
8d9cb14e
NJ
125 #:select ((open-pipe . pipe-open) close-pipe)
126 #:renamer (symbol-prefix-proc 'unixy:)))
aba0dff5 127@end lisp
07d83abe
MV
128
129Here, the interface specification is more complex than before, and the
130result is that a custom interface with only two bindings is created and
131subsequently accessed by the current module. The mapping of old to new
132names is as follows:
133
134@c Use `smallexample' since `table' is ugly. --ttn
135@smallexample
136(ice-9 popen) sees: current module sees:
137open-pipe unixy:pipe-open
138close-pipe unixy:close-pipe
139@end smallexample
140
141This example also shows how to use the convenience procedure
142@code{symbol-prefix-proc}.
143
144You can also directly refer to bindings in a module by using the
145@code{@@} syntax. For example, instead of using the
146@code{use-modules} statement from above and writing
147@code{unixy:pipe-open} to refer to the @code{pipe-open} from the
148@code{(ice-9 popen)}, you could also write @code{(@@ (ice-9 popen)
149open-pipe)}. Thus an alternative to the complete @code{use-modules}
150statement would be
151
aba0dff5 152@lisp
07d83abe
MV
153(define unixy:pipe-open (@@ (ice-9 popen) open-pipe))
154(define unixy:close-pipe (@@ (ice-9 popen) close-pipe))
aba0dff5 155@end lisp
07d83abe
MV
156
157There is also @code{@@@@}, which can be used like @code{@@}, but does
158not check whether the variable that is being accessed is actually
159exported. Thus, @code{@@@@} can be thought of as the impolite version
160of @code{@@} and should only be used as a last resort or for
161debugging, for example.
162
163Note that just as with a @code{use-modules} statement, any module that
164has not yet been loaded yet will be loaded when referenced by a
165@code{@@} or @code{@@@@} form.
166
167You can also use the @code{@@} and @code{@@@@} syntaxes as the target
168of a @code{set!} when the binding refers to a variable.
169
07d83abe
MV
170@deffn {Scheme Procedure} symbol-prefix-proc prefix-sym
171Return a procedure that prefixes its arg (a symbol) with
172@var{prefix-sym}.
07d83abe
MV
173@end deffn
174
07d83abe
MV
175@deffn syntax use-modules spec @dots{}
176Resolve each interface specification @var{spec} into an interface and
177arrange for these to be accessible by the current module. The return
178value is unspecified.
179
180@var{spec} can be a list of symbols, in which case it names a module
181whose public interface is found and used.
182
183@var{spec} can also be of the form:
184
46bb559d 185@cindex binding renamer
aba0dff5 186@lisp
992a3879 187 (MODULE-NAME [#:select SELECTION] [#:renamer RENAMER])
aba0dff5 188@end lisp
07d83abe
MV
189
190in which case a custom interface is newly created and used.
191@var{module-name} is a list of symbols, as above; @var{selection} is a
192list of selection-specs; and @var{renamer} is a procedure that takes a
193symbol and returns its new name. A selection-spec is either a symbol or
194a pair of symbols @code{(ORIG . SEEN)}, where @var{orig} is the name in
195the used module and @var{seen} is the name in the using module. Note
196that @var{seen} is also passed through @var{renamer}.
197
992a3879
AW
198The @code{#:select} and @code{#:renamer} clauses are optional. If both are
199omitted, the returned interface has no bindings. If the @code{#:select}
07d83abe
MV
200clause is omitted, @var{renamer} operates on the used module's public
201interface.
202
992a3879 203In addition to the above, @var{spec} can also include a @code{#:version}
dca14012
JG
204clause, of the form:
205
206@lisp
992a3879 207 #:version VERSION-SPEC
dca14012
JG
208@end lisp
209
992a3879
AW
210where @var{version-spec} is an R6RS-compatible version reference. An
211error will be signaled in the case in which a module with the same name
212has already been loaded, if that module specifies a version and that
213version is not compatible with @var{version-spec}. @xref{R6RS Version
214References}, for more on version references.
07d83abe 215
992a3879
AW
216If the module name is not resolvable, @code{use-modules} will signal an
217error.
07d83abe
MV
218@end deffn
219
220@deffn syntax @@ module-name binding-name
221Refer to the binding named @var{binding-name} in module
222@var{module-name}. The binding must have been exported by the module.
223@end deffn
224
225@deffn syntax @@@@ module-name binding-name
226Refer to the binding named @var{binding-name} in module
227@var{module-name}. The binding must not have been exported by the
228module. This syntax is only intended for debugging purposes or as a
229last resort.
230@end deffn
231
232@node Creating Guile Modules
726b8ba3 233@subsection Creating Guile Modules
07d83abe
MV
234
235When you want to create your own modules, you have to take the following
236steps:
237
238@itemize @bullet
239@item
240Create a Scheme source file and add all variables and procedures you wish
241to export, or which are required by the exported procedures.
242
243@item
244Add a @code{define-module} form at the beginning.
245
246@item
247Export all bindings which should be in the public interface, either
248by using @code{define-public} or @code{export} (both documented below).
249@end itemize
250
df0a1002 251@deffn syntax define-module module-name option @dots{}
992a3879 252@var{module-name} is a list of one or more symbols.
07d83abe 253
aba0dff5 254@lisp
07d83abe 255(define-module (ice-9 popen))
aba0dff5 256@end lisp
07d83abe
MV
257
258@code{define-module} makes this module available to Guile programs under
259the given @var{module-name}.
260
df0a1002
BT
261@var{option} @dots{} are keyword/value pairs which specify more about the
262defined module. The recognized options and their meaning are shown in
07d83abe
MV
263the following table.
264
07d83abe
MV
265@table @code
266@item #:use-module @var{interface-specification}
267Equivalent to a @code{(use-modules @var{interface-specification})}
268(@pxref{Using Guile Modules}).
269
950f97ac 270@item #:autoload @var{module} @var{symbol-list}
65f1345f 271@cindex autoload
950f97ac
KR
272Load @var{module} when any of @var{symbol-list} are accessed. For
273example,
274
275@example
276(define-module (my mod)
277 #:autoload (srfi srfi-1) (partition delete-duplicates))
278...
279(if something
280 (set! foo (delete-duplicates ...)))
281@end example
282
a236df75 283When a module is autoloaded, all its bindings become available.
950f97ac
KR
284@var{symbol-list} is just those that will first trigger the load.
285
286An autoload is a good way to put off loading a big module until it's
287really needed, for instance for faster startup or if it will only be
288needed in certain circumstances.
289
290@code{@@} can do a similar thing (@pxref{Using Guile Modules}), but in
291that case an @code{@@} form must be written every time a binding from
292the module is used.
07d83abe
MV
293
294@item #:export @var{list}
65f1345f 295@cindex export
78c22f5e 296Export all identifiers in @var{list} which must be a list of symbols
992a3879 297or pairs of symbols. This is equivalent to @code{(export @var{list})}
78c22f5e 298in the module body.
07d83abe 299
46bb559d
KR
300@item #:re-export @var{list}
301@cindex re-export
302Re-export all identifiers in @var{list} which must be a list of
78c22f5e
JG
303symbols or pairs of symbols. The symbols in @var{list} must be
304imported by the current module from other modules. This is equivalent
305to @code{re-export} below.
46bb559d 306
46bb559d
KR
307@item #:replace @var{list}
308@cindex replace
309@cindex replacing binding
310@cindex overriding binding
311@cindex duplicate binding
78c22f5e
JG
312Export all identifiers in @var{list} (a list of symbols or pairs of
313symbols) and mark them as @dfn{replacing bindings}. In the module
314user's name space, this will have the effect of replacing any binding
315with the same name that is not also ``replacing''. Normally a
316replacement results in an ``override'' warning message,
317@code{#:replace} avoids that.
46bb559d 318
d68a81e0
AW
319In general, a module that exports a binding for which the @code{(guile)}
320module already has a definition should use @code{#:replace} instead of
321@code{#:export}. @code{#:replace}, in a sense, lets Guile know that the
322module @emph{purposefully} replaces a core binding. It is important to
323note, however, that this binding replacement is confined to the name
324space of the module user. In other words, the value of the core binding
325in question remains unchanged for other modules.
326
327Note that although it is often a good idea for the replaced binding to
328remain compatible with a binding in @code{(guile)}, to avoid surprising
329the user, sometimes the bindings will be incompatible. For example,
330SRFI-19 exports its own version of @code{current-time} (@pxref{SRFI-19
331Time}) which is not compatible with the core @code{current-time}
332function (@pxref{Time}). Guile assumes that a user importing a module
333knows what she is doing, and uses @code{#:replace} for this binding
334rather than @code{#:export}.
e724644d 335
992a3879
AW
336A @code{#:replace} clause is equivalent to @code{(export! @var{list})}
337in the module body.
338
e724644d
MV
339The @code{#:duplicates} (see below) provides fine-grain control about
340duplicate binding handling on the module-user side.
46bb559d 341
dca14012
JG
342@item #:version @var{list}
343@cindex module version
344Specify a version for the module in the form of @var{list}, a list of
345zero or more exact, nonnegative integers. The corresponding
346@code{#:version} option in the @code{use-modules} form allows callers
347to restrict the value of this option in various ways.
348
46bb559d
KR
349@item #:duplicates @var{list}
350@cindex duplicate binding handlers
351@cindex duplicate binding
352@cindex overriding binding
353Tell Guile to handle duplicate bindings for the bindings imported by
354the current module according to the policy defined by @var{list}, a
355list of symbols. @var{list} must contain symbols representing a
356duplicate binding handling policy chosen among the following:
357
358@table @code
359@item check
360Raises an error when a binding is imported from more than one place.
361@item warn
362Issue a warning when a binding is imported from more than one place
363and leave the responsibility of actually handling the duplication to
364the next duplicate binding handler.
365@item replace
366When a new binding is imported that has the same name as a previously
367imported binding, then do the following:
368
369@enumerate
370@item
371@cindex replacing binding
372If the old binding was said to be @dfn{replacing} (via the
373@code{#:replace} option above) and the new binding is not replacing,
374the keep the old binding.
375@item
376If the old binding was not said to be replacing and the new binding is
377replacing, then replace the old binding with the new one.
378@item
379If neither the old nor the new binding is replacing, then keep the old
380one.
381@end enumerate
382
383@item warn-override-core
384Issue a warning when a core binding is being overwritten and actually
385override the core binding with the new one.
386@item first
387In case of duplicate bindings, the firstly imported binding is always
388the one which is kept.
389@item last
390In case of duplicate bindings, the lastly imported binding is always
391the one which is kept.
392@item noop
393In case of duplicate bindings, leave the responsibility to the next
394duplicate handler.
395@end table
396
397If @var{list} contains more than one symbol, then the duplicate
398binding handlers which appear first will be used first when resolving
399a duplicate binding situation. As mentioned above, some resolution
400policies may explicitly leave the responsibility of handling the
401duplication to the next handler in @var{list}.
402
992a3879
AW
403If GOOPS has been loaded before the @code{#:duplicates} clause is
404processed, there are additional strategies available for dealing with
405generic functions. @xref{Merging Generics}, for more information.
406
46bb559d
KR
407@findex default-duplicate-binding-handler
408The default duplicate binding resolution policy is given by the
409@code{default-duplicate-binding-handler} procedure, and is
410
aba0dff5 411@lisp
46bb559d 412(replace warn-override-core warn last)
aba0dff5 413@end lisp
46bb559d 414
07d83abe 415@item #:pure
65f1345f 416@cindex pure module
07d83abe
MV
417Create a @dfn{pure} module, that is a module which does not contain any
418of the standard procedure bindings except for the syntax forms. This is
419useful if you want to create @dfn{safe} modules, that is modules which
420do not know anything about dangerous procedures.
421@end table
422
423@end deffn
07d83abe
MV
424
425@deffn syntax export variable @dots{}
78c22f5e
JG
426Add all @var{variable}s (which must be symbols or pairs of symbols) to
427the list of exported bindings of the current module. If @var{variable}
428is a pair, its @code{car} gives the name of the variable as seen by the
429current module and its @code{cdr} specifies a name for the binding in
430the current module's public interface.
07d83abe
MV
431@end deffn
432
07d83abe
MV
433@deffn syntax define-public @dots{}
434Equivalent to @code{(begin (define foo ...) (export foo))}.
435@end deffn
07d83abe 436
46bb559d 437@deffn syntax re-export variable @dots{}
78c22f5e
JG
438Add all @var{variable}s (which must be symbols or pairs of symbols) to
439the list of re-exported bindings of the current module. Pairs of
440symbols are handled as in @code{export}. Re-exported bindings must be
441imported by the current module from some other module.
46bb559d
KR
442@end deffn
443
992a3879
AW
444@deffn syntax export! variable @dots{}
445Like @code{export}, but marking the exported variables as replacing.
446Using a module with replacing bindings will cause any existing bindings
447to be replaced without issuing any warnings. See the discussion of
448@code{#:replace} above.
cdf1ad3b
MV
449@end deffn
450
992a3879
AW
451@node Modules and the File System
452@subsection Modules and the File System
07d83abe 453
992a3879
AW
454Typical programs only use a small subset of modules installed on a Guile
455system. In order to keep startup time down, Guile only loads modules
456when a program uses them, on demand.
e376f9e5 457
992a3879
AW
458When a program evaluates @code{(use-modules (ice-9 popen))}, and the
459module is not loaded, Guile searches for a conventionally-named file
460from in the @dfn{load path}.
07d83abe 461
992a3879
AW
462In this case, loading @code{(ice-9 popen)} will eventually cause Guile
463to run @code{(primitive-load-path "ice-9/popen")}.
464@code{primitive-load-path} will search for a file @file{ice-9/popen} in
0740cb49 465the @code{%load-path} (@pxref{Load Paths}). For each directory in
992a3879
AW
466@code{%load-path}, Guile will try to find the file name, concatenated
467with the extensions from @code{%load-extensions}. By default, this will
468cause Guile to @code{stat} @file{ice-9/popen.scm}, and then
925172cf 469@file{ice-9/popen}. @xref{Load Paths}, for more on
992a3879 470@code{primitive-load-path}.
e376f9e5 471
992a3879
AW
472If a corresponding compiled @file{.go} file is found in the
473@code{%load-compiled-path} or in the fallback path, and is as fresh as
474the source file, it will be loaded instead of the source file. If no
475compiled file is found, Guile may try to compile the source file and
476cache away the resulting @file{.go} file. @xref{Compilation}, for more
477on compilation.
07d83abe 478
992a3879
AW
479Once Guile finds a suitable source or compiled file is found, the file
480will be loaded. If, after loading the file, the module under
481consideration is still not defined, Guile will signal an error.
e376f9e5 482
992a3879
AW
483For more information on where and how to install Scheme modules,
484@xref{Installing Site Packages}.
07d83abe
MV
485
486
dca14012 487@node R6RS Version References
726b8ba3 488@subsection R6RS Version References
dca14012
JG
489
490Guile's module system includes support for locating modules based on
491a declared version specifier of the same form as the one described in
492R6RS (@pxref{Library form, R6RS Library Form,, r6rs, The Revised^6
493Report on the Algorithmic Language Scheme}). By using the
494@code{#:version} keyword in a @code{define-module} form, a module may
495specify a version as a list of zero or more exact, nonnegative integers.
496
497This version can then be used to locate the module during the module
498search process. Client modules and callers of the @code{use-modules}
499function may specify constraints on the versions of target modules by
500providing a @dfn{version reference}, which has one of the following
501forms:
502
503@lisp
504 (@var{sub-version-reference} ...)
505 (and @var{version-reference} ...)
506 (or @var{version-reference} ...)
507 (not @var{version-reference})
508@end lisp
509
510in which @var{sub-version-reference} is in turn one of:
511
512@lisp
513 (@var{sub-version})
514 (>= @var{sub-version})
515 (<= @var{sub-version})
516 (and @var{sub-version-reference} ...)
517 (or @var{sub-version-reference} ...)
518 (not @var{sub-version-reference})
519@end lisp
520
521in which @var{sub-version} is an exact, nonnegative integer as above. A
522version reference matches a declared module version if each element of
523the version reference matches a corresponding element of the module
524version, according to the following rules:
525
526@itemize @bullet
527@item
528The @code{and} sub-form matches a version or version element if every
529element in the tail of the sub-form matches the specified version or
530version element.
531
532@item
533The @code{or} sub-form matches a version or version element if any
534element in the tail of the sub-form matches the specified version or
535version element.
536
537@item
538The @code{not} sub-form matches a version or version element if the tail
539of the sub-form does not match the version or version element.
540
541@item
542The @code{>=} sub-form matches a version element if the element is
543greater than or equal to the @var{sub-version} in the tail of the
544sub-form.
545
546@item
547The @code{<=} sub-form matches a version element if the version is less
548than or equal to the @var{sub-version} in the tail of the sub-form.
549
550@item
551A @var{sub-version} matches a version element if one is @var{eqv?} to
552the other.
553@end itemize
554
555For example, a module declared as:
556
557@lisp
558 (define-module (mylib mymodule) #:version (1 2 0))
559@end lisp
560
561would be successfully loaded by any of the following @code{use-modules}
562expressions:
563
564@lisp
565 (use-modules ((mylib mymodule) #:version (1 2 (>= 0))))
566 (use-modules ((mylib mymodule) #:version (or (1 2 0) (1 2 1))))
567 (use-modules ((mylib mymodule) #:version ((and (>= 1) (not 2)) 2 0)))
568@end lisp
569
570
71194485
JG
571@node R6RS Libraries
572@subsection R6RS Libraries
573
574In addition to the API described in the previous sections, you also
43d6eb75 575have the option to create modules using the portable @code{library} form
71194485
JG
576described in R6RS (@pxref{Library form, R6RS Library Form,, r6rs, The
577Revised^6 Report on the Algorithmic Language Scheme}), and to import
578libraries created in this format by other programmers. Guile's R6RS
43d6eb75
JG
579library implementation takes advantage of the flexibility built into the
580module system by expanding the R6RS library form into a corresponding
581Guile @code{define-module} form that specifies equivalent import and
582export requirements and includes the same body expressions. The library
583expression:
71194485
JG
584
585@lisp
586 (library (mylib (1 2))
587 (import (otherlib (3)))
588 (export mybinding))
589@end lisp
590
591is equivalent to the module definition:
592
593@lisp
594 (define-module (mylib)
595 #:version (1 2)
596 #:use-module ((otherlib) #:version (3))
597 #:export (mybinding))
598@end lisp
599
600Central to the mechanics of R6RS libraries is the concept of import
43d6eb75 601and export @dfn{levels}, which control the visibility of bindings at
71194485
JG
602various phases of a library's lifecycle --- macros necessary to
603expand forms in the library's body need to be available at expand
604time; variables used in the body of a procedure exported by the
605library must be available at runtime. R6RS specifies the optional
606@code{for} sub-form of an @emph{import set} specification (see below)
607as a mechanism by which a library author can indicate that a
608particular library import should take place at a particular phase
609with respect to the lifecycle of the importing library.
610
c8eb2797 611Guile's library implementation uses a technique called
43d6eb75
JG
612@dfn{implicit phasing} (first described by Abdulaziz Ghuloum and R.
613Kent Dybvig), which allows the expander and compiler to automatically
614determine the necessary visibility of a binding imported from another
615library. As such, the @code{for} sub-form described below is ignored by
616Guile (but may be required by Schemes in which phasing is explicit).
71194485 617
43d6eb75 618@deffn {Scheme Syntax} library name (export export-spec ...) (import import-spec ...) body ...
71194485
JG
619Defines a new library with the specified name, exports, and imports,
620and evaluates the specified body expressions in this library's
621environment.
622
623The library @var{name} is a non-empty list of identifiers, optionally
624ending with a version specification of the form described above
625(@pxref{Creating Guile Modules}).
626
627Each @var{export-spec} is the name of a variable defined or imported
628by the library, or must take the form
629@code{(rename (internal-name external-name) ...)}, where the
630identifier @var{internal-name} names a variable defined or imported
631by the library and @var{external-name} is the name by which the
632variable is seen by importing libraries.
633
43d6eb75 634Each @var{import-spec} must be either an @dfn{import set} (see below)
71194485
JG
635or must be of the form @code{(for import-set import-level ...)},
636where each @var{import-level} is one of:
637
638@lisp
639 run
640 expand
641 (meta @var{level})
642@end lisp
643
644where @var{level} is an integer. Note that since Guile does not
645require explicit phase specification, any @var{import-set}s found
646inside of @code{for} sub-forms will be ``unwrapped'' during
647expansion and processed as if they had been specified directly.
648
649Import sets in turn take one of the following forms:
650
651@lisp
652 @var{library-reference}
653 (library @var{library-reference})
654 (only @var{import-set} @var{identifier} ...)
655 (except @var{import-set} @var{identifier} ...)
656 (prefix @var{import-set} @var{identifier})
657 (rename @var{import-set} (@var{internal-identifier} @var{external-identifier}) ...)
658@end lisp
659
660where @var{library-reference} is a non-empty list of identifiers
661ending with an optional version reference (@pxref{R6RS Version
662References}), and the other sub-forms have the following semantics,
663defined recursively on nested @var{import-set}s:
664
665@itemize @bullet
666
667@item
668The @code{library} sub-form is used to specify libraries for import
669whose names begin with the identifier ``library.''
670
671@item
672The @code{only} sub-form imports only the specified @var{identifier}s
673from the given @var{import-set}.
674
675@item
676The @code{except} sub-form imports all of the bindings exported by
677@var{import-set} except for those that appear in the specified list
678of @var{identifier}s.
679
680@item
681The @code{prefix} sub-form imports all of the bindings exported
682by @var{import-set}, first prefixing them with the specified
683@var{identifier}.
684
685@item
686The @code{rename} sub-form imports all of the identifiers exported
687by @var{import-set}. The binding for each @var{internal-identifier}
688among these identifiers is made visible to the importing library as
689the corresponding @var{external-identifier}; all other bindings are
690imported using the names provided by @var{import-set}.
691
692@end itemize
693
694Note that because Guile translates R6RS libraries into module
695definitions, an import specification may be used to declare a
696dependency on a native Guile module --- although doing so may make
697your libraries less portable to other Schemes.
698
699@end deffn
700
43d6eb75 701@deffn {Scheme Syntax} import import-spec ...
71194485
JG
702Import into the current environment the libraries specified by the
703given import specifications, where each @var{import-spec} takes the
43d6eb75 704same form as in the @code{library} form described above.
71194485
JG
705@end deffn
706
707
992a3879
AW
708@node Variables
709@subsection Variables
710@tpindex Variables
711
712Each module has its own hash table, sometimes known as an @dfn{obarray},
713that maps the names defined in that module to their corresponding
714variable objects.
715
716A variable is a box-like object that can hold any Scheme value. It is
717said to be @dfn{undefined} if its box holds a special Scheme value that
718denotes undefined-ness (which is different from all other Scheme values,
719including for example @code{#f}); otherwise the variable is
720@dfn{defined}.
721
722On its own, a variable object is anonymous. A variable is said to be
723@dfn{bound} when it is associated with a name in some way, usually a
724symbol in a module obarray. When this happens, the name is said to be
725bound to the variable, in that module.
726
727(That's the theory, anyway. In practice, defined-ness and bound-ness
728sometimes get confused, because Lisp and Scheme implementations have
729often conflated --- or deliberately drawn no distinction between --- a
730name that is unbound and a name that is bound to a variable whose value
731is undefined. We will try to be clear about the difference and explain
732any confusion where it is unavoidable.)
733
734Variables do not have a read syntax. Most commonly they are created and
735bound implicitly by @code{define} expressions: a top-level @code{define}
736expression of the form
737
738@lisp
739(define @var{name} @var{value})
740@end lisp
741
742@noindent
743creates a variable with initial value @var{value} and binds it to the
744name @var{name} in the current module. But they can also be created
745dynamically by calling one of the constructor procedures
746@code{make-variable} and @code{make-undefined-variable}.
747
748@deffn {Scheme Procedure} make-undefined-variable
749@deffnx {C Function} scm_make_undefined_variable ()
750Return a variable that is initially unbound.
751@end deffn
752
753@deffn {Scheme Procedure} make-variable init
754@deffnx {C Function} scm_make_variable (init)
755Return a variable initialized to value @var{init}.
756@end deffn
757
758@deffn {Scheme Procedure} variable-bound? var
759@deffnx {C Function} scm_variable_bound_p (var)
a4b4fbbd
JE
760Return @code{#t} if @var{var} is bound to a value, or @code{#f}
761otherwise. Throws an error if @var{var} is not a variable object.
992a3879
AW
762@end deffn
763
764@deffn {Scheme Procedure} variable-ref var
765@deffnx {C Function} scm_variable_ref (var)
766Dereference @var{var} and return its value.
767@var{var} must be a variable object; see @code{make-variable}
768and @code{make-undefined-variable}.
769@end deffn
770
771@deffn {Scheme Procedure} variable-set! var val
772@deffnx {C Function} scm_variable_set_x (var, val)
773Set the value of the variable @var{var} to @var{val}.
774@var{var} must be a variable object, @var{val} can be any
775value. Return an unspecified value.
776@end deffn
777
778@deffn {Scheme Procedure} variable-unset! var
779@deffnx {C Function} scm_variable_unset_x (var)
780Unset the value of the variable @var{var}, leaving @var{var} unbound.
781@end deffn
782
783@deffn {Scheme Procedure} variable? obj
784@deffnx {C Function} scm_variable_p (obj)
a4b4fbbd
JE
785Return @code{#t} if @var{obj} is a variable object, else return
786@code{#f}.
992a3879
AW
787@end deffn
788
789
790@node Module System Reflection
791@subsection Module System Reflection
792
793The previous sections have described a declarative view of the module
794system. You can also work with it programmatically by accessing and
795modifying various parts of the Scheme objects that Guile uses to
796implement the module system.
797
798At any time, there is a @dfn{current module}. This module is the one
799where a top-level @code{define} and similar syntax will add new
800bindings. You can find other module objects with @code{resolve-module},
801for example.
802
803These module objects can be used as the second argument to @code{eval}.
804
805@deffn {Scheme Procedure} current-module
806@deffnx {C Function} scm_current_module ()
807Return the current module object.
808@end deffn
809
810@deffn {Scheme Procedure} set-current-module module
811@deffnx {C Function} scm_set_current_module (module)
812Set the current module to @var{module} and return
813the previous current module.
814@end deffn
815
816@deffn {Scheme Procedure} save-module-excursion thunk
817Call @var{thunk} within a @code{dynamic-wind} such that the module that
818is current at invocation time is restored when @var{thunk}'s dynamic
819extent is left (@pxref{Dynamic Wind}).
820
821More precisely, if @var{thunk} escapes non-locally, the current module
822(at the time of escape) is saved, and the original current module (at
823the time @var{thunk}'s dynamic extent was last entered) is restored. If
824@var{thunk}'s dynamic extent is re-entered, then the current module is
825saved, and the previously saved inner module is set current again.
826@end deffn
827
994d87be
BT
828@deffn {Scheme Procedure} resolve-module name [autoload=#t] [version=#f] @
829 [#:ensure=#t]
992a3879
AW
830@deffnx {C Function} scm_resolve_module (name)
831Find the module named @var{name} and return it. When it has not already
832been defined and @var{autoload} is true, try to auto-load it. When it
833can't be found that way either, create an empty module if @var{ensure}
834is true, otherwise return @code{#f}. If @var{version} is true, ensure
835that the resulting module is compatible with the given version reference
836(@pxref{R6RS Version References}). The name is a list of symbols.
837@end deffn
838
994d87be
BT
839@deffn {Scheme Procedure} resolve-interface name [#:select=#f] @
840 [#:hide='()] [#:prefix=#f] @
841 [#:renamer=#f] [#:version=#f]
992a3879
AW
842Find the module named @var{name} as with @code{resolve-module} and
843return its interface. The interface of a module is also a module
844object, but it contains only the exported bindings.
845@end deffn
846
847@deffn {Scheme Procedure} module-uses module
848Return a list of the interfaces used by @var{module}.
849@end deffn
850
851@deffn {Scheme Procedure} module-use! module interface
852Add @var{interface} to the front of the use-list of @var{module}. Both
853arguments should be module objects, and @var{interface} should very
854likely be a module returned by @code{resolve-interface}.
855@end deffn
856
857@deffn {Scheme Procedure} reload-module module
858Revisit the source file that corresponds to @var{module}. Raises an
859error if no source file is associated with the given module.
860@end deffn
861
862As mentioned in the previous section, modules contain a mapping between
863identifiers (as symbols) and storage locations (as variables). Guile
864defines a number of procedures to allow access to this mapping. If you
865are programming in C, @ref{Accessing Modules from C}.
866
867@deffn {Scheme Procedure} module-variable module name
868Return the variable bound to @var{name} (a symbol) in @var{module}, or
869@code{#f} if @var{name} is unbound.
870@end deffn
871
872@deffn {Scheme Procedure} module-add! module name var
873Define a new binding between @var{name} (a symbol) and @var{var} (a
874variable) in @var{module}.
875@end deffn
876
877@deffn {Scheme Procedure} module-ref module name
878Look up the value bound to @var{name} in @var{module}. Like
879@code{module-variable}, but also does a @code{variable-ref} on the
880resulting variable, raising an error if @var{name} is unbound.
881@end deffn
882
883@deffn {Scheme Procedure} module-define! module name value
884Locally bind @var{name} to @var{value} in @var{module}. If @var{name}
885was already locally bound in @var{module}, i.e., defined locally and not
886by an imported module, the value stored in the existing variable will be
887updated. Otherwise, a new variable will be added to the module, via
888@code{module-add!}.
889@end deffn
890
891@deffn {Scheme Procedure} module-set! module name value
892Update the binding of @var{name} in @var{module} to @var{value}, raising
893an error if @var{name} is not already bound in @var{module}.
894@end deffn
895
896There are many other reflective procedures available in the default
897environment. If you find yourself using one of them, please contact the
898Guile developers so that we can commit to stability for that interface.
899
900
07d83abe 901@node Accessing Modules from C
726b8ba3 902@subsection Accessing Modules from C
07d83abe
MV
903
904The last sections have described how modules are used in Scheme code,
905which is the recommended way of creating and accessing modules. You
906can also work with modules from C, but it is more cumbersome.
907
908The following procedures are available.
909
7af1ba2f 910@deftypefn {C Function} SCM scm_c_call_with_current_module (SCM @var{module}, SCM (*@var{func})(void *), void *@var{data})
07d83abe
MV
911Call @var{func} and make @var{module} the current module during the
912call. The argument @var{data} is passed to @var{func}. The return
913value of @code{scm_c_call_with_current_module} is the return value of
914@var{func}.
915@end deftypefn
916
7af1ba2f
LC
917@deftypefn {C Function} SCM scm_public_variable (SCM @var{module_name}, SCM @var{name})
918@deftypefnx {C Function} SCM scm_c_public_variable ({const char *}@var{module_name}, {const char *}@var{name})
831e6782
AW
919Find a the variable bound to the symbol @var{name} in the public
920interface of the module named @var{module_name}.
921
7af1ba2f 922@var{module_name} should be a list of symbols, when represented as a
831e6782
AW
923Scheme object, or a space-separated string, in the @code{const char *}
924case. See @code{scm_c_define_module} below, for more examples.
925
926Signals an error if no module was found with the given name. If
927@var{name} is not bound in the module, just returns @code{#f}.
928@end deftypefn
929
7af1ba2f
LC
930@deftypefn {C Function} SCM scm_private_variable (SCM @var{module_name}, SCM @var{name})
931@deftypefnx {C Function} SCM scm_c_private_variable ({const char *}@var{module_name}, {const char *}@var{name})
831e6782
AW
932Like @code{scm_public_variable}, but looks in the internals of the
933module named @var{module_name} instead of the public interface.
934Logically, these procedures should only be called on modules you write.
935@end deftypefn
936
7af1ba2f
LC
937@deftypefn {C Function} SCM scm_public_lookup (SCM @var{module_name}, SCM @var{name})
938@deftypefnx {C Function} SCM scm_c_public_lookup ({const char *}@var{module_name}, {const char *}@var{name})
939@deftypefnx {C Function} SCM scm_private_lookup (SCM @var{module_name}, SCM @var{name})
940@deftypefnx {C Function} SCM scm_c_private_lookup ({const char *}@var{module_name}, {const char *}@var{name})
831e6782
AW
941Like @code{scm_public_variable} or @code{scm_private_variable}, but if
942the @var{name} is not bound in the module, signals an error. Returns a
943variable, always.
944
945@example
f57ea23a 946static SCM eval_string_var;
831e6782 947
f57ea23a
MW
948/* NOTE: It is important that the call to 'my_init'
949 happens-before all calls to 'my_eval_string'. */
950void my_init (void)
951@{
952 eval_string_var = scm_c_public_lookup ("ice-9 eval-string",
953 "eval-string");
954@}
831e6782 955
f57ea23a
MW
956SCM my_eval_string (SCM str)
957@{
831e6782
AW
958 return scm_call_1 (scm_variable_ref (eval_string_var), str);
959@}
960@end example
961@end deftypefn
962
7af1ba2f
LC
963@deftypefn {C Function} SCM scm_public_ref (SCM @var{module_name}, SCM @var{name})
964@deftypefnx {C Function} SCM scm_c_public_ref ({const char *}@var{module_name}, {const char *}@var{name})
965@deftypefnx {C Function} SCM scm_private_ref (SCM @var{module_name}, SCM @var{name})
966@deftypefnx {C Function} SCM scm_c_private_ref ({const char *}@var{module_name}, {const char *}@var{name})
831e6782
AW
967Like @code{scm_public_lookup} or @code{scm_private_lookup}, but
968additionally dereferences the variable. If the variable object is
969unbound, signals an error. Returns the value bound to @var{name} in
64de6db5 970@var{module_name}.
831e6782
AW
971@end deftypefn
972
973In addition, there are a number of other lookup-related procedures. We
974suggest that you use the @code{scm_public_} and @code{scm_private_}
975family of procedures instead, if possible.
976
7af1ba2f 977@deftypefn {C Function} SCM scm_c_lookup ({const char *}@var{name})
07d83abe
MV
978Return the variable bound to the symbol indicated by @var{name} in the
979current module. If there is no such binding or the symbol is not
980bound to a variable, signal an error.
981@end deftypefn
982
7af1ba2f 983@deftypefn {C Function} SCM scm_lookup (SCM @var{name})
07d83abe
MV
984Like @code{scm_c_lookup}, but the symbol is specified directly.
985@end deftypefn
986
7af1ba2f
LC
987@deftypefn {C Function} SCM scm_c_module_lookup (SCM @var{module}, {const char *}@var{name})
988@deftypefnx {C Function} SCM scm_module_lookup (SCM @var{module}, SCM @var{name})
07d83abe
MV
989Like @code{scm_c_lookup} and @code{scm_lookup}, but the specified
990module is used instead of the current one.
991@end deftypefn
992
7af1ba2f 993@deftypefn {C Function} SCM scm_module_variable (SCM @var{module}, SCM @var{name})
831e6782
AW
994Like @code{scm_module_lookup}, but if the binding does not exist, just
995returns @code{#f} instead of raising an error.
996@end deftypefn
997
998To define a value, use @code{scm_define}:
999
7af1ba2f 1000@deftypefn {C Function} SCM scm_c_define ({const char *}@var{name}, SCM @var{val})
07d83abe
MV
1001Bind the symbol indicated by @var{name} to a variable in the current
1002module and set that variable to @var{val}. When @var{name} is already
1003bound to a variable, use that. Else create a new variable.
1004@end deftypefn
1005
7af1ba2f 1006@deftypefn {C Function} SCM scm_define (SCM @var{name}, SCM @var{val})
07d83abe
MV
1007Like @code{scm_c_define}, but the symbol is specified directly.
1008@end deftypefn
1009
7af1ba2f
LC
1010@deftypefn {C Function} SCM scm_c_module_define (SCM @var{module}, {const char *}@var{name}, SCM @var{val})
1011@deftypefnx {C Function} SCM scm_module_define (SCM @var{module}, SCM @var{name}, SCM @var{val})
07d83abe
MV
1012Like @code{scm_c_define} and @code{scm_define}, but the specified
1013module is used instead of the current one.
1014@end deftypefn
1015
62e15979
AW
1016In some rare cases, you may need to access the variable that
1017@code{scm_module_define} would have accessed, without changing the
1018binding of the existing variable, if one is present. In that case, use
1019@code{scm_module_ensure_local_variable}:
1020
1021@deftypefn {C Function} SCM scm_module_ensure_local_variable (SCM @var{module}, SCM @var{sym})
1022Like @code{scm_module_define}, but if the @var{sym} is already locally
1023bound in that module, the variable's existing binding is not reset.
1024Returns a variable.
1025@end deftypefn
1026
7af1ba2f 1027@deftypefn {C Function} SCM scm_module_reverse_lookup (SCM @var{module}, SCM @var{variable})
64de6db5 1028Find the symbol that is bound to @var{variable} in @var{module}. When no such binding is found, return @code{#f}.
07d83abe
MV
1029@end deftypefn
1030
7af1ba2f 1031@deftypefn {C Function} SCM scm_c_define_module ({const char *}@var{name}, void (*@var{init})(void *), void *@var{data})
07d83abe
MV
1032Define a new module named @var{name} and make it current while
1033@var{init} is called, passing it @var{data}. Return the module.
1034
1035The parameter @var{name} is a string with the symbols that make up
1036the module name, separated by spaces. For example, @samp{"foo bar"} names
1037the module @samp{(foo bar)}.
1038
1039When there already exists a module named @var{name}, it is used
1040unchanged, otherwise, an empty module is created.
1041@end deftypefn
1042
7af1ba2f 1043@deftypefn {C Function} SCM scm_c_resolve_module ({const char *}@var{name})
07d83abe
MV
1044Find the module name @var{name} and return it. When it has not
1045already been defined, try to auto-load it. When it can't be found
1046that way either, create an empty module. The name is interpreted as
1047for @code{scm_c_define_module}.
1048@end deftypefn
1049
7af1ba2f 1050@deftypefn {C Function} SCM scm_c_use_module ({const char *}@var{name})
07d83abe
MV
1051Add the module named @var{name} to the uses list of the current
1052module, as with @code{(use-modules @var{name})}. The name is
1053interpreted as for @code{scm_c_define_module}.
1054@end deftypefn
1055
7af1ba2f 1056@deftypefn {C Function} SCM scm_c_export ({const char *}@var{name}, ...)
07d83abe
MV
1057Add the bindings designated by @var{name}, ... to the public interface
1058of the current module. The list of names is terminated by
1059@code{NULL}.
1060@end deftypefn
1061
ef5f9163 1062
726b8ba3
AW
1063@node provide and require
1064@subsection provide and require
1065
1066Aubrey Jaffer, mostly to support his portable Scheme library SLIB,
1067implemented a provide/require mechanism for many Scheme implementations.
1068Library files in SLIB @emph{provide} a feature, and when user programs
1069@emph{require} that feature, the library file is loaded in.
1070
1071For example, the file @file{random.scm} in the SLIB package contains the
1072line
1073
1074@lisp
1075(provide 'random)
1076@end lisp
1077
1078so to use its procedures, a user would type
1079
1080@lisp
1081(require 'random)
1082@end lisp
1083
1084and they would magically become available, @emph{but still have the same
1085names!} So this method is nice, but not as good as a full-featured
1086module system.
1087
1088When SLIB is used with Guile, provide and require can be used to access
1089its facilities.
1090
1091@node Environments
1092@subsection Environments
1093@cindex environment
1094
1095Scheme, as defined in R5RS, does @emph{not} have a full module system.
1096However it does define the concept of a top-level @dfn{environment}.
1097Such an environment maps identifiers (symbols) to Scheme objects such
1098as procedures and lists: @ref{About Closure}. In other words, it
1099implements a set of @dfn{bindings}.
1100
1101Environments in R5RS can be passed as the second argument to
1102@code{eval} (@pxref{Fly Evaluation}). Three procedures are defined to
1103return environments: @code{scheme-report-environment},
1104@code{null-environment} and @code{interaction-environment} (@pxref{Fly
1105Evaluation}).
1106
1107In addition, in Guile any module can be used as an R5RS environment,
1108i.e., passed as the second argument to @code{eval}.
1109
1110Note: the following two procedures are available only when the
1111@code{(ice-9 r5rs)} module is loaded:
1112
1113@lisp
1114(use-modules (ice-9 r5rs))
1115@end lisp
1116
1117@deffn {Scheme Procedure} scheme-report-environment version
1118@deffnx {Scheme Procedure} null-environment version
1119@var{version} must be the exact integer `5', corresponding to revision
11205 of the Scheme report (the Revised^5 Report on Scheme).
1121@code{scheme-report-environment} returns a specifier for an
1122environment that is empty except for all bindings defined in the
1123report that are either required or both optional and supported by the
1124implementation. @code{null-environment} returns a specifier for an
1125environment that is empty except for the (syntactic) bindings for all
1126syntactic keywords defined in the report that are either required or
1127both optional and supported by the implementation.
1128
1129Currently Guile does not support values of @var{version} for other
1130revisions of the report.
1131
1132The effect of assigning (through the use of @code{eval}) a variable
1133bound in a @code{scheme-report-environment} (for example @code{car})
1134is unspecified. Currently the environments specified by
1135@code{scheme-report-environment} are not immutable in Guile.
1136@end deffn
1137
1138
1139
07d83abe
MV
1140@c Local Variables:
1141@c TeX-master: "guile.texi"
1142@c End: