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