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