~ chicken-core (chicken-5) /manual/Modules
Trap1[[tags: manual]]
2[[toc:]]
3
4
5=== Modules
6
7To allow control over visible bindings and to organize code in namespaces,
8a module system is available. A ''module''
9defines a set of toplevel expressions that are initially evaluated in
10an empty syntactical environment. By ''importing'' other modules,
11exported value- and syntax-bindings are made visible inside the
12environment of the module that imports them.
13
14Note that modules are purely syntactical - they do not change the
15control flow or delay the execution of the contained toplevel
16forms. The body of a module is executed at load-time, when code is
17loaded or imported, just like normal
18toplevel expressions. Exported syntax-definitions are compiled as
19well, and can be accessed in interpreted or compiled code by loading
20and importing the compiled file that contains the module.
21
22Imported toplevel bindings are mutable and can be assigned
23(with {{set!}}), any modifications
24to these will change the global value and will be visible to other
25modules that export or import the same toplevel binding.
26
27A module is initially empty (has no visible bindings with the exception
28of {{import}} and {{cond-expand}}). You must at least
29import the {{scheme}} module to do anything useful. To access any
30of the non-standard macros and procedures, import the {{(chicken base)}}
31module.
32
33CHICKEN's module system has the following features:
34
35* Separation of compile/expansion-time and run-time code is provided, which allows cross compilation
36* Supports batch-compilation of separate compilation units
37* Imports can be lexically scoped
38* Parameterized modules are supported
39
40At toplevel and outside of a module, the initially available bindings
41are everything that is exported from the [[Module scheme|scheme]],
42[[Module (chicken base)|(chicken base)]] and
43[[Module (chicken syntax)|(chicken syntax)]] modules.
44
45
46==== module
47
48<macro>(module NAME (EXPORT ...) BODY ...)</macro>
49<macro>(module NAME (EXPORT ...) FILENAME)</macro>
50<macro>(module NAME * BODY ...)</macro>
51<macro>(module NAME = (FUNCTORNAME MODULENAME1 ...))</macro>
52<macro>(module NAME = FUNCTORNAME BODY ...)</macro>
53
54Defines a module with the name {{NAME}}, a set of exported bindings and
55a contained sequence of toplevel expressions that are evaluated in an
56empty syntactical environment.
57
58{{NAME}} and {{FUNCTORNAME}} should be symbols or lists of symbols and
59integers, where {{(foo bar baz)}} is equivalent to {{foo.bar.baz}}.
60
61{{(EXPORT ...)}} should be an export-specification which holds a list
62of identifiers to be exported from the module and which should be
63visible when imported into another module or the toplevel
64environment. {{EXPORT}} may have any of the following forms:
65
66{{IDENTIFIER}} names a value- or syntax binding to be exported.
67
68{{(IDENTIFIER1 ...)}} or {{(syntax: IDENTIFIER1 ...)}} exports
69{{IDENTIFIER1}} (which should name a macro) and also arranges for the
70remaining identifiers in the list to be visible as value bindings in the expansion of
71the macro (this is a hint to the module expander to export bindings
72referenced by syntax-definitions which make use of them, but which
73would normally be internal to the module - which gives more
74opportunities for optimization).
75
76{{(interface: INTERFACENAME)}} adds all exports defined for the given
77interface to be added to the list of exported identifiers of this
78module.
79
80As a special case, specifying {{*}} instead of an export-list will
81export all definitions. As another special case, the export-list may
82be a symbol naming an interface.
83
84When the {{BODY}} consists of a single string, it is treated
85like {{(include FILENAME)}}.
86
87{{(module NAME = (FUNCTORNAME MODULENAME1 ...))}} instantiates
88a ''functor'' (see below for information about functors).
89
90{{(module NAME = FUNCTORNAME BODY ...)}} is a special form of
91''functor instantiation'' where the {{BODY}} implements a module
92satisfying a single functor argument to {{FUNCTORNAME}}.
93
94Nested modules, modules not at toplevel (i.e. local modules) or
95mutually recursive modules are not supported.
96
97When compiled, the module information, including exported syntax
98is stored in the generated binary and available when loading
99it into interpreted or compiled code. Note that this is different
100to normal syntax (outside of module declarations), which are normally
101not exported from compiled code.
102
103Note that the module system is only a device for controlling the
104mapping of identifiers to value or syntax bindings. Modules do not
105instantiate separate environments that contain their own bindings, as
106do many other module systems. Redefinition or assignment of value or
107syntax bindings will modify the original, imported definition.
108
109Syntax expansions may result in module-definitions, but must be
110at toplevel.
111
112
113==== export
114
115<macro>(export EXPORT ...)</macro>
116
117Allows augmenting module-exports from inside the module-body.
118{{EXPORT}} is if the same form as an export-specifier in a
119{{module}} export list. An export must precede its first occurrence
120(either use or definition).
121
122If used outside of a module, then this form does nothing.
123
124==== export/rename
125
126<macro>(export/rename (NAME EXPORT) ...)</macro>
127
128Allows augmenting module-exports from inside the module-body.
129Each argument should be a two-element list containing the name
130of the local value- or syntax-definition (NAME) and the name under which the
131definition should be exported (EXPORT).
132
133If used outside of a module, then this form does nothing.
134
135==== import
136
137<macro>(import IMPORT ...)</macro>
138
139Imports module bindings into the current syntactical environment.
140The visibility of any imported bindings is limited to the current
141module, if used inside a module-definition, or to the current
142compilation unit, if compiled and used outside of a module.
143
144Importing a module will also load or link its associated library when
145needed.
146
147{{IMPORT}} may be a module name or an ''import specifier'', where a
148module name is either a symbol or a list of symbols and integers.
149An {{IMPORT}} defines a set of bindings that are to be made visible
150in the current scope.
151
152===== only
153
154 [import specifier] (only IMPORT IDENTIFIER ...)
155
156Only import the listed value- or syntax bindings from the set given
157by {{IMPORT}}.
158
159===== except
160
161 [import specifier] (except IMPORT IDENTIFIER ...)
162
163Remove the listed identifiers from the import-set defined by {{IMPORT}}.
164
165===== rename
166
167 [import specifier] (rename IMPORT (OLD1 NEW1) ...)
168
169Renames identifiers imported from {{IMPORT}}.
170
171===== prefix
172
173 [import specifier] (prefix IMPORT SYMBOL)
174
175Prefixes all imported identifiers with {{SYMBOL}}.
176
177==== import-syntax
178
179<macro>(import-syntax IMPORT ...)</macro>
180
181Similar to {{import}} but only import syntactic definitions such as
182macros, as well as identifiers, but does not load or link the library
183containing the module.
184
185==== import-for-syntax
186
187<macro>(import-for-syntax IMPORT ...)</macro>
188
189Similar to {{import}}, but imports exported bindings of a module into
190the environment in which macro transformers are evaluated.
191
192Note: currently this isn't fully correct - value bindings are still
193imported into the normal environment because a separate import
194environment for syntax has not been implemented (syntactic bindings
195are kept separate correctly).
196
197==== import-syntax-for-syntax
198
199<macro>(import-syntax-for-syntax IMPORT ...)</macro>
200
201Combination of {{import-syntax}} and {{import-for-syntax}}. Loads
202syntactic definitions and valinside the environment in which macro
203transformers are evaluated but do not load the associated library.
204
205==== reexport
206
207<macro>(reexport IMPORT ...)</macro>
208
209Imports {{IMPORT ...}} and automatically exports all imported identifiers.
210This can be used to build ''compound modules'': modules that just extend
211other modules:
212
213<enscript hightlight=scheme>
214(module r4rs ()
215 (import scheme (chicken module))
216 (reexport
217 (except scheme
218 dynamic-wind values call-with-values eval scheme-report-environment
219 null-environment interaction-environment)))
220</enscript>
221
222
223=== define-interface
224
225<macro>(define-interface INTERFACENAME (EXPORT ...))</macro>
226
227Defines an ''interface'', a group of exports that can be used in
228module-definitions using the {{(interface: INTERFACE)}} syntax.
229See the definition of {{module}} above for an explanation of
230{{EXPORT}} specifications.
231
232Interface names use a distinct global namespace. Interfaces defined
233inside modules are not visible outside of the module body.
234
235
236=== import libraries
237
238''import libraries'' allow the syntactical (compile-time)
239and run-time parts of a compiled module to be separated into a normal
240compiled file and a shared library that only contains macro definitions
241and module information. This reduces the size of executables and
242simplifies compiling code that uses modules for a different architecture
243than the machine the compiler is executing on (i.e. "cross" compilation).
244
245By using the {{emit-import-library}} compiler-option or declaration,
246a separate file is generated that only contains syntactical information
247(including macros) for a module. {{import}} will automatically find and
248load an import library for a currently unknown module, if the import-
249library is either in the extension repository or the current include
250path. Interpreted code
251can simply load the import library to make the module-definition
252available. Syntax-support definitions defined with {{define-for-syntax}}
253and expansion-time expressions of the form {{(begin-for-syntax ...)}}
254will be added to import libraries to make them available for exported
255syntax. Note that these definitions will ruthlessly pollute the
256toplevel namespace and so they should be used sparingly.
257
258
259=== Predefined modules
260
261Import libraries for the following modules are initially
262available outside of a module:
263
264 [module] scheme
265 [module] (chicken base)
266 [module] (chicken syntax)
267
268Every other module needs to be imported explicitly to have access to
269its exported identifiers.
270
271
272=== Examples of using modules
273
274Here is a silly little test module to demonstrate how modules
275are defined and used:
276
277 ;; hello.scm
278
279 (module test (hello greet)
280 (import scheme)
281
282 (define-syntax greet
283 (syntax-rules ()
284 ((_ whom)
285 (begin
286 (display "Hello, ")
287 (display whom)
288 (display " !\n") ) ) ) )
289
290 (define (hello)
291 (greet "world") ) )
292
293The module {{test}} exports one value ({{hello}}) and one syntax
294binding ({{greet}}). To use it in {{csi}}, the interpreter,
295simply load and import it:
296
297 #;1> ,l hello.scm
298 ; loading hello.scm ...
299 ; loading /usr/local/lib/chicken/4/scheme.import.so ...
300 #;1> (import test)
301 #;2> (hello)
302 Hello, world !
303 #;3> (greet "you")
304 Hello, you !
305
306The module can easily be compiled
307
308 % csc -s hello.scm
309
310and used in an identical manner:
311
312 #;1> ,l hello.so
313 ; loading hello.so ...
314 #;1> (import test)
315 #;2> (hello)
316 Hello, world !
317 #;3> (greet "you")
318 Hello, you !
319
320If you want to keep macro-definitions in a separate file, use import
321libraries:
322
323 % csc -s hello.scm -j test
324 % csc -s test.import.scm
325
326 #;1> ,l hello.so
327 ; loading hello.so ...
328 #;1> (import test)
329 ; loading ./test.import.so ...
330 #;2> (hello)
331 Hello, world !
332 #;3> (greet "you")
333 Hello, you !
334
335If an import library (compiled or in source-form) is located
336somewhere in the extensions-repository or include path, it
337is automatically loaded on import. Otherwise you have to
338load it manually:
339
340 #;1> ,l hello.so
341 ; loading hello.so ...
342 #;1> ,l test.import.so
343 ; loading test.import.so ...
344 #;1> (import test)
345 #;2>
346
347Note that you must use import libraries if you compile code
348that depends on other modules. The compiler will not execute
349the modules that are referred to by compiled code, and thus
350the binding information and exported syntax of the former
351must be available separately.
352
353=== Example of compiling modules and linking them into an executable
354
355Here is a test module, in the file mymod.scm:
356
357<enscript highlight=scheme>
358(module mymod (hello)
359 (import scheme)
360 (define (hello)
361 (display "Hello, World, I'm in mymod!")
362 (newline)))
363</enscript>
364
365Here is the main module, in the file trymod.scm:
366
367<enscript highlight=scheme>
368(module trymod ()
369 (import scheme)
370 (import mymod)
371 (display "I'm in trymod!")
372 (newline)
373 (hello)
374 (display "Now I'm back in trymod!")
375 (newline))
376</enscript>
377
378You can compile mymod.scm into a shared object and compile trymod.scm into an executable trymod that uses that shared object like this:
379
380 csc -s -J mymod.scm
381 csc trymod.scm
382
383You can execute trymod and it will load the shared object mymod.so. When loading a shared
384object, the CHICKEN runtime uses the libld API to obtain the entry point ("C_toplevel") to invoke top-level initialization code of the module (which also setups up global bindings, etc.). However, if you move the trymod executable to another directory, it won't be able to find mymod.so to load it. If you want include the object into the executable directly, it needs to have a unique entry point name, separate from any other entry point of other linked modules.
385
386To give the module a name, we pass the "-unit modulename" argument to csc, and the name of the module is added to the entry point, so the entry point for mymod would become "C_mymod_toplevel". Then the "-uses modulename" argument is passed to csc while compiling and linking trymod so it knows to use that entry point.
387
388To compile mymod.scm and trymod.scm and link them into the executable trymod, issue the following commands:
389
390 csc -c -J mymod.scm -unit mymod -o mymod.o
391 csc -o trymod mymod.o -uses mymod trymod.scm
392
393This creates an executable that is dynamically linked against libchicken.so, but which includes the mymod.o object file directly.
394
395To create an executable that is statically linked, issue the following commands:
396
397 csc -c -static -J mymod.scm -unit mymod -o mymod.o
398 csc -o trymod -static mymod.o -uses mymod trymod.scm
399
400If you later add another module you'd need to compile it similar to how mymod.scm is
401compiled and add a "modulename.o -uses modulename" to the csc command that compiles trymod.scm.
402
403It is possible to use the csm program installed by the [[/egg/csm|csm egg]] to do this automatically. To produce a dynamically linked program you would do:
404
405 csm -program trymod
406
407To produce a statically linked program you would do:
408
409 csm -static -program trymod
410
411=== Functors
412
413A ''functor'' is a higher-order module that can be parameterized with
414other modules. A functor defines the body of a module for a set of
415argument modules and can be instantiated with concrete module names
416specializing the code contained in the functor. This is best explained
417with a silly and pointless example:
418
419<enscript highlight=scheme>
420(functor (squaring-functor (M (multiply))) (square)
421 (import scheme M)
422 (define (square x) (multiply x x)))
423</enscript>
424
425This defines a generic "squaring" operation that uses {{multiply}}, a
426procedure (or macro!) exported by the as-yet-unknown module {{M}}. Now
427let's instantiate the functor for a specific input module:
428
429<enscript highlight=scheme>
430(module nums (multiply)
431 (import scheme)
432 (define (multiply x y) (* x y)))
433
434(module number-squarer = (squaring-functor nums))
435
436(import number-squarer)
437(square 3) ===> 9
438</enscript>
439
440We can easily instantiate the functor for other inputs:
441
442<enscript highlight=scheme>
443(module stars (multiply)
444 (import scheme)
445 (define (list-tabulate n f)
446 (let loop ((i 0))
447 (if (= i n)
448 '()
449 (cons (f i) (loop (+ i 1))))))
450 (define (multiply x y)
451 (list-tabulate x (lambda _ (list-tabulate y (lambda _ '*))))))
452
453(module star-squarer = (squaring-functor stars))
454
455(import star-squarer)
456(square 3) ===> ((* * *)
457 (* * *)
458 (* * *))
459</enscript>
460
461So whenever you have a generic algorithm it can be packaged into a
462functor and specialized for specific input modules. The instantiation
463will check that the argument modules match the required signature,
464{{(multiply)}} in the case above. The argument module must export at
465least the signature given in the functor definition. You can use
466{{define-interface}} to reduce typing and give a more meaningful name
467to a set of exports.
468
469The general syntax of a functor definition looks like this:
470
471<syntax>(functor (FUNCTORNAME (ARGUMENTMODULE1 EXPORTS1) ...) FUNCTOREXPORTS BODY)</syntax>
472
473Defines a "functor", a parameterized module.
474
475This functor definition does not generate any code. This is done
476by ''instantiating'' the functor for specific input modules:
477
478<enscript highlight=scheme>
479(module MODULENAME = (FUNCTORNAME MODULENAME1 ...))
480</enscript>
481
482Inside {{BODY}}, references to {{ARGUMENTMODULE}} will be replaced by
483the corresponding {{MODULENAME}} argument. The instantiation expands
484into the complete functor-code {{BODY}} and as such can be considered
485a particular sort of macro-expansion. Note that there is no
486requirement that a specific export of an argument-module must be
487syntax or non-syntax - it can be syntax in one instantiation and a
488procedure definition in another.
489
490{{ARGUMENTMODULE}} may also be a list of the form {{(ALIAS DEFAULT)}}
491to allow specifying a default- or optional functor argument in case
492the instanation doesn't provide one. Optional functor
493arguments may only be followed by non-optional functor arguments.
494
495The common case of using a functor with a single argument module
496that is not used elsewhere can be expressed in the following way:
497
498<enscript highlight=scheme>
499(module NAME = FUNCTORNAME BODY ...)
500</enscript>
501
502which is the same as
503
504<enscript highlight=scheme>
505(begin
506 (module _NAME * BODY ...)
507 (module NAME = (FUNCTORNAME _NAME)))
508</enscript>
509
510Since functors exist at compile time, they can be stored in
511import-libraries via {{-emit-import-library FUNCTORNAME}} or
512{{-emit-all-import-libraries}} (see [[Using the compiler]] for more
513information about this). That allows you to import functors for later
514instantiation. Internally, a functor-definition also defines a module
515with the same name, but importing this module has no effect. It also
516has no runtime code, so it is sufficient to merely {{import}} it (as
517opposed to using {{require-extension}} or one of its variants, which
518also loads the run-time part of a module).
519
520Note that functor-instantiation creates a complete copy of the
521functor body.
522
523=== current-module
524
525<macro>(current-module)</macro>
526
527This will expand to a symbol which matches the current module's name
528when used inside a module. If not inside a module (i.e., at
529toplevel), this expands to {{#f}}.
530
531
532---
533Previous: [[Interface to external functions and variables]]
534
535Next: [[Types]]