~ chicken-core (master) /manual/Modules


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