Debian Codegraph @

src/module.c

raw
1 /*
2 * module.c - module implementation
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #define LIBGAUCHE_BODY
35 #include "gauche.h"
36 #include "gauche/priv/configP.h"
37 #include "gauche/priv/builtin-syms.h"
38 #include "gauche/priv/glocP.h"
39 #include "gauche/priv/moduleP.h"
40
41 /*
42 * Modules
43 *
44 * A module maps symbols to global locations (GLOCs).
45 * The mapping is resolved at the compile time.
46 * Scheme's current-module is therefore a syntax, instead of
47 * a procedure, to capture compile-time information.
48 *
49 * Each module has two hashtables; the 'internal' table keeps all the
50 * bindings in the module, while the 'external' table keeps only the
51 * bindings that are exported. In most cases, the latter is a subset
52 * of the former. If a binding is renamed on export, however,
53 * two tables map different symbols on the same GLOC.
54 *
55 * Modules are registered to a global hash table using their names
56 * as keys, so that the module is retrieved by its name. The exception
57 * is "anonymous modules", which have #f as the name field
58 * and not registered in the global table. Anonymous modules are especially
59 * useful for certain applications that need temporary, segregated
60 * namespace---for example, a 'sandbox' environment to evaluate an
61 * expression sent over the network during a session.
62 * The anonymous namespace will be garbage-collected if nobody references
63 * it, recovering its resources.
64 */
65
66 /* Note on mutex of module operation
67 *
68 * Each module used to have a mutex for accesses to it. I changed it
69 * to use a single global lock (modules.mutex), based on the following
70 * observations:
71 *
72 * - Profiling showed mutex_lock was taking around 10% of program loading
73 * phase in the previous version.
74 *
75 * - Module operations almost always occur during program loading and
76 * interactive session. Having giant lock for module operations won't
77 * affect normal runtime performance.
78 *
79 * Benchmark showed the change made program loading 30% faster.
80 */
81
82 /* Special treatment of keyword modules.
83 * We need to achieve two goals:
84 *
85 * (1) For ordinary Gauche programs (modules that uses implicit inheritance
86 * of #<module gauche>), we want to see all keywords being bound to
87 * itself by default. It can be achieved by inheriting a module that
88 * has such keyword bindings.
89 * (2) For R7RS programs we want to see the default keyword bindings only
90 * when the programmer explicitly asks so - notably, by importing some
91 * special module. It can be achieved by a module that has all keywords
92 * each bound to itself, *and* exports all of such bindings.
93 *
94 * It turned out we can't use one 'keyword' module for both purpose; if
95 * we have a keyword module that exports all bindings, they are automatically
96 * exported from modules that inherits them. This means if a R7RS program
97 * imports any of Gauche modules, it carries all of keyword bindings. It's
98 * not only nasty, but also dangerous for it can shadow bindings to the
99 * symbols starting with a colon inadvertently.
100 *
101 * So we have two modules, #<module gauche.keyword> and
102 * #<module keyword>. The former have export-all flag, and to be imported
103 * from R7RS programs as needed. The latter doesn't export anything, and
104 * to be inherited to Gauche modules by default. Whenever a keyword
105 * is created, its default binding is inserted to both - actually,
106 * to prevent two modules from being out of sync, we specially wire them
107 * to share a single hashtable for their internal bindings.
108 */
109
110 /* Note on gauche.require-base module
111 It is an immutable module to which 'require' loads code.
112 We need a base module where 'define-module' and 'define-library' are
113 visible in order for requiring modules using them to work, so
114 loading into the current module won't cut it. However, we don't
115 want to use a specific mutable module (such as #<module gauche>) as
116 a base, since if the required module has toplevel defines without
117 switching the module, it will modify the base module.
118 By using immutable module as a base, we can reject the latter case;
119 requiring a code that inserts toplevel binding without specifying
120 a module is simply a bad idea and shouldn't be allowed.
121 */
122
123 /* Note on gauche.bootstrap module
124 This module is only exists during boot process. Once booting is
125 complete, it is destroyed. We use the module to define some
126 under-the-hood procedures that we don't want ordinary programs
127 to call directly.
128 */
129
130 /* Global module table */
131 static struct {
132 ScmHashTable *table; /* Maps name -> module. */
133 ScmInternalMutex mutex; /* Lock for table. Only register_module and
134 lookup_module may hold the lock. */
135 } modules;
136
137 /* Predefined modules - slots will be initialized by Scm__InitModule */
138 #define DEFINE_STATIC_MODULE(cname) \
139 static ScmModule cname;
140
141 DEFINE_STATIC_MODULE(nullModule); /* #<module null> */
142 DEFINE_STATIC_MODULE(schemeModule); /* #<module scheme> */
143 DEFINE_STATIC_MODULE(gaucheModule); /* #<module gauche> */
144 DEFINE_STATIC_MODULE(internalModule); /* #<module gauche.internal> */
145 DEFINE_STATIC_MODULE(gfModule); /* #<module gauche.gf> */
146 DEFINE_STATIC_MODULE(userModule); /* #<module user> */
147 DEFINE_STATIC_MODULE(keywordModule); /* #<module keyword> */
148 DEFINE_STATIC_MODULE(gkeywordModule); /* #<module gauche.keyword> */
149 DEFINE_STATIC_MODULE(reqbaseModule); /* #<module gauche.require-base> */
150
151 static ScmObj defaultParents = SCM_NIL; /* will be initialized */
152 static ScmObj defaultMpl = SCM_NIL; /* will be initialized */
153 static ScmObj bootstrapModule = SCM_FALSE; /* will be initialized */
154
155 /*----------------------------------------------------------------------
156 * Constructor
157 */
158
159 static void init_module(ScmModule *m, ScmObj name, ScmHashTable *internal)
160 {
161 m->name = name;
162 m->imported = m->depended = SCM_NIL;
163 m->exportAll = FALSE;
164 m->parents = defaultParents;
165 m->mpl = Scm_Cons(SCM_OBJ(m), defaultMpl);
166 if (internal) {
167 m->internal = internal;
168 } else {
169 m->internal = SCM_HASH_TABLE(Scm_MakeHashTableSimple(SCM_HASH_EQ, 0));
170 }
171 m->external = SCM_HASH_TABLE(Scm_MakeHashTableSimple(SCM_HASH_EQ, 0));
172 m->origin = m->prefix = SCM_FALSE;
173 m->sealed = FALSE;
174 m->placeholding = FALSE;
175 }
176
177 /* Internal */
178 static ScmObj make_module(ScmObj name, ScmHashTable *internal)
179 {
180 ScmModule *m = SCM_NEW(ScmModule);
181 SCM_SET_CLASS(m, SCM_CLASS_MODULE);
182 init_module(m, name, internal);
183 return SCM_OBJ(m);
184 }
185
186 /* Internal. Lookup module with name N from the table. */
187 static ScmModule *lookup_module(ScmSymbol *name)
188 {
189 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
190 ScmObj v = Scm_HashTableRef(modules.table, SCM_OBJ(name), SCM_UNBOUND);
191 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
192 if (SCM_UNBOUNDP(v)) return NULL;
193 else return SCM_MODULE(v);
194 }
195
196 /* Internal. Lookup module, and if there's none, create one. */
197 static ScmModule *lookup_module_create(ScmSymbol *name, int *created)
198 {
199 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
200 ScmDictEntry *e = Scm_HashCoreSearch(SCM_HASH_TABLE_CORE(modules.table),
201 (intptr_t)name,
202 SCM_DICT_CREATE);
203 if (e->value == 0) {
204 (void)SCM_DICT_SET_VALUE(e, make_module(SCM_OBJ(name), NULL));
205 *created = TRUE;
206 } else {
207 *created = FALSE;
208 }
209 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
210 return SCM_MODULE(e->value);
211 }
212
213 ScmObj Scm_MakeModule(ScmSymbol *name, int error_if_exists)
214 {
215 if (name == NULL) {
216 return make_module(SCM_FALSE, NULL);
217 }
218 int created;
219 ScmObj r = SCM_OBJ(lookup_module_create(name, &created));
220 if (!created) {
221 if (error_if_exists) {
222 Scm_Error("couldn't create module '%S': named module already exists",
223 SCM_OBJ(name));
224 }
225 return SCM_FALSE;
226 }
227 return r;
228 }
229
230 /* internal API to create an anonymous wrapper module */
231 ScmObj Scm__MakeWrapperModule(ScmModule *origin, ScmObj prefix)
232 {
233 ScmModule *m = SCM_MODULE(make_module(SCM_FALSE, NULL));
234 m->parents = SCM_LIST1(SCM_OBJ(origin));
235 m->mpl = Scm_Cons(SCM_OBJ(m), origin->mpl);
236 m->prefix = prefix;
237 while (SCM_MODULEP(origin->origin)) {
238 origin = SCM_MODULE(origin->origin);
239 }
240 m->origin = SCM_OBJ(origin);
241 return SCM_OBJ(m);
242 }
243
244 /* Common code to report error on sealed module.
245 One common error is to try to 'use' or 'require' a file that doesn't
246 have module definitions in it. The default error message in that case
247 is perplexing, so we use more helpful message in that case.
248 */
249 static void err_sealed(ScmObj source, ScmModule *target)
250 {
251 const char *what = "";
252 if (SCM_MODULEP(source)) what = "import a module";
253 else what = "create a binding";
254
255 if (target == Scm__RequireBaseModule()) {
256 Scm_Error("Attempted to %s (%S) into gauche.require-base. "
257 "This may be caused by trying to 'use' or 'require' a file"
258 " in which no module is defined. Make sure the file has"
259 " define-module/select-module or define-library at the"
260 " beginning.",
261 what, source, SCM_OBJ(target));
262 } else {
263 Scm_Error("Attempted to %s (%S) in a sealed module: %S",
264 what, source, SCM_OBJ(target));
265 }
266 }
267
268 /*----------------------------------------------------------------------
269 * Finding and modifying bindings
270 */
271
272 #define SEARCHED_ARRAY_SIZE 64
273
274 /* Keep record of searched modules. we use stack array for small # of
275 modules, in order to avoid consing for typical cases. */
276 typedef struct {
277 int num_searched;
278 ScmObj searched[SEARCHED_ARRAY_SIZE];
279 ScmObj more_searched;
280 } module_cache;
281
282
283 static inline void init_module_cache(module_cache *c)
284 {
285 c->num_searched = 0;
286 c->more_searched = SCM_NIL;
287 }
288
289 static inline int module_visited_p(module_cache *c, ScmModule *m)
290 {
291 for (int i=0; i<c->num_searched; i++) {
292 if (SCM_EQ(SCM_OBJ(m), c->searched[i])) return TRUE;
293 }
294 if (!SCM_NULLP(c->more_searched)) {
295 if (!SCM_FALSEP(Scm_Memq(SCM_OBJ(m), c->more_searched))) return TRUE;
296 }
297 return FALSE;
298 }
299
300 static inline void module_add_visited(module_cache *c, ScmModule *m)
301 {
302 if (c->num_searched < SEARCHED_ARRAY_SIZE) {
303 c->searched[c->num_searched++] = SCM_OBJ(m);
304 } else {
305 c->more_searched = Scm_Cons(SCM_OBJ(m), c->more_searched);
306 }
307 }
308
309 /* The main logic of global binding search. We factored this out since
310 we need recursive searching in case of phantom binding (see gloc.h
311 about phantom bindings). The flags stay_in_module and external_only
312 corresponds to the flags passed to Scm_FindBinding. The exclude_self
313 flag is only used in recursive search. */
314 static ScmGloc *search_binding(ScmModule *module, ScmSymbol *symbol,
315 int stay_in_module, int external_only,
316 int exclude_self)
317 {
318 module_cache searched;
319 init_module_cache(&searched);
320
321 /* First, search from the specified module. In this phase, we just ignore
322 phantom bindings, for we'll search imported bindings later anyway. */
323 if (!exclude_self) {
324 ScmObj v = Scm_HashTableRef(
325 external_only? module->external : module->internal,
326 SCM_OBJ(symbol), SCM_FALSE);
327 if (SCM_GLOCP(v)) {
328 if (SCM_GLOC_PHANTOM_BINDING_P(SCM_GLOC(v))) {
329 /* If we're here, the symbol is external to MODULE but
330 the real GLOC is somewhere in imported or inherited
331 modules. We turn off external_only switch so that
332 when we search inherited modules we look into it's
333 internal bindings. */
334 external_only = FALSE;
335 symbol = SCM_GLOC(v)->name; /* in case it's renamed on export */
336 } else {
337 return SCM_GLOC(v);
338 }
339 }
340 if (stay_in_module) return NULL;
341 module_add_visited(&searched, module);
342 }
343
344 ScmObj p, mp;
345 /* Next, search from imported modules
346 If the import is prefixed, we avoid caching the result. */
347 SCM_FOR_EACH(p, module->imported) {
348 ScmObj elt = SCM_CAR(p);
349 ScmObj sym = SCM_OBJ(symbol);
350 int prefixed = FALSE;
351
352 SCM_ASSERT(SCM_MODULEP(elt));
353 SCM_FOR_EACH(mp, SCM_MODULE(elt)->mpl) {
354 ScmGloc *g;
355
356 SCM_ASSERT(SCM_MODULEP(SCM_CAR(mp)));
357 ScmModule *m = SCM_MODULE(SCM_CAR(mp));
358 if (!prefixed && module_visited_p(&searched, m)) continue;
359 if (SCM_SYMBOLP(m->prefix)) {
360 sym = Scm_SymbolSansPrefix(SCM_SYMBOL(sym),
361 SCM_SYMBOL(m->prefix));
362 if (!SCM_SYMBOLP(sym)) break;
363 prefixed = TRUE;
364 }
365
366 ScmObj v = Scm_HashTableRef(m->external, SCM_OBJ(sym), SCM_FALSE);
367 if (SCM_GLOCP(v)) {
368 g = SCM_GLOC(v);
369 if (g->hidden) break;
370 if (SCM_GLOC_PHANTOM_BINDING_P(g)) {
371 g = search_binding(m, g->name, FALSE, FALSE, TRUE);
372 if (g) return g;
373 } else {
374 return g;
375 }
376 }
377 if (!prefixed) module_add_visited(&searched, m);
378 }
379 }
380
381 /* Then, search from parent modules */
382 SCM_ASSERT(SCM_PAIRP(module->mpl));
383 SCM_FOR_EACH(mp, SCM_CDR(module->mpl)) {
384 SCM_ASSERT(SCM_MODULEP(SCM_CAR(mp)));
385 ScmModule *m = SCM_MODULE(SCM_CAR(mp));
386
387 if (SCM_SYMBOLP(m->prefix)) {
388 ScmObj sym = Scm_SymbolSansPrefix(symbol, SCM_SYMBOL(m->prefix));
389 if (!SCM_SYMBOLP(sym)) return NULL;
390 symbol = SCM_SYMBOL(sym);
391 }
392 ScmObj v = Scm_HashTableRef(external_only?m->external:m->internal,
393 SCM_OBJ(symbol), SCM_FALSE);
394
395 if (SCM_GLOCP(v)) {
396 if (SCM_GLOC_PHANTOM_BINDING_P(SCM_GLOC(v))) {
397 symbol = SCM_GLOC(v)->name; /* in case it's renamed on export */ ScmGloc *g = search_binding(m, symbol, FALSE, FALSE, TRUE);
398 if (g) return g;
399 external_only = FALSE; /* See above comment */
400 } else {
401 return SCM_GLOC(v);
402 }
403 }
404 }
405 return NULL;
406 }
407
408 /* See also Scm_IdentifierGlobalBinding in compaux.c */
409 ScmGloc *Scm_FindBinding(ScmModule *module, ScmSymbol *symbol, int flags)
410 {
411 int stay_in_module = flags&SCM_BINDING_STAY_IN_MODULE;
412 int external_only = flags&SCM_BINDING_EXTERNAL;
413 ScmGloc *gloc = NULL;
414
415 SCM_INTERNAL_MUTEX_SAFE_LOCK_BEGIN(modules.mutex);
416 gloc = search_binding(module, symbol, stay_in_module, external_only, FALSE);
417 SCM_INTERNAL_MUTEX_SAFE_LOCK_END();
418 return gloc;
419 }
420
421 /* See also Scm_GlobalIdentifierRef in compaux.c */
422 ScmObj Scm_GlobalVariableRef(ScmModule *module,
423 ScmSymbol *symbol,
424 int flags)
425 {
426 ScmGloc *g = Scm_FindBinding(module, symbol, flags);
427
428 if (g == NULL) return SCM_UNBOUND;
429 ScmObj val = SCM_GLOC_GET(g);
430 if (SCM_AUTOLOADP(val)) {
431 /* NB: Scm_ResolveAutoload may return SCM_UNBOUND */
432 val = Scm_ResolveAutoload(SCM_AUTOLOAD(val), 0);
433 }
434 return val;
435 }
436
437 /*
438 * Definition.
439 */
440 ScmGloc *Scm_MakeBinding(ScmModule *module, ScmSymbol *symbol,
441 ScmObj value, int flags)
442 {
443 if (module->sealed) err_sealed(SCM_OBJ(symbol), module);
444
445 ScmGloc *g;
446 int existing = FALSE;
447
448 SCM_INTERNAL_MUTEX_SAFE_LOCK_BEGIN(modules.mutex);
449 ScmObj v = Scm_HashTableRef(module->internal, SCM_OBJ(symbol), SCM_FALSE);
450 /* NB: this function bypasses check of gloc setter */
451 if (SCM_GLOCP(v)) {
452 g = SCM_GLOC(v);
453 existing = TRUE;
454 } else {
455 g = SCM_GLOC(Scm_MakeGloc(symbol, module));
456 Scm_HashTableSet(module->internal, SCM_OBJ(symbol), SCM_OBJ(g), 0);
457 /* If module is marked 'export-all', export this binding by default */
458 if (module->exportAll && SCM_SYMBOL_INTERNED(symbol)) {
459 Scm_HashTableSet(module->external, SCM_OBJ(symbol), SCM_OBJ(g), 0);
460 }
461 }
462 SCM_INTERNAL_MUTEX_SAFE_LOCK_END();
463
464 if (existing && !Scm_GlocSupersedableP(g, flags, value)) {
465 Scm_Warn("redefining %s %S#%S",
466 Scm_GlocConstP(g)? "constant" : "inlinable",
467 g->module->name, g->name);
468 }
469
470 g->value = value;
471 Scm_GlocMark(g, flags);
472 return g;
473 }
474
475 /* Convenience wrapper (return value is ScmObj for the backward compatibility)*/
476 ScmObj Scm_Define(ScmModule *module, ScmSymbol *symbol, ScmObj value)
477 {
478 return SCM_OBJ(Scm_MakeBinding(module, symbol, value, 0));
479 }
480
481 ScmObj Scm_DefineConst(ScmModule *module, ScmSymbol *symbol, ScmObj value)
482 {
483 return SCM_OBJ(Scm_MakeBinding(module, symbol, value, SCM_BINDING_CONST));
484 }
485
486 /*
487 * Injecting hidden binding
488 * This inserts a dummy binding with hidden==true so that
489 * the module effectively removes the binding of the given symbol
490 * inherited from parent.
491 * This is not for genreral use. It is intended to be used for
492 * intermediate anonymous modules, created by import handling
493 * routine to implement :except and :rename qualifiers.
494 * Since we assume MODULE is for intermediate modules, we only
495 * insert bindings to the external table, for those modules are
496 * only searched in the 'import' path.
497 */
498 void Scm_HideBinding(ScmModule *module, ScmSymbol *symbol)
499 {
500 if (module->sealed) err_sealed(SCM_OBJ(symbol), module);
501
502 int err_exists = FALSE;
503
504 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
505 ScmObj v = Scm_HashTableRef(module->external, SCM_OBJ(symbol), SCM_FALSE);
506 if (!SCM_FALSEP(v)) {
507 if (!SCM_GLOC(v)->hidden) err_exists = TRUE;
508 } else {
509 ScmGloc *g = SCM_GLOC(Scm_MakeGloc(symbol, module));
510 g->hidden = TRUE;
511 Scm_HashTableSet(module->external, SCM_OBJ(symbol), SCM_OBJ(g), 0);
512 }
513 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
514
515 if (err_exists) {
516 Scm_Error("hide-binding: binding already exists: %S (exports=%S)", SCM_OBJ(symbol), Scm_ModuleExports(module));
517 }
518 }
519
520 /*
521 * Binding aliasing
522 * This is a special operation to realize :only and :rename import option.
523 * The name ORIGINNAME is looked up in the module ORIGIN to get a gloc.
524 * Then the gloc is directly inserted into the module TARGET under the name
525 * TARGETNAME.
526 * Since gloc is shared, subsequent changes in the binding are also shared.
527 *
528 * If the original binding doesn't exist, or isn't exported, noop and
529 * FALSE is returned. Otherwise TRUE is returned.
530 *
531 * CAVEATS:
532 *
533 * - gloc's module remains the same.
534 * - autoload won't be resolved.
535 * - TARGETNAME shouldn't be bound in TARGET beforehand. We don't check
536 * it and just insert the gloc. If there is an existing binding,
537 * it would become orphaned, possibly causing problems.
538 *
539 * NB: This is the only operation that causes a gloc to be shared between
540 * more than one modules. I'm not yet clear on the implication of such
541 * sharing in general, so this should be used with care. At least it
542 * won't cause much trouble if the target module is an implicit anonymous
543 * module created by :only and :rename import options.
544 */
545 int Scm_AliasBinding(ScmModule *target, ScmSymbol *targetName,
546 ScmModule *origin, ScmSymbol *originName)
547 {
548 if (target->sealed) err_sealed(SCM_OBJ(targetName), target);
549
550 ScmGloc *g = Scm_FindBinding(origin, originName, SCM_BINDING_EXTERNAL);
551 if (g == NULL) return FALSE;
552 SCM_INTERNAL_MUTEX_SAFE_LOCK_BEGIN(modules.mutex);
553 Scm_HashTableSet(target->external, SCM_OBJ(targetName), SCM_OBJ(g), 0);
554 Scm_HashTableSet(target->internal, SCM_OBJ(targetName), SCM_OBJ(g), 0);
555 SCM_INTERNAL_MUTEX_SAFE_LOCK_END();
556 return TRUE;
557 }
558
559 /*
560 * Import
561 */
562 ScmObj Scm_ImportModule(ScmModule *module,
563 ScmObj imported,
564 ScmObj prefix,
565 u_long flags SCM_UNUSED) /* reserved for future use */
566 {
567 if (module->sealed) err_sealed(SCM_OBJ(imported), module);
568
569 ScmModule *imp = NULL;
570 if (SCM_MODULEP(imported)) {
571 imp = SCM_MODULE(imported);
572 } else if (SCM_SYMBOLP(imported)) {
573 imp = Scm_FindModule(SCM_SYMBOL(imported), 0);
574 } else if (SCM_IDENTIFIERP(imported)) {
575 imp = Scm_FindModule(Scm_UnwrapIdentifier(SCM_IDENTIFIER(imported)), 0);
576 } else {
577 Scm_Error("module name or module required, but got %S", imported);
578 }
579
580 if (SCM_SYMBOLP(prefix)) {
581 imp = SCM_MODULE(Scm__MakeWrapperModule(imp, prefix));
582 }
583
584 /* Preallocate a pair, so that we won't call malloc during locking */
585 ScmObj p = Scm_Cons(SCM_OBJ(imp), SCM_NIL);
586
587 /* Prepend imported module to module->imported list. */
588 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
589 {
590 ScmObj ms, prev = p;
591 SCM_SET_CDR_UNCHECKED(p, module->imported);
592 /* Remove duplicate module, if any.
593 NB: We allow to import the same module multiple times if they are
594 qualified by :only, :prefix, etc. Theoretically we should check
595 exactly same qualifications, but we hope that kind of duplication
596 is rare.
597 */
598 SCM_FOR_EACH(ms, SCM_CDR(p)) {
599 ScmModule *m = SCM_MODULE(SCM_CAR(ms));
600 if (!SCM_EQ(SCM_OBJ(m), SCM_OBJ(imp))) {
601 prev = ms;
602 continue;
603 }
604 SCM_SET_CDR_UNCHECKED(prev, SCM_CDR(ms));
605 break;
606 }
607 module->imported = p;
608 }
609 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
610
611 return module->imported;
612 }
613
614 /* Deprecated */
615 ScmObj Scm_ImportModules(ScmModule *module, ScmObj list)
616 {
617 ScmObj lp;
618 SCM_FOR_EACH(lp, list) {
619 Scm_ImportModule(module, SCM_CAR(lp), SCM_FALSE, 0);
620 }
621 return module->imported;
622 }
623
624 /*
625 * Export
626 */
627 /* <spec> :: <name> | (rename <name> <exported-name>) */
628 ScmObj Scm_ExportSymbols(ScmModule *module, ScmObj specs)
629 {
630 ScmObj lp;
631 ScmObj overwritten = SCM_NIL; /* list of (exported-name orig-internal-name
632 new-internal-name). */
633 /* Check input first */
634 SCM_FOR_EACH(lp, specs) {
635 ScmObj spec = SCM_CAR(lp);
636 if (!(SCM_SYMBOLP(spec)
637 || (SCM_PAIRP(spec) && SCM_PAIRP(SCM_CDR(spec))
638 && SCM_PAIRP(SCM_CDDR(spec))
639 && SCM_NULLP(SCM_CDR(SCM_CDDR(spec)))
640 && SCM_EQ(SCM_CAR(spec), SCM_SYM_RENAME)
641 && SCM_SYMBOLP(SCM_CADR(spec))
642 && SCM_SYMBOLP(SCM_CAR(SCM_CDDR(spec)))))) {
643 Scm_Error("Invalid export-spec; a symbol, or (rename <symbol> <symbol>) is expected, but got %S", spec);
644 }
645 }
646
647 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
648 SCM_FOR_EACH(lp, specs) {
649 ScmObj spec = SCM_CAR(lp);
650 ScmSymbol *name, *exported_name;
651 if (SCM_SYMBOLP(spec)) {
652 name = exported_name = SCM_SYMBOL(spec);
653 } else {
654 /* we already knew those are symbols */
655 name = SCM_SYMBOL(SCM_CADR(spec));
656 exported_name = SCM_SYMBOL(SCM_CAR(SCM_CDDR(spec)));
657 }
658 ScmDictEntry *e = Scm_HashCoreSearch(SCM_HASH_TABLE_CORE(module->external),
659 (intptr_t)exported_name, SCM_DICT_GET);
660 if (e) {
661 /* If we have e, it's already exported. Check if
662 the previous export is for the same binding. */
663 SCM_ASSERT(SCM_DICT_VALUE(e) && SCM_GLOCP(SCM_DICT_VALUE(e)));
664 ScmGloc *g = SCM_GLOC(SCM_DICT_VALUE(e));
665 if (!SCM_EQ(name, g->name)) {
666 /* exported_name got a different meaning. we record it to warn
667 later, then 'unexport' the old one. */
668 overwritten = Scm_Cons(SCM_LIST3(SCM_OBJ(exported_name),
669 SCM_OBJ(g->name),
670 SCM_OBJ(name)),
671 overwritten);
672 Scm_HashCoreSearch(SCM_HASH_TABLE_CORE(module->external),
673 (intptr_t)exported_name, SCM_DICT_DELETE);
674 e = NULL;
675 }
676 }
677 /* we check again, for the symbol may be unexported above. */
678 if (e == NULL) {
679 /* This symbol hasn't been exported. Either it only has an
680 internal binding, or there's no binding at all. In the latter
681 case, we create a new binding (without value). */
682 e = Scm_HashCoreSearch(SCM_HASH_TABLE_CORE(module->internal),
683 (intptr_t)name, SCM_DICT_CREATE);
684 if (!e->value) {
685 ScmGloc *g = SCM_GLOC(Scm_MakeGloc(name, module));
686 (void)SCM_DICT_SET_VALUE(e, SCM_OBJ(g));
687 }
688 Scm_HashTableSet(module->external, SCM_OBJ(exported_name),
689 SCM_DICT_VALUE(e), 0);
690 }
691 }
692 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
693
694 /* Now, if this export changes the meaning of exported symbols, we
695 warn it. We expect this only happens at the development time, when
696 one is fiddling exports incrementally, so we just use Scm_Warn -
697 a library ready to be used shouldn't cause this warning. */
698 if (!SCM_NULLP(overwritten)) {
699 ScmObj lp;
700 SCM_FOR_EACH(lp, overwritten) {
701 ScmObj p = SCM_CAR(lp);
702 Scm_Warn("Exporting %S from %S as %S overrides the previous export of %S",
703 SCM_CAR(SCM_CDDR(p)), SCM_OBJ(module), SCM_CAR(p),
704 SCM_CADR(p));
705 }
706 }
707
708 return SCM_UNDEFINED; /* we might want to return something more useful...*/
709 }
710
711 ScmObj Scm_ExportAll(ScmModule *module)
712 {
713 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
714 if (!module->exportAll) {
715 /* Mark the module 'export-all' so that the new bindings would get
716 exported mark by default. */
717 module->exportAll = TRUE;
718
719 /* Scan the module and mark all existing bindings as exported. */
720 ScmHashIter iter;
721 Scm_HashIterInit(&iter, SCM_HASH_TABLE_CORE(module->internal));
722 ScmDictEntry *e;
723 while ((e = Scm_HashIterNext(&iter)) != NULL) {
724 ScmDictEntry *ee;
725 ee = Scm_HashCoreSearch(SCM_HASH_TABLE_CORE(module->external),
726 e->key, SCM_DICT_CREATE);
727 if (!ee->value) {
728 (void)SCM_DICT_SET_VALUE(ee, SCM_DICT_VALUE(e));
729 }
730 }
731 }
732 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
733 return SCM_OBJ(module);
734 }
735
736 /* internal routine form Scm_ModuleExports */
737 static void add_parent_module_exports(ScmHashCore *syms,
738 ScmModule *module,
739 module_cache *visited)
740 {
741 ScmObj mp;
742 SCM_FOR_EACH(mp, module->mpl) {
743 ScmModule *m = SCM_MODULE(SCM_CAR(mp));
744 if (module_visited_p(visited, m)) continue;
745 module_add_visited(visited, m);
746
747 ScmHashIter iter;
748 Scm_HashIterInit(&iter, SCM_HASH_TABLE_CORE(m->external));
749 ScmDictEntry *e;
750 while ((e = Scm_HashIterNext(&iter)) != NULL) {
751 if (!(SCM_GLOC(SCM_DICT_VALUE(e)))->hidden) {
752 (void)Scm_HashCoreSearch(syms, e->key, SCM_DICT_CREATE);
753 }
754 }
755 add_parent_module_exports(syms, m, visited);
756 }
757 }
758
759 /* Returns list of exported symbols. We assume this is infrequent
760 operation, so we build the list every call. If it becomes a problem,
761 we can cache the result. */
762 ScmObj Scm_ModuleExports(ScmModule *module)
763 {
764 ScmHashCore syms;
765 Scm_HashCoreInitSimple(&syms, SCM_HASH_EQ, 0, NULL);
766 module_cache visited;
767 init_module_cache(&visited);
768
769 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
770 Scm_HashCoreCopy(&syms, SCM_HASH_TABLE_CORE(module->external));
771 add_parent_module_exports(&syms, module, &visited);
772 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
773
774 ScmObj h = SCM_NIL, t = SCM_NIL;
775 ScmHashIter iter;
776 Scm_HashIterInit(&iter, &syms);
777 ScmDictEntry *e;
778 while ((e = Scm_HashIterNext(&iter)) != NULL) {
779 intptr_t v = e->value;
780 if (!v || (SCM_GLOCP(v) && !(SCM_GLOC(v)->hidden))) {
781 SCM_APPEND1(h, t, SCM_OBJ(e->key));
782 }
783 }
784 return h;
785 }
786
787 /*----------------------------------------------------------------------
788 * Extending (inheriting) modules
789 */
790
791 /* Module inheritance obeys the same rule as class inheritance,
792 hence we use monotonic merge. */
793 /* NB: ExtendModule alters module's precedence list, and may cause
794 unwanted side effects when used carelessly. */
795
796 ScmObj Scm_ExtendModule(ScmModule *module, ScmObj supers)
797 {
798 if (module->sealed) {
799 Scm_Error("Attempt to extend a sealed module: %S", SCM_OBJ(module));
800 }
801
802 ScmObj seqh = SCM_NIL, seqt = SCM_NIL;
803 ScmObj sp;
804 SCM_FOR_EACH(sp, supers) {
805 if (!SCM_MODULEP(SCM_CAR(sp))) {
806 Scm_Error("non-module object found in the extend syntax: %S",
807 SCM_CAR(sp));
808 }
809 SCM_APPEND1(seqh, seqt, SCM_MODULE(SCM_CAR(sp))->mpl);
810 }
811 SCM_APPEND1(seqh, seqt, supers);
812 module->parents = supers;
813 ScmObj mpl = Scm_MonotonicMerge1(seqh);
814 if (SCM_FALSEP(mpl)) {
815 Scm_Error("can't extend those modules simultaneously because of inconsistent precedence lists: %S", supers);
816 }
817 module->mpl = Scm_Cons(SCM_OBJ(module), mpl);
818 return module->mpl;
819 }
820
821 /*----------------------------------------------------------------------
822 * Module sealing
823 */
824
825 /* NB: In general it is a bad idea to "unseal" module, so we only
826 provide an API to make module sealed. However, unsealing might
827 be useful for debugging. */
828 void Scm_ModuleSeal(ScmModule *module)
829 {
830 module->sealed = TRUE;
831 }
832
833 /*----------------------------------------------------------------------
834 * Module destroying
835 */
836
837 /* Destroying modules isn't a usual operation; it can break existing
838 code if used carelessly. We treat it as an internal API.
839 */
840 void Scm__DestroyModule(ScmModule *m)
841 {
842 if (!SCM_FALSEP(m->name)) {
843 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
844 Scm_HashTableDelete(modules.table, m->name);
845 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
846 }
847 m->imported = SCM_NIL;
848 m->parents = SCM_NIL;
849 m->mpl = SCM_NIL;
850 m->depended = SCM_NIL;
851 Scm_HashCoreClear(&m->internal->core);
852 Scm_HashCoreClear(&m->external->core);
853 m->origin = SCM_FALSE;
854 m->prefix = SCM_FALSE;
855 }
856
857 /*----------------------------------------------------------------------
858 * Finding modules
859 */
860
861 ScmModule *Scm_FindModule(ScmSymbol *name, int flags)
862 {
863 if (flags & SCM_FIND_MODULE_CREATE) {
864 int created;
865 ScmModule *m = lookup_module_create(name, &created);
866 SCM_ASSERT(m != NULL);
867 /* If the module is ever called with CREATE and PLACEHOLDING flag,
868 turn placeholding flag on. The flag is cleared if the module
869 is ever called with CREATE but without PLACEHOLDING. */
870 if (created && (flags & SCM_FIND_MODULE_PLACEHOLDING)) {
871 m->placeholding = TRUE;
872 }
873 if (!(flags & SCM_FIND_MODULE_PLACEHOLDING)) {
874 m->placeholding = FALSE;
875 }
876 return m;
877 } else {
878 ScmModule *m = lookup_module(name);
879 if (m == NULL) {
880 if (!(flags & SCM_FIND_MODULE_QUIET)) {
881 Scm_Error("no such module: %S", name);
882 }
883 return NULL;
884 } else {
885 return m;
886 }
887 }
888 }
889
890 ScmObj Scm_AllModules(void)
891 {
892 ScmObj h = SCM_NIL, t = SCM_NIL;
893 ScmHashIter iter;
894 ScmDictEntry *e;
895
896 (void)SCM_INTERNAL_MUTEX_LOCK(modules.mutex);
897 Scm_HashIterInit(&iter, SCM_HASH_TABLE_CORE(modules.table));
898 while ((e = Scm_HashIterNext(&iter)) != NULL) {
899 ScmModule *m = SCM_MODULE(SCM_DICT_VALUE(e));
900 if (!m->placeholding) {
901 SCM_APPEND1(h, t, SCM_DICT_VALUE(e));
902 }
903 }
904 (void)SCM_INTERNAL_MUTEX_UNLOCK(modules.mutex);
905 return h;
906 }
907
908 void Scm_SelectModule(ScmModule *mod)
909 {
910 SCM_ASSERT(SCM_MODULEP(mod));
911 Scm_VM()->module = mod;
912 }
913
914 /*----------------------------------------------------------------------
915 * Module and pathnames
916 */
917
918 /* Convert module name and pathname (mod load-path) and vice versa.
919 We moved the definition in Scheme. These are just stubs to call them. */
920 ScmObj Scm_ModuleNameToPath(ScmSymbol *name)
921 {
922 static ScmObj module_name_to_path_proc = SCM_UNDEFINED;
923 SCM_BIND_PROC(module_name_to_path_proc, "module-name->path", Scm_GaucheModule());
924 return Scm_ApplyRec1(module_name_to_path_proc, SCM_OBJ(name));
925 }
926
927 ScmObj Scm_PathToModuleName(ScmString *path)
928 {
929 static ScmObj path_to_module_name_proc = SCM_UNDEFINED;
930 SCM_BIND_PROC(path_to_module_name_proc, "path->module-name", Scm_GaucheModule());
931 return Scm_ApplyRec1(path_to_module_name_proc, SCM_OBJ(path));
932 }
933
934 /*----------------------------------------------------------------------
935 * Predefined modules and initialization
936 */
937
938 ScmModule *Scm_NullModule(void)
939 {
940 return &nullModule;
941 }
942
943 ScmModule *Scm_SchemeModule(void)
944 {
945 return &schemeModule;
946 }
947
948 ScmModule *Scm_GaucheModule(void)
949 {
950 return &gaucheModule;
951 }
952
953 ScmModule *Scm_GaucheInternalModule(void)
954 {
955 return &internalModule;
956 }
957
958 ScmModule *Scm_UserModule(void)
959 {
960 return &userModule;
961 }
962
963 ScmModule *Scm__KeywordModule(void) /* internal */
964 {
965 return &keywordModule;
966 }
967
968 ScmModule *Scm__GaucheKeywordModule(void) /* internal */
969 {
970 return &gkeywordModule;
971 }
972
973 ScmModule *Scm__RequireBaseModule(void) /* internal */
974 {
975 return &reqbaseModule;
976 }
977
978 ScmModule *Scm_CurrentModule(void)
979 {
980 return Scm_VM()->module;
981 }
982
983 extern void Scm__InitCurrentRecursiveHash();
984
985 /* NB: we don't need to lock the global module table in initialization */
986 #define INIT_MOD(mod, mname, mpl, inttab) \
987 do { \
988 SCM_SET_CLASS(&mod, SCM_CLASS_MODULE); \
989 init_module(&mod, mname, inttab); \
990 Scm_HashTableSet(modules.table, (mod).name, SCM_OBJ(&mod), 0); \
991 mod.parents = (SCM_NULLP(mpl)? SCM_NIL : SCM_LIST1(SCM_CAR(mpl))); \
992 mpl = mod.mpl = Scm_Cons(SCM_OBJ(&mod), mpl); \
993 } while (0)
994
995 void Scm__InitModule(void)
996 {
997 (void)SCM_INTERNAL_MUTEX_INIT(modules.mutex);
998 modules.table = SCM_HASH_TABLE(Scm_MakeHashTableSimple(SCM_HASH_EQ, 64));
999
1000 /* standard module chain */
1001 ScmObj mpl = SCM_NIL;
1002 INIT_MOD(nullModule, SCM_SYM_NULL, mpl, NULL);
1003 INIT_MOD(schemeModule, SCM_SYM_SCHEME, mpl, NULL);
1004 INIT_MOD(keywordModule, SCM_SYM_KEYWORD, mpl, NULL);
1005 INIT_MOD(gaucheModule, SCM_SYM_GAUCHE, mpl, NULL);
1006 INIT_MOD(gfModule, SCM_SYM_GAUCHE_GF, mpl, NULL);
1007 INIT_MOD(userModule, SCM_SYM_USER, mpl, NULL);
1008
1009 mpl = SCM_CDR(mpl); /* default mpl doesn't include user module */
1010 defaultParents = SCM_LIST1(SCM_CAR(mpl));
1011 defaultMpl = mpl;
1012
1013 /* other modules */
1014 mpl = defaultMpl;
1015 INIT_MOD(internalModule, SCM_SYM_GAUCHE_INTERNAL, mpl, NULL);
1016 INIT_MOD(reqbaseModule, SCM_INTERN("gauche.require-base"), mpl, NULL);
1017 Scm_ModuleSeal(&reqbaseModule);
1018
1019 mpl = keywordModule.mpl;
1020 INIT_MOD(gkeywordModule, SCM_INTERN("gauche.keyword"), mpl,
1021 keywordModule.internal);
1022 gkeywordModule.exportAll = TRUE;
1023
1024 bootstrapModule = Scm_MakeModule(SCM_SYMBOL(SCM_INTERN("gauche.bootstrap")),
1025 FALSE);
1026
1027 /* Bind %current-recursive-hash. It can't be done in Scm__InitHash, for
1028 it needs symbol and module to be initialized. */
1029 Scm__InitCurrentRecursiveHash();
1030 }
1031
1032 void Scm__FinishModuleInitialization(void)
1033 {
1034 #if !GAUCHE_DEBUG_BOOTSTRAP
1035 Scm__DestroyModule(SCM_MODULE(bootstrapModule));
1036 bootstrapModule = SCM_FALSE;
1037 #endif
1038 }