(guile_TEXINFOS): Add tools.texi.
[bpt/guile.git] / doc / ref / scheme-modules.texi
CommitLineData
a0e07ba4
NJ
1@page
2@node Modules
3@chapter Modules
4@cindex modules
5
6When programs become large, naming conflicts can occur when a function
7or global variable defined in one file has the same name as a function
8or global variable in another file. Even just a @emph{similarity}
9between function names can cause hard-to-find bugs, since a programmer
10might type the wrong function name.
11
12The approach used to tackle this problem is called @emph{information
13encapsulation}, which consists of packaging functional units into a
14given name space that is clearly separated from other name spaces.
15@cindex encapsulation
16@cindex information encapsulation
17@cindex name space
18
19The language features that allow this are usually called @emph{the
20module system} because programs are broken up into modules that are
21compiled separately (or loaded separately in an interpreter).
22
23Older languages, like C, have limited support for name space
24manipulation and protection. In C a variable or function is public by
25default, and can be made local to a module with the @code{static}
26keyword. But you cannot reference public variables and functions from
27another module with different names.
28
29More advanced module systems have become a common feature in recently
30designed languages: ML, Python, Perl, and Modula 3 all allow the
31@emph{renaming} of objects from a foreign module, so they will not
32clutter the global name space.
33@cindex name space - private
34
2a946b44
NJ
35In addition, Guile offers variables as first-class objects. They can
36be used for interacting with the module system.
37
a0e07ba4
NJ
38@menu
39* Scheme and modules:: How modules are handled in standard Scheme.
40* The Guile module system:: How Guile does it.
41* Dynamic Libraries:: Loading libraries of compiled code at run time.
2a946b44 42* Variables:: First-class variables.
a0e07ba4
NJ
43@end menu
44
45
46@node Scheme and modules
47@section Scheme and modules
48
49Scheme, as defined in R5RS, does @emph{not} have a module system at all.
50
51Aubrey Jaffer, mostly to support his portable Scheme library SLIB,
52implemented a provide/require mechanism for many Scheme implementations.
53Library files in SLIB @emph{provide} a feature, and when user programs
54@emph{require} that feature, the library file is loaded in.
55
56For example, the file @file{random.scm} in the SLIB package contains the
57line
58
59@smalllisp
60(provide 'random)
61@end smalllisp
62
63so to use its procedures, a user would type
64
65@smalllisp
66(require 'random)
67@end smalllisp
68
69and they would magically become available, @emph{but still have the same
70names!} So this method is nice, but not as good as a full-featured
71module system.
72
73
74@node The Guile module system
75@section The Guile module system
76
77In 1996 Tom Lord implemented a full-featured module system for Guile which
78allows loading Scheme source files into a private name space. This system has
79been in available since Guile version 1.4.
80@c fixme: Actually, was it available before? 1.4 seems a bit late...
81
82For Guile version 1.5.0 and later, the system has been improved to have better
83integration from C code, more fine-grained user control over interfaces, and
84documentation.
85
86Although it is anticipated that the module system implementation will
87change in the future, the Scheme programming interface described in this
88manual should be considered stable. The C programming interface is
89considered relatively stable, although at the time of this writing,
90there is still some flux.
91@c fixme: Review: Need better C code interface commentary.
92
93@menu
94* General Information about Modules:: Guile module basics.
95* Using Guile Modules:: How to use existing modules.
96* Creating Guile Modules:: How to package your code into modules.
97* More Module Procedures:: Low-level module code.
98* Module System Quirks:: Strange things to be aware of.
99* Included Guile Modules:: Which modules come with Guile?
100@end menu
101
102@node General Information about Modules
103@subsection General Information about Modules
104
105A Guile module is a collection of named procedures, variables and
106macros, altogether called the @dfn{bindings}, since they bind, or
107associate, a symbol (the name) to a Scheme object (procedure, variable,
108or macro). Within a module, all bindings are visible. Certain bindings
109can be declared @dfn{public}, in which case they are added to the
110module's so-called @dfn{export list}; this set of public bindings is
111called the module's @dfn{public interface} (@pxref{Creating Guile
112Modules}).
113
114A client module @dfn{uses} a providing module's bindings by either
115accessing the providing module's public interface, or by building a
116custom interface (and then accessing that). In a custom interface, the
117client module can @dfn{select} which bindings to access and can also
118algorithmically @dfn{rename} bindings. In contrast, when using the
119providing module's public interface, the entire export list is available
120without renaming (@pxref{Using Guile Modules}).
121
122To use a module, it must be found and loaded. All Guile modules have a
123unique @dfn{module name}, which is a list of one or more symbols.
124Examples are @code{(ice-9 popen)} or @code{(srfi srfi-11)}. When Guile
125searches for the code of a module, it constructs the name of the file to
126load by concatenating the name elements with slashes between the
127elements and appending a number of file name extensions from the list
128@code{%load-extensions} (REFFIXME). The resulting file name is then
129searched in all directories in the variable @code{%load-path}. For
130example, the @code{(ice-9 popen)} module would result in the filename
131@code{ice-9/popen.scm} and searched in the installation directory of
132Guile and in all other directories in the load path.
133
134@c FIXME::martin: Not sure about this, maybe someone knows better?
135Every module has a so-called syntax transformer associated with it.
136This is a procedure which performs all syntax transformation for the
137time the module is read in and evaluated. When working with modules,
138you can manipulate the current syntax transformer using the
139@code{use-syntax} syntactic form or the @code{#:use-syntax} module
140definition option (@pxref{Creating Guile Modules}).
141
142Please note that there are some problems with the current module system
143you should keep in mind (@pxref{Module System Quirks}). We hope to
144address these eventually.
145
146
147@node Using Guile Modules
148@subsection Using Guile Modules
149
150To use a Guile module is to access either its public interface or a
151custom interface (@pxref{General Information about Modules}). Both
152types of access are handled by the syntactic form @code{use-modules},
153which accepts one or more interface specifications and, upon evaluation,
154arranges for those interfaces to be available to the current module.
155This process may include locating and loading code for a given module if
156that code has not yet been loaded (REFFIXME %load-path).
157
158An @dfn{interface specification} has one of two forms. The first
159variation is simply to name the module, in which case its public
160interface is the one accessed. For example:
161
162@smalllisp
163(use-modules (ice-9 popen))
164@end smalllisp
165
166Here, the interface specification is @code{(ice-9 popen)}, and the
167result is that the current module now has access to @code{open-pipe},
168@code{close-pipe}, @code{open-input-pipe}, and so on (@pxref{Included
169Guile Modules}).
170
171Note in the previous example that if the current module had already
172defined @code{open-pipe}, that definition would be overwritten by the
173definition in @code{(ice-9 popen)}. For this reason (and others), there
174is a second variation of interface specification that not only names a
175module to be accessed, but also selects bindings from it and renames
176them to suit the current module's needs. For example:
177
178@smalllisp
179(use-modules ((ice-9 popen)
180 :select ((open-pipe . pipe-open) close-pipe)
181 :rename (symbol-prefix-proc 'unixy:)))
182@end smalllisp
183
184Here, the interface specification is more complex than before, and the
185result is that a custom interface with only two bindings is created and
186subsequently accessed by the current module. The mapping of old to new
187names is as follows:
188
189@c Use `smallexample' since `table' is ugly. --ttn
190@smallexample
191(ice-9 popen) sees: current module sees:
192open-pipe unixy:pipe-open
193close-pipe unixy:close-pipe
194@end smallexample
195
196This example also shows how to use the convenience procedure
197@code{symbol-prefix-proc}.
198
199@c begin (scm-doc-string "boot-9.scm" "symbol-prefix-proc")
8f85c0c6 200@deffn {Scheme Procedure} symbol-prefix-proc prefix-sym
a0e07ba4
NJ
201Return a procedure that prefixes its arg (a symbol) with
202@var{prefix-sym}.
203@c Insert gratuitous C++ slam here. --ttn
204@end deffn
205
206@c begin (scm-doc-string "boot-9.scm" "use-modules")
207@deffn syntax use-modules spec @dots{}
208Resolve each interface specification @var{spec} into an interface and
209arrange for these to be accessible by the current module. The return
210value is unspecified.
211
212@var{spec} can be a list of symbols, in which case it names a module
213whose public interface is found and used.
214
215@var{spec} can also be of the form:
216
217@smalllisp
218 (MODULE-NAME [:select SELECTION] [:rename RENAMER])
219@end smalllisp
220
221in which case a custom interface is newly created and used.
222@var{module-name} is a list of symbols, as above; @var{selection} is a
223list of selection-specs; and @var{renamer} is a procedure that takes a
224symbol and returns its new name. A selection-spec is either a symbol or
225a pair of symbols @code{(ORIG . SEEN)}, where @var{orig} is the name in
226the used module and @var{seen} is the name in the using module. Note
227that @var{seen} is also passed through @var{renamer}.
228
229The @code{:select} and @code{:rename} clauses are optional. If both are
230omitted, the returned interface has no bindings. If the @code{:select}
231clause is omitted, @var{renamer} operates on the used module's public
232interface.
233
234Signal error if module name is not resolvable.
235@end deffn
236
237
238@c FIXME::martin: Is this correct, and is there more to say?
239@c FIXME::martin: Define term and concept `system transformer' somewhere.
240
241@deffn syntax use-syntax module-name
242Load the module @code{module-name} and use its system
243transformer as the system transformer for the currently defined module,
244as well as installing it as the current system transformer.
245@end deffn
246
247
248@node Creating Guile Modules
249@subsection Creating Guile Modules
250
251When you want to create your own modules, you have to take the following
252steps:
253
254@itemize @bullet
255@item
256Create a Scheme source file and add all variables and procedures you wish
257to export, or which are required by the exported procedures.
258
259@item
260Add a @code{define-module} form at the beginning.
261
262@item
263Export all bindings which should be in the public interface, either
264by using @code{define-public} or @code{export} (both documented below).
265@end itemize
266
267@c begin (scm-doc-string "boot-9.scm" "define-module")
268@deffn syntax define-module module-name [options @dots{}]
269@var{module-name} is of the form @code{(hierarchy file)}. One
270example of this is
271
272@smalllisp
273(define-module (ice-9 popen))
274@end smalllisp
275
276@code{define-module} makes this module available to Guile programs under
277the given @var{module-name}.
278
279The @var{options} are keyword/value pairs which specify more about the
280defined module. The recognized options and their meaning is shown in
281the following table.
282
283@c fixme: Should we use "#:" or ":"?
284
285@table @code
286@item #:use-module @var{interface-specification}
287Equivalent to a @code{(use-modules @var{interface-specification})}
288(@pxref{Using Guile Modules}).
289
290@item #:use-syntax @var{module}
291Use @var{module} when loading the currently defined module, and install
292it as the syntax transformer.
293
294@item #:autoload @var{module} @var{symbol}
295Load @var{module} whenever @var{symbol} is accessed.
296
297@item #:export @var{list}
298Export all identifiers in @var{list}, which must be a list of symbols.
299This is equivalent to @code{(export @var{list})} in the module body.
300
301@item #:no-backtrace
302Tell Guile not to record information for procedure backtraces when
303executing the procedures in this module.
304
305@item #:pure
306Create a @dfn{pure} module, that is a module which does not contain any
307of the standard procedure bindings except for the syntax forms. This is
308useful if you want to create @dfn{safe} modules, that is modules which
309do not know anything about dangerous procedures.
310@end table
311
312@end deffn
313@c end
314
315@deffn syntax export variable @dots{}
316Add all @var{variable}s (which must be symbols) to the list of exported
317bindings of the current module.
318@end deffn
319
320@c begin (scm-doc-string "boot-9.scm" "define-public")
321@deffn syntax define-public @dots{}
322Equivalent to @code{(begin (define foo ...) (export foo))}.
323@end deffn
324@c end
325
326
327@node More Module Procedures
328@subsection More Module Procedures
329
330@c FIXME::martin: Review me!
331
332@c FIXME::martin: Should this procedure be documented and supported
333@c at all?
334
335The procedures in this section are useful if you want to dig into the
336innards of Guile's module system. If you don't know precisely what you
337do, you should probably avoid using any of them.
338
8f85c0c6
NJ
339@deffn {Scheme Procedure} standard-eval-closure module
340@deffnx {C Function} scm_standard_eval_closure (module)
a0e07ba4
NJ
341Return an eval closure for the module @var{module}.
342@end deffn
343
344
345@node Module System Quirks
346@subsection Module System Quirks
347
348Although the programming interfaces are relatively stable, the Guile
349module system itself is still evolving. Here are some situations where
350usage surpasses design.
351
352@itemize @bullet
353
354@item
355When using a module which exports a macro definition, the other module
356must export all bindings the macro expansion uses, too, because the
357expanded code would otherwise not be able to see these definitions and
358issue a ``variable unbound'' error, or worse, would use another binding
359which might be present in the scope of the expansion.
360
361@item
362When two or more used modules export bindings with the same names, the
363last accessed module wins, and the exported binding of that last module
364will silently be used. This might lead to hard-to-find errors because
365wrong procedures or variables are used. To avoid this kind of
366@dfn{name-clash} situation, use a custom interface specification
367(@pxref{Using Guile Modules}). (We include this entry for the possible
368benefit of users of Guile versions previous to 1.5.0, when custom
369interfaces were added to the module system.)
370
371@item
372[Add other quirks here.]
373
374@end itemize
375
376
377@node Included Guile Modules
378@subsection Included Guile Modules
379
380@c FIXME::martin: Review me!
381
382Some modules are included in the Guile distribution; here are references
383to the entries in this manual which describe them in more detail:
384
385@table @strong
386@item boot-9
387boot-9 is Guile's initialization module, and it is always loaded when
388Guile starts up.
389
390@item (ice-9 debug)
391Mikael Djurfeldt's source-level debugging support for Guile
392(@pxref{Debugger User Interface}).
393
394@item (ice-9 threads)
395Guile's support for multi threaded execution (@pxref{Scheduling}).
396
397@item (ice-9 rdelim)
398Line- and character-delimited input (@pxref{Line/Delimited}).
399
400@item (ice-9 rw)
401Block string input/output (@pxref{Block Reading and Writing}).
402
403@item (ice-9 documentation)
404Online documentation (REFFIXME).
405
406@item (srfi srfi-1)
407A library providing a lot of useful list and pair processing
408procedures (@pxref{SRFI-1}).
409
410@item (srfi srfi-2)
411Support for @code{and-let*} (@pxref{SRFI-2}).
412
413@item (srfi srfi-4)
414Support for homogeneous numeric vectors (@pxref{SRFI-4}).
415
416@item (srfi srfi-6)
417Support for some additional string port procedures (@pxref{SRFI-6}).
418
419@item (srfi srfi-8)
420Multiple-value handling with @code{receive} (@pxref{SRFI-8}).
421
422@item (srfi srfi-9)
423Record definition with @code{define-record-type} (@pxref{SRFI-9}).
424
425@item (srfi srfi-10)
426Read hash extension @code{#,()} (@pxref{SRFI-10}).
427
428@item (srfi srfi-11)
429Multiple-value handling with @code{let-values} and @code{let-values*}
430(@pxref{SRFI-11}).
431
432@item (srfi srfi-13)
433String library (@pxref{SRFI-13}).
434
435@item (srfi srfi-14)
436Character-set library (@pxref{SRFI-14}).
437
438@item (srfi srfi-17)
439Getter-with-setter support (@pxref{SRFI-17}).
440
441@item (ice-9 slib)
442This module contains hooks for using Aubrey Jaffer's portable Scheme
443library SLIB from Guile (@pxref{SLIB}).
444
445@c FIXME::martin: This module is not in the distribution. Remove it
446@c from here?
447@item (ice-9 jacal)
448This module contains hooks for using Aubrey Jaffer's symbolic math
85a9b4ed 449package Jacal from Guile (@pxref{JACAL}).
a0e07ba4
NJ
450@end table
451
452
453@node Dynamic Libraries
454@section Dynamic Libraries
455
456Most modern Unices have something called @dfn{shared libraries}. This
457ordinarily means that they have the capability to share the executable
458image of a library between several running programs to save memory and
459disk space. But generally, shared libraries give a lot of additional
460flexibility compared to the traditional static libraries. In fact,
461calling them `dynamic' libraries is as correct as calling them `shared'.
462
463Shared libraries really give you a lot of flexibility in addition to the
464memory and disk space savings. When you link a program against a shared
465library, that library is not closely incorporated into the final
466executable. Instead, the executable of your program only contains
467enough information to find the needed shared libraries when the program
468is actually run. Only then, when the program is starting, is the final
469step of the linking process performed. This means that you need not
470recompile all programs when you install a new, only slightly modified
471version of a shared library. The programs will pick up the changes
472automatically the next time they are run.
473
474Now, when all the necessary machinery is there to perform part of the
475linking at run-time, why not take the next step and allow the programmer
476to explicitly take advantage of it from within his program? Of course,
477many operating systems that support shared libraries do just that, and
478chances are that Guile will allow you to access this feature from within
479your Scheme programs. As you might have guessed already, this feature
480is called @dfn{dynamic linking}@footnote{Some people also refer to the
481final linking stage at program startup as `dynamic linking', so if you
482want to make yourself perfectly clear, it is probably best to use the
483more technical term @dfn{dlopening}, as suggested by Gordon Matzigkeit
484in his libtool documentation.}
485
486As with many aspects of Guile, there is a low-level way to access the
487dynamic linking apparatus, and a more high-level interface that
488integrates dynamically linked libraries into the module system.
489
490@menu
491* Low level dynamic linking::
492* Compiled Code Modules::
493* Dynamic Linking and Compiled Code Modules::
494@end menu
495
496@node Low level dynamic linking
497@subsection Low level dynamic linking
498
499When using the low level procedures to do your dynamic linking, you have
85a9b4ed 500complete control over which library is loaded when and what gets done
a0e07ba4
NJ
501with it.
502
8f85c0c6
NJ
503@deffn {Scheme Procedure} dynamic-link library
504@deffnx {C Function} scm_dynamic_link (library)
a0e07ba4
NJ
505Find the shared library denoted by @var{library} (a string) and link it
506into the running Guile application. When everything works out, return a
507Scheme object suitable for representing the linked object file.
508Otherwise an error is thrown. How object files are searched is system
509dependent.
510
511Normally, @var{library} is just the name of some shared library file
512that will be searched for in the places where shared libraries usually
513reside, such as in @file{/usr/lib} and @file{/usr/local/lib}.
514@end deffn
515
8f85c0c6
NJ
516@deffn {Scheme Procedure} dynamic-object? obj
517@deffnx {C Function} scm_dynamic_object_p (obj)
518Return @code{#t} if @var{obj} is a dynamic library handle, or @code{#f}
519otherwise.
a0e07ba4
NJ
520@end deffn
521
8f85c0c6
NJ
522@deffn {Scheme Procedure} dynamic-unlink dobj
523@deffnx {C Function} scm_dynamic_unlink (dobj)
524Unlink the indicated object file from the application. The
525argument @var{dobj} must have been obtained by a call to
526@code{dynamic-link}. After @code{dynamic-unlink} has been
527called on @var{dobj}, its content is no longer accessible.
a0e07ba4
NJ
528@end deffn
529
8f85c0c6
NJ
530@deffn {Scheme Procedure} dynamic-func name dobj
531@deffnx {C Function} scm_dynamic_func (name, dobj)
532Search the dynamic object @var{dobj} for the C function
533indicated by the string @var{name} and return some Scheme
534handle that can later be used with @code{dynamic-call} to
535actually call the function.
a0e07ba4
NJ
536
537Regardless whether your C compiler prepends an underscore @samp{_} to
538the global names in a program, you should @strong{not} include this
539underscore in @var{function}. Guile knows whether the underscore is
540needed or not and will add it when necessary.
541@end deffn
542
8f85c0c6
NJ
543@deffn {Scheme Procedure} dynamic-call func dobj
544@deffnx {C Function} scm_dynamic_call (func, dobj)
545Call the C function indicated by @var{func} and @var{dobj}.
546The function is passed no arguments and its return value is
547ignored. When @var{function} is something returned by
548@code{dynamic-func}, call that function and ignore @var{dobj}.
549When @var{func} is a string , look it up in @var{dynobj}; this
550is equivalent to
a0e07ba4 551@smallexample
8f85c0c6 552(dynamic-call (dynamic-func @var{func} @var{dobj} #f))
a0e07ba4
NJ
553@end smallexample
554
555Interrupts are deferred while the C function is executing (with
556@code{SCM_DEFER_INTS}/@code{SCM_ALLOW_INTS}).
557@end deffn
558
8f85c0c6
NJ
559@deffn {Scheme Procedure} dynamic-args-call func dobj args
560@deffnx {C Function} scm_dynamic_args_call (func, dobj, args)
561Call the C function indicated by @var{func} and @var{dobj},
562just like @code{dynamic-call}, but pass it some arguments and
563return its return value. The C function is expected to take
564two arguments and return an @code{int}, just like @code{main}:
a0e07ba4
NJ
565@smallexample
566int c_func (int argc, char **argv);
567@end smallexample
568
8f85c0c6
NJ
569The parameter @var{args} must be a list of strings and is
570converted into an array of @code{char *}. The array is passed
571in @var{argv} and its size in @var{argc}. The return value is
572converted to a Scheme number and returned from the call to
573@code{dynamic-args-call}.
a0e07ba4
NJ
574@end deffn
575
576When dynamic linking is disabled or not supported on your system,
577the above functions throw errors, but they are still available.
578
579Here is a small example that works on GNU/Linux:
580
581@smallexample
582(define libc-obj (dynamic-link "libc.so"))
583libc-obj
584@result{} #<dynamic-object "libc.so">
585(dynamic-args-call 'rand libc-obj '())
586@result{} 269167349
587(dynamic-unlink libc-obj)
588libc-obj
589@result{} #<dynamic-object "libc.so" (unlinked)>
590@end smallexample
591
592As you can see, after calling @code{dynamic-unlink} on a dynamically
593linked library, it is marked as @samp{(unlinked)} and you are no longer
594able to use it with @code{dynamic-call}, etc. Whether the library is
595really removed from you program is system-dependent and will generally
596not happen when some other parts of your program still use it. In the
597example above, @code{libc} is almost certainly not removed from your
598program because it is badly needed by almost everything.
599
600The functions to call a function from a dynamically linked library,
601@code{dynamic-call} and @code{dynamic-args-call}, are not very powerful.
602They are mostly intended to be used for calling specially written
603initialization functions that will then add new primitives to Guile.
604For example, we do not expect that you will dynamically link
605@file{libX11} with @code{dynamic-link} and then construct a beautiful
606graphical user interface just by using @code{dynamic-call} and
607@code{dynamic-args-call}. Instead, the usual way would be to write a
608special Guile<->X11 glue library that has intimate knowledge about both
609Guile and X11 and does whatever is necessary to make them inter-operate
610smoothly. This glue library could then be dynamically linked into a
611vanilla Guile interpreter and activated by calling its initialization
612function. That function would add all the new types and primitives to
613the Guile interpreter that it has to offer.
614
615From this setup the next logical step is to integrate these glue
616libraries into the module system of Guile so that you can load new
617primitives into a running system just as you can load new Scheme code.
618
619There is, however, another possibility to get a more thorough access to
620the functions contained in a dynamically linked library. Anthony Green
621has written @file{libffi}, a library that implements a @dfn{foreign
622function interface} for a number of different platforms. With it, you
623can extend the Spartan functionality of @code{dynamic-call} and
624@code{dynamic-args-call} considerably. There is glue code available in
625the Guile contrib archive to make @file{libffi} accessible from Guile.
626
627@node Compiled Code Modules
628@subsection Putting Compiled Code into Modules
629
630@c FIXME::martin: Change all gh_ references to their scm_ equivalents.
631
632The new primitives that you add to Guile with @code{gh_new_procedure}
633or with any of the other mechanisms are normally placed into the same
634module as all the other builtin procedures (like @code{display}).
635However, it is also possible to put new primitives into their own
636module.
637
638The mechanism for doing so is not very well thought out and is likely to
639change when the module system of Guile itself is revised, but it is
640simple and useful enough to document it as it stands.
641
642What @code{gh_new_procedure} and the functions used by the snarfer
643really do is to add the new primitives to whatever module is the
644@emph{current module} when they are called. This is analogous to the
645way Scheme code is put into modules: the @code{define-module} expression
646at the top of a Scheme source file creates a new module and makes it the
647current module while the rest of the file is evaluated. The
648@code{define} expressions in that file then add their new definitions to
649this current module.
650
651Therefore, all we need to do is to make sure that the right module is
652current when calling @code{gh_new_procedure} for our new primitives.
653Unfortunately, there is not yet an easy way to access the module system
654from C, so we are better off with a more indirect approach. Instead of
655adding our primitives at initialization time we merely register with
656Guile that we are ready to provide the contents of a certain module,
657should it ever be needed.
658
659@deftypefun void scm_register_module_xxx (char *@var{name}, void (*@var{initfunc})(void))
660Register with Guile that @var{initfunc} will provide the contents of the
661module @var{name}.
662
663The function @var{initfunc} should perform the usual initialization
664actions for your new primitives, like calling @code{gh_new_procedure} or
665including the file produced by the snarfer. When @var{initfunc} is
666called, the current module is a newly created module with a name as
667indicated by @var{name}. Each definition that is added to it will be
668automatically exported.
669
85a9b4ed 670The string @var{name} indicates the hierarchical name of the new module.
a0e07ba4
NJ
671It should consist of the individual components of the module name
672separated by single spaces. That is, the Scheme module name @code{(foo
673bar)}, which is a list, should be written as @code{"foo bar"} for the
674@var{name} parameter.
675
676You can call @code{scm_register_module_xxx} at any time, even before
677Guile has been initialized. This might be useful when you want to put
678the call to it in some initialization code that is magically called
679before main, like constructors for global C++ objects.
680
681An example for @code{scm_register_module_xxx} appears in the next section.
682@end deftypefun
683
684Now, instead of calling the initialization function at program startup,
685you should simply call @code{scm_register_module_xxx} and pass it the
686initialization function. When the named module is later requested by
687Scheme code with @code{use-modules} for example, Guile will notice that
688it knows how to create this module and will call the initialization
689function at the right time in the right context.
690
691@node Dynamic Linking and Compiled Code Modules
692@subsection Dynamic Linking and Compiled Code Modules
693
694The most interesting application of dynamically linked libraries is
695probably to use them for providing @emph{compiled code modules} to
696Scheme programs. As much fun as programming in Scheme is, every now and
697then comes the need to write some low-level C stuff to make Scheme even
698more fun.
699
700Not only can you put these new primitives into their own module (see the
701previous section), you can even put them into a shared library that is
702only then linked to your running Guile image when it is actually
703needed.
704
705An example will hopefully make everything clear. Suppose we want to
706make the Bessel functions of the C library available to Scheme in the
707module @samp{(math bessel)}. First we need to write the appropriate
708glue code to convert the arguments and return values of the functions
709from Scheme to C and back. Additionally, we need a function that will
710add them to the set of Guile primitives. Because this is just an
6c997de2 711example, we will only implement this for the @code{j0} function.
a0e07ba4
NJ
712
713@c FIXME::martin: Change all gh_ references to their scm_ equivalents.
714
715@smallexample
716#include <math.h>
717#include <guile/gh.h>
718
719SCM
720j0_wrapper (SCM x)
721@{
722 return gh_double2scm (j0 (gh_scm2double (x)));
723@}
724
725void
726init_math_bessel ()
727@{
728 gh_new_procedure1_0 ("j0", j0_wrapper);
729@}
730@end smallexample
731
732We can already try to bring this into action by manually calling the low
733level functions for performing dynamic linking. The C source file needs
734to be compiled into a shared library. Here is how to do it on
735GNU/Linux, please refer to the @code{libtool} documentation for how to
736create dynamically linkable libraries portably.
737
738@smallexample
739gcc -shared -o libbessel.so -fPIC bessel.c
740@end smallexample
741
742Now fire up Guile:
743
744@smalllisp
745(define bessel-lib (dynamic-link "./libbessel.so"))
746(dynamic-call "init_math_bessel" bessel-lib)
747(j0 2)
748@result{} 0.223890779141236
749@end smalllisp
750
751The filename @file{./libbessel.so} should be pointing to the shared
752library produced with the @code{gcc} command above, of course. The
753second line of the Guile interaction will call the
754@code{init_math_bessel} function which in turn will register the C
755function @code{j0_wrapper} with the Guile interpreter under the name
756@code{j0}. This function becomes immediately available and we can call
757it from Scheme.
758
759Fun, isn't it? But we are only half way there. This is what
760@code{apropos} has to say about @code{j0}:
761
762@smallexample
763(apropos 'j0)
764@print{} the-root-module: j0 #<primitive-procedure j0>
765@end smallexample
766
767As you can see, @code{j0} is contained in the root module, where all
768the other Guile primitives like @code{display}, etc live. In general,
769a primitive is put into whatever module is the @dfn{current module} at
770the time @code{gh_new_procedure} is called. To put @code{j0} into its
771own module named @samp{(math bessel)}, we need to make a call to
772@code{scm_register_module_xxx}. Additionally, to have Guile perform
773the dynamic linking automatically, we need to put @file{libbessel.so}
774into a place where Guile can find it. The call to
775@code{scm_register_module_xxx} should be contained in a specially
776named @dfn{module init function}. Guile knows about this special name
777and will call that function automatically after having linked in the
778shared library. For our example, we add the following code to
779@file{bessel.c}:
780
781@smallexample
782void scm_init_math_bessel_module ()
783@{
784 scm_register_module_xxx ("math bessel", init_math_bessel);
785@}
786@end smallexample
787
788The general pattern for the name of a module init function is:
789@samp{scm_init_}, followed by the name of the module where the
790individual hierarchical components are concatenated with underscores,
791followed by @samp{_module}. It should call
792@code{scm_register_module_xxx} with the correct module name and the
793appropriate initialization function. When that initialization function
794will be called, a newly created module with the right name will be the
795@emph{current module} so that all definitions that the initialization
796functions makes will end up in the correct module.
797
798After @file{libbessel.so} has been rebuild, we need to place the shared
799library into the right place. When Guile tries to autoload the
800@samp{(math bessel)} module, it looks not only for a file called
801@file{math/bessel.scm} in its @code{%load-path}, but also for
802@file{math/libbessel.so}. So all we need to do is to create a directory
803called @file{math} somewhere in Guile's @code{%load-path} and place
804@file{libbessel.so} there. Normally, the current directory @file{.} is
805in the @code{%load-path}, so we just use that for this example.
806
807@smallexample
808% mkdir maths
809% cd maths
810% ln -s ../libbessel.so .
811% cd ..
812% guile
813guile> (use-modules (math bessel))
814guile> (j0 2)
8150.223890779141236
816guile> (apropos 'j0)
817@print{} bessel: j0 #<primitive-procedure j0>
818@end smallexample
819
820That's it!
821
822Note that we used a symlink to make @file{libbessel.so} appear in the
823right spot. This is probably not a bad idea in general. The
824directories that the @file{%load-path} normally contains are supposed to
825contain only architecture independent files. They are not really the
826right place for a shared library. You might want to install the
827libraries somewhere below @samp{exec_prefix} and then symlink to them
828from the architecture independent directory. This will at least work on
829heterogenous systems where the architecture dependent stuff resides in
830the same place on all machines (which seems like a good idea to me
831anyway).
832
833
2a946b44
NJ
834@node Variables
835@section Variables
836@tpindex Variables
837
838A variable is a box-like object that can hold any Scheme value. It is
839said to be @dfn{undefined} if its box holds a special Scheme value that
840denotes undefined-ness (which is different from all other Scheme values,
841including for example @code{#f}); otherwise the variable is
842@dfn{defined}.
843
844On its own, a variable object is anonymous. A variable is said to be
845@dfn{bound} when it is associated with a name in some way, usually a
846symbol in a module obarray. When this happens, the relationship is
847mutual: the variable is bound to the name (in that module), and the name
848(in that module) is bound to the variable.
849
850(That's the theory, anyway. In practice, defined-ness and bound-ness
851sometimes get confused, because Lisp and Scheme implementations have
852often conflated --- or deliberately drawn no distinction between --- a
853name that is unbound and a name that is bound to a variable whose value
854is undefined. We will try to be clear about the difference and explain
855any confusion where it is unavoidable.)
856
857Variables do not have a read syntax. Most commonly they are created and
858bound implicitly by @code{define} expressions: a top-level @code{define}
859expression of the form
860
861@lisp
862(define @var{name} @var{value})
863@end lisp
864
865@noindent
866creates a variable with initial value @var{value} and binds it to the
867name @var{name} in the current module. But they can also be created
868dynamically by calling one of the constructor procedures
869@code{make-variable} and @code{make-undefined-variable}.
870
871First-class variables are especially useful for interacting with the
872current module system (@pxref{The Guile module system}).
873
874@deffn {Scheme Procedure} make-undefined-variable
875@deffnx {C Function} scm_make_undefined_variable ()
876Return a variable that is initially unbound.
877@end deffn
878
879@deffn {Scheme Procedure} make-variable init
880@deffnx {C Function} scm_make_variable (init)
881Return a variable initialized to value @var{init}.
882@end deffn
883
884@deffn {Scheme Procedure} variable-bound? var
885@deffnx {C Function} scm_variable_bound_p (var)
886Return @code{#t} iff @var{var} is bound to a value.
887Throws an error if @var{var} is not a variable object.
888@end deffn
889
890@deffn {Scheme Procedure} variable-ref var
891@deffnx {C Function} scm_variable_ref (var)
892Dereference @var{var} and return its value.
893@var{var} must be a variable object; see @code{make-variable}
894and @code{make-undefined-variable}.
895@end deffn
896
897@deffn {Scheme Procedure} variable-set! var val
898@deffnx {C Function} scm_variable_set_x (var, val)
899Set the value of the variable @var{var} to @var{val}.
900@var{var} must be a variable object, @var{val} can be any
901value. Return an unspecified value.
902@end deffn
903
904@deffn {Scheme Procedure} variable? obj
905@deffnx {C Function} scm_variable_p (obj)
906Return @code{#t} iff @var{obj} is a variable object, else
907return @code{#f}.
908@end deffn
909
910
a0e07ba4
NJ
911@c Local Variables:
912@c TeX-master: "guile.texi"
913@c End: