Add `compose', `negate', and `const'.
[bpt/guile.git] / module / ice-9 / boot-9.scm
CommitLineData
87e00370 1;;; -*- mode: scheme; coding: utf-8; -*-
0f2d19dd 2
41131340 3;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010
3d2ada2f 4;;;; Free Software Foundation, Inc.
20edfbbd 5;;;;
73be1d9e
MV
6;;;; This library is free software; you can redistribute it and/or
7;;;; modify it under the terms of the GNU Lesser General Public
8;;;; License as published by the Free Software Foundation; either
53befeb7 9;;;; version 3 of the License, or (at your option) any later version.
73be1d9e
MV
10;;;;
11;;;; This library is distributed in the hope that it will be useful,
0f2d19dd 12;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
73be1d9e
MV
13;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14;;;; Lesser General Public License for more details.
15;;;;
16;;;; You should have received a copy of the GNU Lesser General Public
17;;;; License along with this library; if not, write to the Free Software
92205699 18;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
a482f2cc 19;;;;
3d2ada2f 20
0f2d19dd
JB
21\f
22
20edfbbd
TTN
23;;; Commentary:
24
0f2d19dd
JB
25;;; This file is the first thing loaded into Guile. It adds many mundane
26;;; definitions and a few that are interesting.
27;;;
20edfbbd 28;;; The module system (hence the hierarchical namespace) are defined in this
0f2d19dd
JB
29;;; file.
30;;;
31
20edfbbd
TTN
32;;; Code:
33
0f2d19dd 34\f
9fb41cea 35
9c35c579
AW
36;; Before compiling, make sure any symbols are resolved in the (guile)
37;; module, the primary location of those symbols, rather than in
38;; (guile-user), the default module that we compile in.
39
40(eval-when (compile)
41 (set-current-module (resolve-module '(guile))))
42
416f26c7
AW
43\f
44
45;;; {Error handling}
46;;;
47
48;; Define delimited continuation operators, and implement catch and throw in
49;; terms of them.
50
d648f569
AW
51(define make-prompt-tag
52 (lambda* (#:optional (stem "prompt"))
53 (gensym stem)))
54
c6a32a2c
AW
55(define default-prompt-tag
56 ;; not sure if we should expose this to the user as a fluid
57 (let ((%default-prompt-tag (make-prompt-tag)))
58 (lambda ()
59 %default-prompt-tag)))
8fc43b12
AW
60
61(define (call-with-prompt tag thunk handler)
416f26c7 62 (@prompt tag (thunk) handler))
8fc43b12 63(define (abort-to-prompt tag . args)
416f26c7
AW
64 (@abort tag args))
65
66
416f26c7
AW
67;; Define catch and with-throw-handler, using some common helper routines and a
68;; shared fluid. Hide the helpers in a lexical contour.
69
37620f3f 70(define with-throw-handler #f)
416f26c7
AW
71(let ()
72 ;; Ideally we'd like to be able to give these default values for all threads,
73 ;; even threads not created by Guile; but alack, that does not currently seem
74 ;; possible. So wrap the getters in thunks.
75 (define %running-exception-handlers (make-fluid))
76 (define %exception-handler (make-fluid))
77
78 (define (running-exception-handlers)
79 (or (fluid-ref %running-exception-handlers)
80 (begin
81 (fluid-set! %running-exception-handlers '())
82 '())))
83 (define (exception-handler)
84 (or (fluid-ref %exception-handler)
85 (begin
86 (fluid-set! %exception-handler default-exception-handler)
87 default-exception-handler)))
88
89 (define (default-exception-handler k . args)
90 (cond
91 ((eq? k 'quit)
92 (primitive-exit (cond
93 ((not (pair? args)) 0)
94 ((integer? (car args)) (car args))
95 ((not (car args)) 1)
96 (else 0))))
97 (else
98 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
99 (primitive-exit 1))))
100
101 (define (default-throw-handler prompt-tag catch-k)
102 (let ((prev (exception-handler)))
103 (lambda (thrown-k . args)
104 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
8fc43b12 105 (apply abort-to-prompt prompt-tag thrown-k args)
416f26c7
AW
106 (apply prev thrown-k args)))))
107
108 (define (custom-throw-handler prompt-tag catch-k pre)
109 (let ((prev (exception-handler)))
110 (lambda (thrown-k . args)
111 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
112 (let ((running (running-exception-handlers)))
113 (with-fluids ((%running-exception-handlers (cons pre running)))
114 (if (not (memq pre running))
115 (apply pre thrown-k args))
116 ;; fall through
117 (if prompt-tag
8fc43b12 118 (apply abort-to-prompt prompt-tag thrown-k args)
416f26c7
AW
119 (apply prev thrown-k args))))
120 (apply prev thrown-k args)))))
121
37620f3f
AW
122 (set! catch
123 (lambda* (k thunk handler #:optional pre-unwind-handler)
124 "Invoke @var{thunk} in the dynamic context of @var{handler} for
416f26c7
AW
125exceptions matching @var{key}. If thunk throws to the symbol
126@var{key}, then @var{handler} is invoked this way:
127@lisp
128 (handler key args ...)
129@end lisp
130
131@var{key} is a symbol or @code{#t}.
132
133@var{thunk} takes no arguments. If @var{thunk} returns
134normally, that is the return value of @code{catch}.
135
136Handler is invoked outside the scope of its own @code{catch}.
137If @var{handler} again throws to the same key, a new handler
138from further up the call chain is invoked.
139
140If the key is @code{#t}, then a throw to @emph{any} symbol will
141match this call to @code{catch}.
142
143If a @var{pre-unwind-handler} is given and @var{thunk} throws
144an exception that matches @var{key}, Guile calls the
145@var{pre-unwind-handler} before unwinding the dynamic state and
146invoking the main @var{handler}. @var{pre-unwind-handler} should
147be a procedure with the same signature as @var{handler}, that
148is @code{(lambda (key . args))}. It is typically used to save
149the stack at the point where the exception occurred, but can also
150query other parts of the dynamic state at that point, such as
151fluid values.
152
153A @var{pre-unwind-handler} can exit either normally or non-locally.
154If it exits normally, Guile unwinds the stack and dynamic context
155and then calls the normal (third argument) handler. If it exits
156non-locally, that exit determines the continuation."
37620f3f
AW
157 (if (not (or (symbol? k) (eqv? k #t)))
158 (scm-error "catch" 'wrong-type-arg
159 "Wrong type argument in position ~a: ~a"
160 (list 1 k) (list k)))
161 (let ((tag (make-prompt-tag "catch")))
162 (call-with-prompt
163 tag
164 (lambda ()
165 (with-fluids
166 ((%exception-handler
167 (if pre-unwind-handler
168 (custom-throw-handler tag k pre-unwind-handler)
169 (default-throw-handler tag k))))
170 (thunk)))
171 (lambda (cont k . args)
172 (apply handler k args))))))
173
174 (set! with-throw-handler
175 (lambda (k thunk pre-unwind-handler)
176 "Add @var{handler} to the dynamic context as a throw handler
416f26c7 177for key @var{key}, then invoke @var{thunk}."
37620f3f
AW
178 (if (not (or (symbol? k) (eqv? k #t)))
179 (scm-error "with-throw-handler" 'wrong-type-arg
180 "Wrong type argument in position ~a: ~a"
181 (list 1 k) (list k)))
182 (with-fluids ((%exception-handler
183 (custom-throw-handler #f k pre-unwind-handler)))
184 (thunk))))
185
186 (set! throw
187 (lambda (key . args)
188 "Invoke the catch form matching @var{key}, passing @var{args} to the
416f26c7
AW
189@var{handler}.
190
191@var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
192
193If there is no handler at all, Guile prints an error and then exits."
37620f3f
AW
194 (if (not (symbol? key))
195 ((exception-handler) 'wrong-type-arg "throw"
196 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
197 (apply (exception-handler) key args)))))
416f26c7
AW
198
199
200\f
201
928258fb
AW
202;;; {R4RS compliance}
203;;;
204
205(primitive-load-path "ice-9/r4rs")
206
207\f
208
eb5d1f88
AW
209;;; {Simple Debugging Tools}
210;;;
211
212;; peek takes any number of arguments, writes them to the
213;; current ouput port, and returns the last argument.
214;; It is handy to wrap around an expression to look at
215;; a value each time is evaluated, e.g.:
216;;
9b5a0d84
AW
217;; (+ 10 (troublesome-fn))
218;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
eb5d1f88
AW
219;;
220
221(define (peek . stuff)
222 (newline)
223 (display ";;; ")
224 (write stuff)
225 (newline)
226 (car (last-pair stuff)))
227
228(define pk peek)
229
b7742c6b 230
eb5d1f88
AW
231(define (warn . stuff)
232 (with-output-to-port (current-error-port)
233 (lambda ()
234 (newline)
235 (display ";;; WARNING ")
236 (display stuff)
237 (newline)
238 (car (last-pair stuff)))))
239
240\f
241
21ed9efe 242;;; {Features}
3d2ada2f 243;;;
21ed9efe
MD
244
245(define (provide sym)
246 (if (not (memq sym *features*))
247 (set! *features* (cons sym *features*))))
248
3d2ada2f
DH
249;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
250;; provided? also checks to see if the module is available. We should do that
251;; too, but don't.
252
50706e94
JB
253(define (provided? feature)
254 (and (memq feature *features*) #t))
255
4d248541
AW
256\f
257
9b3cc659
AW
258;;; {Structs}
259;;;
260
261(define (make-struct/no-tail vtable . args)
262 (apply make-struct vtable 0 args))
263
264\f
265
4d248541
AW
266;;; {and-map and or-map}
267;;;
268;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
269;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
270;;;
271
272;; and-map f l
273;;
274;; Apply f to successive elements of l until exhaustion or f returns #f.
275;; If returning early, return #f. Otherwise, return the last value returned
276;; by f. If f has never been called because l is empty, return #t.
277;;
278(define (and-map f lst)
279 (let loop ((result #t)
9b5a0d84 280 (l lst))
4d248541 281 (and result
9b5a0d84
AW
282 (or (and (null? l)
283 result)
284 (loop (f (car l)) (cdr l))))))
4d248541
AW
285
286;; or-map f l
287;;
288;; Apply f to successive elements of l until exhaustion or while f returns #f.
289;; If returning early, return the return value of f.
290;;
291(define (or-map f lst)
292 (let loop ((result #f)
9b5a0d84 293 (l lst))
4d248541 294 (or result
9b5a0d84
AW
295 (and (not (null? l))
296 (loop (f (car l)) (cdr l))))))
4d248541
AW
297
298\f
299
3d2ada2f 300;; let format alias simple-format until the more complete version is loaded
52cfc69b 301
8641dd9e
GB
302(define format simple-format)
303
fdc6aebf
KR
304;; this is scheme wrapping the C code so the final pred call is a tail call,
305;; per SRFI-13 spec
a4c8a02e
AW
306(define string-any
307 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
fdc6aebf 308 (if (and (procedure? char_pred)
9b5a0d84
AW
309 (> end start)
310 (<= end (string-length s))) ;; let c-code handle range error
311 (or (string-any-c-code char_pred s start (1- end))
312 (char_pred (string-ref s (1- end))))
313 (string-any-c-code char_pred s start end))))
fdc6aebf
KR
314
315;; this is scheme wrapping the C code so the final pred call is a tail call,
316;; per SRFI-13 spec
a4c8a02e
AW
317(define string-every
318 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
fdc6aebf 319 (if (and (procedure? char_pred)
9b5a0d84
AW
320 (> end start)
321 (<= end (string-length s))) ;; let c-code handle range error
322 (and (string-every-c-code char_pred s start (1- end))
323 (char_pred (string-ref s (1- end))))
324 (string-every-c-code char_pred s start end))))
fdc6aebf 325
1b05b324
MV
326;; A variant of string-fill! that we keep for compatability
327;;
328(define (substring-fill! str start end fill)
329 (string-fill! str fill start end))
330
21ed9efe 331\f
79451588 332
12eae603
AW
333;; Define a minimal stub of the module API for psyntax, before modules
334;; have booted.
efa6f9d9 335(define (module-name x)
a26934a8 336 '(guile))
3d5f3091
AW
337(define (module-define! module sym val)
338 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
339 (if v
340 (variable-set! v val)
341 (hashq-set! (%get-pre-modules-obarray) sym
342 (make-variable val)))))
343(define (module-ref module sym)
344 (let ((v (module-variable module sym)))
345 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
12eae603
AW
346(define (resolve-module . args)
347 #f)
3d5f3091 348
6a952e0e 349;; API provided by psyntax
e4721dde 350(define syntax-violation #f)
22225fc1
AW
351(define datum->syntax #f)
352(define syntax->datum #f)
750ae8b7 353(define syntax-source #f)
22225fc1
AW
354(define identifier? #f)
355(define generate-temporaries #f)
13182603 356(define bound-identifier=? #f)
13182603 357(define free-identifier=? #f)
5a0132b3 358
8a73a6d2 359;; $sc-dispatch is an implementation detail of psyntax. It is used by
6a952e0e 360;; expanded macros, to dispatch an input against a set of patterns.
5a0132b3
AW
361(define $sc-dispatch #f)
362
6a952e0e 363;; Load it up!
13182603 364(primitive-load-path "ice-9/psyntax-pp")
4f692ace
AW
365;; The binding for `macroexpand' has now been overridden, making psyntax the
366;; expander now.
79451588 367
a1a482e0
AW
368(define-syntax and
369 (syntax-rules ()
370 ((_) #t)
371 ((_ x) x)
372 ((_ x y ...) (if x (and y ...) #f))))
373
374(define-syntax or
375 (syntax-rules ()
376 ((_) #f)
377 ((_ x) x)
378 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
379
dc1eed52
AW
380;; The "maybe-more" bits are something of a hack, so that we can support
381;; SRFI-61. Rewrites into a standalone syntax-case macro would be
382;; appreciated.
a1a482e0 383(define-syntax cond
dc1eed52
AW
384 (syntax-rules (=> else)
385 ((_ "maybe-more" test consequent)
386 (if test consequent))
387
388 ((_ "maybe-more" test consequent clause ...)
389 (if test consequent (cond clause ...)))
390
391 ((_ (else else1 else2 ...))
392 (begin else1 else2 ...))
393
394 ((_ (test => receiver) more-clause ...)
395 (let ((t test))
396 (cond "maybe-more" t (receiver t) more-clause ...)))
397
398 ((_ (generator guard => receiver) more-clause ...)
399 (call-with-values (lambda () generator)
400 (lambda t
401 (cond "maybe-more"
402 (apply guard t) (apply receiver t) more-clause ...))))
403
404 ((_ (test => receiver ...) more-clause ...)
405 (syntax-violation 'cond "wrong number of receiver expressions"
406 '(test => receiver ...)))
407 ((_ (generator guard => receiver ...) more-clause ...)
408 (syntax-violation 'cond "wrong number of receiver expressions"
409 '(generator guard => receiver ...)))
410
411 ((_ (test) more-clause ...)
412 (let ((t test))
413 (cond "maybe-more" t t more-clause ...)))
414
415 ((_ (test body1 body2 ...) more-clause ...)
416 (cond "maybe-more"
417 test (begin body1 body2 ...) more-clause ...))))
a1a482e0
AW
418
419(define-syntax case
420 (syntax-rules (else)
421 ((case (key ...)
422 clauses ...)
423 (let ((atom-key (key ...)))
424 (case atom-key clauses ...)))
425 ((case key
426 (else result1 result2 ...))
427 (begin result1 result2 ...))
428 ((case key
429 ((atoms ...) result1 result2 ...))
430 (if (memv key '(atoms ...))
431 (begin result1 result2 ...)))
432 ((case key
433 ((atoms ...) result1 result2 ...)
434 clause clauses ...)
435 (if (memv key '(atoms ...))
436 (begin result1 result2 ...)
437 (case key clause clauses ...)))))
438
439(define-syntax do
440 (syntax-rules ()
441 ((do ((var init step ...) ...)
442 (test expr ...)
443 command ...)
444 (letrec
445 ((loop
446 (lambda (var ...)
447 (if test
448 (begin
449 (if #f #f)
450 expr ...)
451 (begin
452 command
453 ...
454 (loop (do "step" var step ...)
455 ...))))))
456 (loop init ...)))
457 ((do "step" x)
458 x)
459 ((do "step" x y)
460 y)))
461
1eec95f8
AW
462(define-syntax delay
463 (syntax-rules ()
464 ((_ exp) (make-promise (lambda () exp)))))
79451588 465
cb65f76c
AR
466(include-from-path "ice-9/quasisyntax")
467
41147ee7
AW
468(define-syntax current-source-location
469 (lambda (x)
470 (syntax-case x ()
471 ((_)
472 (with-syntax ((s (datum->syntax x (syntax-source x))))
473 #''s)))))
474
475
79451588 476\f
48fdec21 477
3d2ada2f
DH
478;;; {Defmacros}
479;;;
3d2ada2f 480
13182603
AW
481(define-syntax define-macro
482 (lambda (x)
97ce9dbf 483 "Define a defmacro."
13182603 484 (syntax-case x ()
97ce9dbf 485 ((_ (macro . args) doc body1 body ...)
a927454d
AW
486 (string? (syntax->datum #'doc))
487 #'(define-macro macro doc (lambda args body1 body ...)))
97ce9dbf 488 ((_ (macro . args) body ...)
a927454d 489 #'(define-macro macro #f (lambda args body ...)))
97ce9dbf 490 ((_ macro doc transformer)
a927454d
AW
491 (or (string? (syntax->datum #'doc))
492 (not (syntax->datum #'doc)))
493 #'(define-syntax macro
494 (lambda (y)
495 doc
a5e95abe
AW
496 #((macro-type . defmacro)
497 (defmacro-args args))
a927454d
AW
498 (syntax-case y ()
499 ((_ . args)
500 (let ((v (syntax->datum #'args)))
501 (datum->syntax y (apply transformer v)))))))))))
13182603
AW
502
503(define-syntax defmacro
504 (lambda (x)
97ce9dbf 505 "Define a defmacro, with the old lispy defun syntax."
13182603 506 (syntax-case x ()
97ce9dbf 507 ((_ macro args doc body1 body ...)
a927454d
AW
508 (string? (syntax->datum #'doc))
509 #'(define-macro macro doc (lambda args body1 body ...)))
97ce9dbf 510 ((_ macro args body ...)
a927454d 511 #'(define-macro macro #f (lambda args body ...))))))
3d2ada2f
DH
512
513(provide 'defmacro)
48fdec21
MV
514
515\f
516
3d2ada2f
DH
517;;; {Deprecation}
518;;;
3d2ada2f 519
ec0f307e
AW
520(define-syntax begin-deprecated
521 (lambda (x)
522 (syntax-case x ()
523 ((_ form form* ...)
524 (if (include-deprecated-features)
525 #'(begin form form* ...)
526 #'(begin))))))
0f2d19dd
JB
527
528\f
3d2ada2f 529
79451588 530;;; {Trivial Functions}
0f2d19dd 531;;;
79451588 532
6b08d75b 533(define (identity x) x)
18f06db9
LC
534
535(define (compose proc . rest)
536 "Compose PROC with the procedures in REST, such that the last one in
537REST is applied first and PROC last, and return the resulting procedure.
538The given procedures must have compatible arity."
539 (if (null? rest)
540 proc
541 (let ((g (apply compose rest)))
542 (lambda args
543 (call-with-values (lambda () (apply g args)) proc)))))
544
545(define (negate proc)
546 "Return a procedure with the same arity as PROC that returns the `not'
547of PROC's result."
548 (lambda args
549 (not (apply proc args))))
550
551(define (const value)
552 "Return a procedure that accepts any number of arguments and returns
553VALUE."
554 (lambda _
555 value))
556
132e5fac 557(define (and=> value procedure) (and value (procedure value)))
e8ed460e 558(define call/cc call-with-current-continuation)
79451588 559
27ae3651
AW
560(define-syntax false-if-exception
561 (syntax-rules ()
562 ((_ expr)
563 (catch #t
564 (lambda () expr)
565 (lambda (k . args) #f)))))
3d2ada2f
DH
566
567\f
568
569;;; {General Properties}
570;;;
571
02b582ce
AW
572;; Properties are a lispy way to associate random info with random objects.
573;; Traditionally properties are implemented as an alist or a plist actually
574;; pertaining to the object in question.
575;;
576;; These "object properties" have the advantage that they can be associated with
577;; any object, even if the object has no plist. Object properties are good when
578;; you are extending pre-existing objects in unexpected ways. They also present
579;; a pleasing, uniform procedure-with-setter interface. But if you have a data
580;; type that always has properties, it's often still best to store those
581;; properties within the object itself.
3d2ada2f
DH
582
583(define (make-object-property)
584 (let ((prop (primitive-make-property #f)))
585 (make-procedure-with-setter
586 (lambda (obj) (primitive-property-ref prop obj))
587 (lambda (obj val) (primitive-property-set! prop obj val)))))
588
0f2d19dd 589\f
6b08d75b 590
0f2d19dd
JB
591;;; {Symbol Properties}
592;;;
593
02b582ce
AW
594;;; Symbol properties are something you see in old Lisp code. In most current
595;;; Guile code, symbols are not used as a data structure -- they are used as
596;;; keys into other data structures.
597
0f2d19dd
JB
598(define (symbol-property sym prop)
599 (let ((pair (assoc prop (symbol-pref sym))))
600 (and pair (cdr pair))))
601
602(define (set-symbol-property! sym prop val)
603 (let ((pair (assoc prop (symbol-pref sym))))
604 (if pair
9b5a0d84
AW
605 (set-cdr! pair val)
606 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
0f2d19dd
JB
607
608(define (symbol-property-remove! sym prop)
609 (let ((pair (assoc prop (symbol-pref sym))))
610 (if pair
9b5a0d84 611 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
0f2d19dd
JB
612
613\f
1e531c3a 614
0f2d19dd
JB
615;;; {Arrays}
616;;;
617
2042e178
MV
618(define (array-shape a)
619 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
620 (array-dimensions a)))
0f2d19dd
JB
621
622\f
3d2ada2f 623
0f2d19dd
JB
624;;; {Keywords}
625;;;
626
010b159f
AW
627;;; It's much better if you can use lambda* / define*, of course.
628
0f2d19dd
JB
629(define (kw-arg-ref args kw)
630 (let ((rem (member kw args)))
631 (and rem (pair? (cdr rem)) (cadr rem))))
632
633\f
fa7e9274 634
9f9aa47b 635;;; {Structs}
3d2ada2f 636;;;
fa7e9274
MV
637
638(define (struct-layout s)
9f9aa47b 639 (struct-ref (struct-vtable s) vtable-index-layout))
fa7e9274
MV
640
641\f
d7faeb2e 642
0f2d19dd
JB
643;;; {Records}
644;;;
645
fa7e9274
MV
646;; Printing records: by default, records are printed as
647;;
648;; #<type-name field1: val1 field2: val2 ...>
649;;
650;; You can change that by giving a custom printing function to
651;; MAKE-RECORD-TYPE (after the list of field symbols). This function
652;; will be called like
653;;
654;; (<printer> object port)
655;;
656;; It should print OBJECT to PORT.
657
cf8f1a90 658(define (inherit-print-state old-port new-port)
8a30733e
MD
659 (if (get-print-state old-port)
660 (port-with-print-state new-port (get-print-state old-port))
cf8f1a90
MV
661 new-port))
662
e31f22eb 663;; 0: type-name, 1: fields, 2: constructor
20edfbbd 664(define record-type-vtable
e31f22eb
AW
665 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
666 ;; that we need to expose the bare vtable-vtable to Scheme.
667 (make-vtable-vtable "prprpw" 0
9b5a0d84
AW
668 (lambda (s p)
669 (cond ((eq? s record-type-vtable)
670 (display "#<record-type-vtable>" p))
671 (else
672 (display "#<record-type " p)
673 (display (record-type-name s) p)
674 (display ">" p))))))
0f2d19dd
JB
675
676(define (record-type? obj)
677 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
678
b2669c41 679(define* (make-record-type type-name fields #:optional printer)
31ac29b6 680 ;; Pre-generate constructors for nfields < 20.
e31f22eb
AW
681 (define-syntax make-constructor
682 (lambda (x)
683 (define *max-static-argument-count* 20)
684 (define (make-formals n)
685 (let lp ((i 0))
686 (if (< i n)
687 (cons (datum->syntax
688 x
689 (string->symbol
690 (string (integer->char (+ (char->integer #\a) i)))))
691 (lp (1+ i)))
692 '())))
693 (syntax-case x ()
694 ((_ rtd exp) (not (identifier? #'exp))
695 #'(let ((n exp))
696 (make-constructor rtd n)))
697 ((_ rtd nfields)
698 #`(case nfields
699 #,@(let lp ((n 0))
700 (if (< n *max-static-argument-count*)
701 (cons (with-syntax (((formal ...) (make-formals n))
702 (n n))
703 #'((n)
704 (lambda (formal ...)
705 (make-struct rtd 0 formal ...))))
706 (lp (1+ n)))
707 '()))
708 (else
709 (lambda args
710 (if (= (length args) nfields)
711 (apply make-struct rtd 0 args)
712 (scm-error 'wrong-number-of-args
713 (format #f "make-~a" type-name)
714 "Wrong number of arguments" '() #f)))))))))
715
51797cec
AW
716 (define (default-record-printer s p)
717 (display "#<" p)
718 (display (record-type-name (record-type-descriptor s)) p)
719 (let loop ((fields (record-type-fields (record-type-descriptor s)))
720 (off 0))
721 (cond
722 ((not (null? fields))
723 (display " " p)
724 (display (car fields) p)
725 (display ": " p)
726 (display (struct-ref s off) p)
727 (loop (cdr fields) (+ 1 off)))))
728 (display ">" p))
729
e31f22eb
AW
730 (let ((rtd (make-struct record-type-vtable 0
731 (make-struct-layout
732 (apply string-append
733 (map (lambda (f) "pw") fields)))
b2669c41 734 (or printer default-record-printer)
e31f22eb
AW
735 type-name
736 (copy-tree fields))))
737 (struct-set! rtd (+ vtable-offset-user 2)
738 (make-constructor rtd (length fields)))
51797cec
AW
739 ;; Temporary solution: Associate a name to the record type descriptor
740 ;; so that the object system can create a wrapper class for it.
e31f22eb
AW
741 (set-struct-vtable-name! rtd (if (symbol? type-name)
742 type-name
743 (string->symbol type-name)))
744 rtd))
0f2d19dd
JB
745
746(define (record-type-name obj)
747 (if (record-type? obj)
9f9aa47b 748 (struct-ref obj vtable-offset-user)
0f2d19dd
JB
749 (error 'not-a-record-type obj)))
750
751(define (record-type-fields obj)
752 (if (record-type? obj)
9f9aa47b 753 (struct-ref obj (+ 1 vtable-offset-user))
0f2d19dd
JB
754 (error 'not-a-record-type obj)))
755
d44a0d12
AW
756(define* (record-constructor rtd #:optional field-names)
757 (if (not field-names)
e31f22eb 758 (struct-ref rtd (+ 2 vtable-offset-user))
d44a0d12
AW
759 (primitive-eval
760 `(lambda ,field-names
761 (make-struct ',rtd 0 ,@(map (lambda (f)
762 (if (memq f field-names)
763 f
764 #f))
765 (record-type-fields rtd)))))))
3bf27608 766
0f2d19dd
JB
767(define (record-predicate rtd)
768 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
769
3ba9acb1 770(define (%record-type-error rtd obj) ;; private helper
afc4ccd4
KR
771 (or (eq? rtd (record-type-descriptor obj))
772 (scm-error 'wrong-type-arg "%record-type-check"
9b5a0d84
AW
773 "Wrong type record (want `~S'): ~S"
774 (list (record-type-name rtd) obj)
775 #f)))
afc4ccd4 776
0f2d19dd 777(define (record-accessor rtd field-name)
3bf27608 778 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 779 (if (not pos)
9b5a0d84 780 (error 'no-such-field field-name))
3bf27608
AW
781 (lambda (obj)
782 (if (eq? (struct-vtable obj) rtd)
783 (struct-ref obj pos)
784 (%record-type-error rtd obj)))))
0f2d19dd
JB
785
786(define (record-modifier rtd field-name)
3bf27608 787 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 788 (if (not pos)
9b5a0d84 789 (error 'no-such-field field-name))
3bf27608
AW
790 (lambda (obj val)
791 (if (eq? (struct-vtable obj) rtd)
792 (struct-set! obj pos val)
793 (%record-type-error rtd obj)))))
0f2d19dd
JB
794
795(define (record? obj)
796 (and (struct? obj) (record-type? (struct-vtable obj))))
797
798(define (record-type-descriptor obj)
799 (if (struct? obj)
800 (struct-vtable obj)
801 (error 'not-a-record obj)))
802
21ed9efe
MD
803(provide 'record)
804
0f2d19dd 805\f
3d2ada2f 806
0f2d19dd
JB
807;;; {Booleans}
808;;;
809
810(define (->bool x) (not (not x)))
811
812\f
3d2ada2f 813
0f2d19dd
JB
814;;; {Symbols}
815;;;
816
817(define (symbol-append . args)
06f0414c 818 (string->symbol (apply string-append (map symbol->string args))))
0f2d19dd
JB
819
820(define (list->symbol . args)
821 (string->symbol (apply list->string args)))
822
823(define (symbol . args)
824 (string->symbol (apply string args)))
825
0f2d19dd 826\f
3d2ada2f 827
0f2d19dd
JB
828;;; {Lists}
829;;;
830
831(define (list-index l k)
832 (let loop ((n 0)
9b5a0d84 833 (l l))
0f2d19dd 834 (and (not (null? l))
9b5a0d84
AW
835 (if (eq? (car l) k)
836 n
837 (loop (+ n 1) (cdr l))))))
0f2d19dd 838
1729d8ff 839\f
3d2ada2f 840
52cfc69b 841(if (provided? 'posix)
1e6ebf54 842 (primitive-load-path "ice-9/posix"))
6fa8995c 843
52cfc69b 844(if (provided? 'socket)
1e6ebf54 845 (primitive-load-path "ice-9/networking"))
3afb28ce 846
f3197274 847;; For reference, Emacs file-exists-p uses stat in this same way.
6fa8995c 848(define file-exists?
52cfc69b 849 (if (provided? 'posix)
6fa8995c 850 (lambda (str)
9b5a0d84 851 (->bool (stat str #f)))
6fa8995c 852 (lambda (str)
9b5a0d84
AW
853 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
854 (lambda args #f))))
855 (if port (begin (close-port port) #t)
856 #f)))))
6fa8995c
GH
857
858(define file-is-directory?
52cfc69b 859 (if (provided? 'posix)
6fa8995c 860 (lambda (str)
9b5a0d84 861 (eq? (stat:type (stat str)) 'directory))
6fa8995c 862 (lambda (str)
9b5a0d84
AW
863 (let ((port (catch 'system-error
864 (lambda () (open-file (string-append str "/.")
865 OPEN_READ))
866 (lambda args #f))))
867 (if port (begin (close-port port) #t)
868 #f)))))
0f2d19dd 869
019ac1c9
MV
870(define (system-error-errno args)
871 (if (eq? (car args) 'system-error)
872 (car (list-ref args 4))
873 #f))
874
0f2d19dd 875\f
3d2ada2f 876
0f2d19dd
JB
877;;; {Error Handling}
878;;;
879
4eeaf67c
AW
880(define error
881 (case-lambda
882 (()
4eeaf67c
AW
883 (scm-error 'misc-error #f "?" #f #f))
884 ((message . args)
4eeaf67c
AW
885 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
886 (scm-error 'misc-error #f msg (cons message args) #f)))))
be2d2c70 887
0f2d19dd 888\f
bce074ee 889
b38507c1
AW
890;;; {Time Structures}
891;;;
892
708bf0f3
GH
893(define (tm:sec obj) (vector-ref obj 0))
894(define (tm:min obj) (vector-ref obj 1))
895(define (tm:hour obj) (vector-ref obj 2))
896(define (tm:mday obj) (vector-ref obj 3))
897(define (tm:mon obj) (vector-ref obj 4))
898(define (tm:year obj) (vector-ref obj 5))
899(define (tm:wday obj) (vector-ref obj 6))
900(define (tm:yday obj) (vector-ref obj 7))
901(define (tm:isdst obj) (vector-ref obj 8))
902(define (tm:gmtoff obj) (vector-ref obj 9))
903(define (tm:zone obj) (vector-ref obj 10))
904
905(define (set-tm:sec obj val) (vector-set! obj 0 val))
906(define (set-tm:min obj val) (vector-set! obj 1 val))
907(define (set-tm:hour obj val) (vector-set! obj 2 val))
908(define (set-tm:mday obj val) (vector-set! obj 3 val))
909(define (set-tm:mon obj val) (vector-set! obj 4 val))
910(define (set-tm:year obj val) (vector-set! obj 5 val))
911(define (set-tm:wday obj val) (vector-set! obj 6 val))
912(define (set-tm:yday obj val) (vector-set! obj 7 val))
913(define (set-tm:isdst obj val) (vector-set! obj 8 val))
914(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
915(define (set-tm:zone obj val) (vector-set! obj 10 val))
916
6afcd3b2
GH
917(define (tms:clock obj) (vector-ref obj 0))
918(define (tms:utime obj) (vector-ref obj 1))
919(define (tms:stime obj) (vector-ref obj 2))
920(define (tms:cutime obj) (vector-ref obj 3))
921(define (tms:cstime obj) (vector-ref obj 4))
922
b38507c1
AW
923\f
924
925;;; {File Descriptors and Ports}
926;;;
927
1334c61a 928(define file-position ftell)
52c9a338
AW
929(define* (file-set-position port offset #:optional (whence SEEK_SET))
930 (seek port offset whence))
8b13c6b3 931
e38303a2
GH
932(define (move->fdes fd/port fd)
933 (cond ((integer? fd/port)
9b5a0d84
AW
934 (dup->fdes fd/port fd)
935 (close fd/port)
936 fd)
937 (else
938 (primitive-move->fdes fd/port fd)
939 (set-port-revealed! fd/port 1)
940 fd/port)))
8b13c6b3
GH
941
942(define (release-port-handle port)
943 (let ((revealed (port-revealed port)))
944 (if (> revealed 0)
9b5a0d84 945 (set-port-revealed! port (- revealed 1)))))
0f2d19dd 946
02851b26
AW
947(define dup->port
948 (case-lambda
949 ((port/fd mode)
950 (fdopen (dup->fdes port/fd) mode))
951 ((port/fd mode new-fd)
952 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
953 (set-port-revealed! port 1)
954 port))))
955
956(define dup->inport
957 (case-lambda
958 ((port/fd)
959 (dup->port port/fd "r"))
960 ((port/fd new-fd)
961 (dup->port port/fd "r" new-fd))))
962
963(define dup->outport
964 (case-lambda
965 ((port/fd)
966 (dup->port port/fd "w"))
967 ((port/fd new-fd)
968 (dup->port port/fd "w" new-fd))))
969
970(define dup
971 (case-lambda
972 ((port/fd)
973 (if (integer? port/fd)
974 (dup->fdes port/fd)
975 (dup->port port/fd (port-mode port/fd))))
976 ((port/fd new-fd)
977 (if (integer? port/fd)
978 (dup->fdes port/fd new-fd)
979 (dup->port port/fd (port-mode port/fd) new-fd)))))
e38303a2
GH
980
981(define (duplicate-port port modes)
982 (dup->port port modes))
983
984(define (fdes->inport fdes)
985 (let loop ((rest-ports (fdes->ports fdes)))
986 (cond ((null? rest-ports)
9b5a0d84
AW
987 (let ((result (fdopen fdes "r")))
988 (set-port-revealed! result 1)
989 result))
990 ((input-port? (car rest-ports))
991 (set-port-revealed! (car rest-ports)
992 (+ (port-revealed (car rest-ports)) 1))
993 (car rest-ports))
994 (else
995 (loop (cdr rest-ports))))))
e38303a2
GH
996
997(define (fdes->outport fdes)
998 (let loop ((rest-ports (fdes->ports fdes)))
999 (cond ((null? rest-ports)
9b5a0d84
AW
1000 (let ((result (fdopen fdes "w")))
1001 (set-port-revealed! result 1)
1002 result))
1003 ((output-port? (car rest-ports))
1004 (set-port-revealed! (car rest-ports)
1005 (+ (port-revealed (car rest-ports)) 1))
1006 (car rest-ports))
1007 (else
1008 (loop (cdr rest-ports))))))
e38303a2
GH
1009
1010(define (port->fdes port)
1011 (set-port-revealed! port (+ (port-revealed port) 1))
1012 (fileno port))
1013
956055a9
GH
1014(define (setenv name value)
1015 (if value
1016 (putenv (string-append name "=" value))
1017 (putenv name)))
1018
5c1254da
MV
1019(define (unsetenv name)
1020 "Remove the entry for NAME from the environment."
1021 (putenv name))
1022
0f2d19dd 1023\f
3d2ada2f 1024
0f2d19dd
JB
1025;;; {Load Paths}
1026;;;
1027
3cab8392
JB
1028(define (in-vicinity vicinity file)
1029 (let ((tail (let ((len (string-length vicinity)))
9b5a0d84
AW
1030 (if (zero? len)
1031 #f
1032 (string-ref vicinity (- len 1))))))
3cab8392 1033 (string-append vicinity
9b5a0d84
AW
1034 (if (or (not tail)
1035 (eq? tail #\/))
1036 ""
1037 "/")
1038 file)))
02ceadb8 1039
0f2d19dd 1040\f
3d2ada2f 1041
ef00e7f4 1042;;; {Help for scm_shell}
3d2ada2f 1043;;;
ef00e7f4
JB
1044;;; The argument-processing code used by Guile-based shells generates
1045;;; Scheme code based on the argument list. This page contains help
1046;;; functions for the code it generates.
3d2ada2f 1047;;;
ef00e7f4 1048
ef00e7f4
JB
1049(define (command-line) (program-arguments))
1050
5aa7fe69
JB
1051;; This is mostly for the internal use of the code generated by
1052;; scm_compile_shell_switches.
eef6519b 1053
ef00e7f4 1054(define (load-user-init)
1f08acd9 1055 (let* ((home (or (getenv "HOME")
9b5a0d84
AW
1056 (false-if-exception (passwd:dir (getpwuid (getuid))))
1057 "/")) ;; fallback for cygwin etc.
1058 (init-file (in-vicinity home ".guile")))
1f08acd9 1059 (if (file-exists? init-file)
9b5a0d84 1060 (primitive-load init-file))))
ef00e7f4
JB
1061
1062\f
3d2ada2f 1063
107139ea
AW
1064;;; {The interpreter stack}
1065;;;
1066
06dcb9df 1067;; %stacks defined in stacks.c
a6cd3555 1068(define (%start-stack tag thunk)
8fc43b12
AW
1069 (let ((prompt-tag (make-prompt-tag "start-stack")))
1070 (call-with-prompt
1071 prompt-tag
1072 (lambda ()
1073 (with-fluids ((%stacks (acons tag prompt-tag
1074 (or (fluid-ref %stacks) '()))))
1075 (thunk)))
1076 (lambda (k . args)
52738540 1077 (%start-stack tag (lambda () (apply k args)))))))
a6cd3555
AW
1078(define-syntax start-stack
1079 (syntax-rules ()
1080 ((_ tag exp)
1081 (%start-stack tag (lambda () exp)))))
107139ea
AW
1082
1083\f
1084
a06181a2 1085;;; {Loading by paths}
3d2ada2f 1086;;;
a06181a2
JB
1087
1088;;; Load a Scheme source file named NAME, searching for it in the
1089;;; directories listed in %load-path, and applying each of the file
1090;;; name extensions listed in %load-extensions.
1091(define (load-from-path name)
1092 (start-stack 'load-stack
9b5a0d84 1093 (primitive-load-path name)))
0f2d19dd 1094
85e95b47
AW
1095(define %load-verbosely #f)
1096(define (assert-load-verbosity v) (set! %load-verbosely v))
1097
1098(define (%load-announce file)
1099 (if %load-verbosely
1100 (with-output-to-port (current-error-port)
9b5a0d84
AW
1101 (lambda ()
1102 (display ";;; ")
1103 (display "loading ")
1104 (display file)
1105 (newline)
1106 (force-output)))))
85e95b47
AW
1107
1108(set! %load-hook %load-announce)
1109
d6e70467 1110(define* (load name #:optional reader)
1ab3976e
AW
1111 ;; Returns the .go file corresponding to `name'. Does not search load
1112 ;; paths, only the fallback path. If the .go file is missing or out of
1113 ;; date, and autocompilation is enabled, will try autocompilation, just
1114 ;; as primitive-load-path does internally. primitive-load is
1115 ;; unaffected. Returns #f if autocompilation failed or was disabled.
04af4c4c
AW
1116 ;;
1117 ;; NB: Unless we need to compile the file, this function should not cause
1118 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1119 ;; partially duplicates functionality from (system base compile).
1120 (define (compiled-file-name canon-path)
1121 (and %compile-fallback-path
1122 (string-append
1123 %compile-fallback-path
1124 ;; no need for '/' separator here, canon-path is absolute
1125 canon-path
1126 (cond ((or (null? %load-compiled-extensions)
1127 (string-null? (car %load-compiled-extensions)))
1128 (warn "invalid %load-compiled-extensions"
1129 %load-compiled-extensions)
1130 ".go")
1131 (else (car %load-compiled-extensions))))))
1132 (define (fresh-compiled-file-name go-path)
1ab3976e
AW
1133 (catch #t
1134 (lambda ()
04af4c4c 1135 (let* ((scmstat (stat name))
abca59fe
LC
1136 (gostat (stat go-path #f)))
1137 (if (and gostat
1138 (or (> (stat:mtime gostat) (stat:mtime scmstat))
1139 (and (= (stat:mtime gostat) (stat:mtime scmstat))
1140 (>= (stat:mtimensec gostat)
1141 (stat:mtimensec scmstat)))))
04af4c4c 1142 go-path
1ab3976e
AW
1143 (begin
1144 (if gostat
1145 (format (current-error-port)
1146 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
04af4c4c 1147 name go-path))
1ab3976e
AW
1148 (cond
1149 (%load-should-autocompile
1150 (%warn-autocompilation-enabled)
1151 (format (current-error-port) ";;; compiling ~a\n" name)
02fcbf78
AW
1152 ;; This use of @ is (ironically?) boot-safe, as modules have
1153 ;; not been booted yet, so the resolve-module call in psyntax
1154 ;; doesn't try to load a module, and compile-file will be
1155 ;; treated as a function, not a macro.
1ab3976e
AW
1156 (let ((cfn ((@ (system base compile) compile-file) name
1157 #:env (current-module))))
1158 (format (current-error-port) ";;; compiled ~a\n" cfn)
1159 cfn))
1160 (else #f))))))
1161 (lambda (k . args)
1162 (format (current-error-port)
1163 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1164 name k args)
1165 #f)))
d6e70467 1166 (with-fluids ((current-reader reader))
eddd16d7
AW
1167 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1168 compiled-file-name)
1169 fresh-compiled-file-name)))
1170 (if cfn
1171 (load-compiled cfn)
1172 (start-stack 'load-stack
1173 (primitive-load name))))))
5552355a 1174
0f2d19dd 1175\f
3d2ada2f 1176
0f2d19dd
JB
1177;;; {Reader Extensions}
1178;;;
0f2d19dd
JB
1179;;; Reader code for various "#c" forms.
1180;;;
1181
600c9584
RB
1182(define read-eval? (make-fluid))
1183(fluid-set! read-eval? #f)
1184(read-hash-extend #\.
1185 (lambda (c port)
1186 (if (fluid-ref read-eval?)
1187 (eval (read port) (interaction-environment))
1188 (error
71335c0d 1189 "#. read expansion found and read-eval? is #f."))))
75a97b92 1190
0f2d19dd 1191\f
3d2ada2f 1192
0f2d19dd
JB
1193;;; {Low Level Modules}
1194;;;
1195;;; These are the low level data structures for modules.
1196;;;
37f5dfe5
DH
1197;;; Every module object is of the type 'module-type', which is a record
1198;;; consisting of the following members:
1199;;;
1200;;; - eval-closure: the function that defines for its module the strategy that
1201;;; shall be followed when looking up symbols in the module.
1202;;;
1203;;; An eval-closure is a function taking two arguments: the symbol to be
1204;;; looked up and a boolean value telling whether a binding for the symbol
1205;;; should be created if it does not exist yet. If the symbol lookup
1206;;; succeeded (either because an existing binding was found or because a new
1207;;; binding was created), a variable object representing the binding is
1208;;; returned. Otherwise, the value #f is returned. Note that the eval
1209;;; closure does not take the module to be searched as an argument: During
1210;;; construction of the eval-closure, the eval-closure has to store the
1211;;; module it belongs to in its environment. This means, that any
1212;;; eval-closure can belong to only one module.
1213;;;
1214;;; The eval-closure of a module can be defined arbitrarily. However, three
1215;;; special cases of eval-closures are to be distinguished: During startup
1216;;; the module system is not yet activated. In this phase, no modules are
1217;;; defined and all bindings are automatically stored by the system in the
1218;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1219;;; functions which require an eval-closure as their argument need to be
1220;;; passed the value #f.
1221;;;
1222;;; The other two special cases of eval-closures are the
1223;;; standard-eval-closure and the standard-interface-eval-closure. Both
1224;;; behave equally for the case that no new binding is to be created. The
1225;;; difference between the two comes in, when the boolean argument to the
1226;;; eval-closure indicates that a new binding shall be created if it is not
1227;;; found.
1228;;;
1229;;; Given that no new binding shall be created, both standard eval-closures
1230;;; define the following standard strategy of searching bindings in the
1231;;; module: First, the module's obarray is searched for the symbol. Second,
1232;;; if no binding for the symbol was found in the module's obarray, the
1233;;; module's binder procedure is exececuted. If this procedure did not
1234;;; return a binding for the symbol, the modules referenced in the module's
1235;;; uses list are recursively searched for a binding of the symbol. If the
1236;;; binding can not be found in these modules also, the symbol lookup has
1237;;; failed.
1238;;;
1239;;; If a new binding shall be created, the standard-interface-eval-closure
1240;;; immediately returns indicating failure. That is, it does not even try
1241;;; to look up the symbol. In contrast, the standard-eval-closure would
1242;;; first search the obarray, and if no binding was found there, would
1243;;; create a new binding in the obarray, therefore not calling the binder
1244;;; procedure or searching the modules in the uses list.
1245;;;
1246;;; The explanation of the following members obarray, binder and uses
1247;;; assumes that the symbol lookup follows the strategy that is defined in
1248;;; the standard-eval-closure and the standard-interface-eval-closure.
1249;;;
1250;;; - obarray: a hash table that maps symbols to variable objects. In this
1251;;; hash table, the definitions are found that are local to the module (that
1252;;; is, not imported from other modules). When looking up bindings in the
1253;;; module, this hash table is searched first.
1254;;;
1255;;; - binder: either #f or a function taking a module and a symbol argument.
1256;;; If it is a function it is called after the obarray has been
1257;;; unsuccessfully searched for a binding. It then can provide bindings
1258;;; that would otherwise not be found locally in the module.
1259;;;
1260;;; - uses: a list of modules from which non-local bindings can be inherited.
1261;;; These modules are the third place queried for bindings after the obarray
1262;;; has been unsuccessfully searched and the binder function did not deliver
1263;;; a result either.
1264;;;
1265;;; - transformer: either #f or a function taking a scheme expression as
1266;;; delivered by read. If it is a function, it will be called to perform
1267;;; syntax transformations (e. g. makro expansion) on the given scheme
1268;;; expression. The output of the transformer function will then be passed
1269;;; to Guile's internal memoizer. This means that the output must be valid
1270;;; scheme code. The only exception is, that the output may make use of the
1271;;; syntax extensions provided to identify the modules that a binding
1272;;; belongs to.
1273;;;
1274;;; - name: the name of the module. This is used for all kinds of printing
1275;;; outputs. In certain places the module name also serves as a way of
1276;;; identification. When adding a module to the uses list of another
1277;;; module, it is made sure that the new uses list will not contain two
1278;;; modules of the same name.
1279;;;
1280;;; - kind: classification of the kind of module. The value is (currently?)
1281;;; only used for printing. It has no influence on how a module is treated.
1282;;; Currently the following values are used when setting the module kind:
1283;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1284;;; is set, it defaults to 'module.
1285;;;
608860a5
LC
1286;;; - duplicates-handlers: a list of procedures that get called to make a
1287;;; choice between two duplicate bindings when name clashes occur. See the
1288;;; `duplicate-handlers' global variable below.
37f5dfe5 1289;;;
608860a5
LC
1290;;; - observers: a list of procedures that get called when the module is
1291;;; modified.
37f5dfe5 1292;;;
608860a5
LC
1293;;; - weak-observers: a weak-key hash table of procedures that get called
1294;;; when the module is modified. See `module-observe-weak' for details.
37f5dfe5
DH
1295;;;
1296;;; In addition, the module may (must?) contain a binding for
608860a5
LC
1297;;; `%module-public-interface'. This variable should be bound to a module
1298;;; representing the exported interface of a module. See the
1299;;; `module-public-interface' and `module-export!' procedures.
37f5dfe5 1300;;;
0f2d19dd
JB
1301;;; !!! warning: The interface to lazy binder procedures is going
1302;;; to be changed in an incompatible way to permit all the basic
1303;;; module ops to be virtualized.
1304;;;
1305;;; (make-module size use-list lazy-binding-proc) => module
1306;;; module-{obarray,uses,binder}[|-set!]
1307;;; (module? obj) => [#t|#f]
1308;;; (module-locally-bound? module symbol) => [#t|#f]
1309;;; (module-bound? module symbol) => [#t|#f]
1310;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1311;;; (module-symbol-interned? module symbol) => [#t|#f]
1312;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1313;;; (module-variable module symbol) => [#<variable ...> | #f]
1314;;; (module-symbol-binding module symbol opt-value)
9b5a0d84 1315;;; => [ <obj> | opt-value | an error occurs ]
0f2d19dd
JB
1316;;; (module-make-local-var! module symbol) => #<variable...>
1317;;; (module-add! module symbol var) => unspecified
1318;;; (module-remove! module symbol) => unspecified
1319;;; (module-for-each proc module) => unspecified
1320;;; (make-scm-module) => module ; a lazy copy of the symhash module
1321;;; (set-current-module module) => unspecified
1322;;; (current-module) => #<module...>
1323;;;
1324;;;
1325
1326\f
3d2ada2f 1327
44cf1f0f 1328;;; {Printing Modules}
3d2ada2f
DH
1329;;;
1330
44cf1f0f 1331;; This is how modules are printed. You can re-define it.
31ac29b6 1332(define (%print-module mod port)
0f2d19dd
JB
1333 (display "#<" port)
1334 (display (or (module-kind mod) "module") port)
dc1eed52
AW
1335 (display " " port)
1336 (display (module-name mod) port)
0f2d19dd
JB
1337 (display " " port)
1338 (display (number->string (object-address mod) 16) port)
1339 (display ">" port))
1340
31ac29b6
AW
1341(letrec-syntax
1342 ;; Locally extend the syntax to allow record accessors to be defined at
1343 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1344 ;; the setters, in order to allow for redefinition of the record type; not
1345 ;; relevant in the case of modules, but perhaps if we make this public, it
1346 ;; could matter.
1347
1348 ((define-record-type
1349 (lambda (x)
1350 (define (make-id scope . fragments)
1351 (datum->syntax #'scope
1352 (apply symbol-append
1353 (map (lambda (x)
1354 (if (symbol? x) x (syntax->datum x)))
1355 fragments))))
1356
1357 (define (getter rtd type-name field slot)
1358 #`(define #,(make-id rtd type-name '- field)
1359 (let ((rtd #,rtd))
1360 (lambda (#,type-name)
1361 (if (eq? (struct-vtable #,type-name) rtd)
1362 (struct-ref #,type-name #,slot)
1363 (%record-type-error rtd #,type-name))))))
1364
1365 (define (setter rtd type-name field slot)
1366 #`(define #,(make-id rtd 'set- type-name '- field '!)
1367 (let ((rtd #,rtd))
1368 (lambda (#,type-name val)
1369 (if (eq? (struct-vtable #,type-name) rtd)
1370 (struct-set! #,type-name #,slot val)
1371 (%record-type-error rtd #,type-name))))))
1372
1373 (define (accessors rtd type-name fields n exp)
1374 (syntax-case fields ()
1375 (() exp)
1376 (((field #:no-accessors) field* ...) (identifier? #'field)
1377 (accessors rtd type-name #'(field* ...) (1+ n)
1378 exp))
1379 (((field #:no-setter) field* ...) (identifier? #'field)
1380 (accessors rtd type-name #'(field* ...) (1+ n)
1381 #`(begin #,exp
1382 #,(getter rtd type-name #'field n))))
1383 (((field #:no-getter) field* ...) (identifier? #'field)
1384 (accessors rtd type-name #'(field* ...) (1+ n)
1385 #`(begin #,exp
1386 #,(setter rtd type-name #'field n))))
1387 ((field field* ...) (identifier? #'field)
1388 (accessors rtd type-name #'(field* ...) (1+ n)
1389 #`(begin #,exp
1390 #,(getter rtd type-name #'field n)
1391 #,(setter rtd type-name #'field n))))))
1392
1393 (define (predicate rtd type-name fields exp)
1394 (accessors
1395 rtd type-name fields 0
1396 #`(begin
1397 #,exp
1398 (define (#,(make-id rtd type-name '?) obj)
1399 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1400
1401 (define (field-list fields)
1402 (syntax-case fields ()
1403 (() '())
1404 (((f . opts) . rest) (identifier? #'f)
1405 (cons #'f (field-list #'rest)))
1406 ((f . rest) (identifier? #'f)
1407 (cons #'f (field-list #'rest)))))
1408
1409 (define (constructor rtd type-name fields exp)
1410 (let ((ctor (make-id rtd type-name '-constructor))
1411 (args (field-list fields)))
1412 (predicate rtd type-name fields
1413 #`(begin #,exp
1414 (define #,ctor
1415 (let ((rtd #,rtd))
1416 (lambda #,args
1417 (make-struct rtd 0 #,@args))))
1418 (struct-set! #,rtd (+ vtable-offset-user 2)
1419 #,ctor)))))
1420
1421 (define (type type-name printer fields)
1422 (define (make-layout)
1423 (let lp ((fields fields) (slots '()))
1424 (syntax-case fields ()
1425 (() (datum->syntax #'here
1426 (make-struct-layout
1427 (apply string-append slots))))
1428 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1429
1430 (let ((rtd (make-id type-name type-name '-type)))
1431 (constructor rtd type-name fields
1432 #`(begin
1433 (define #,rtd
1434 (make-struct record-type-vtable 0
1435 '#,(make-layout)
1436 #,printer
1437 '#,type-name
1438 '#,(field-list fields)))
1439 (set-struct-vtable-name! #,rtd '#,type-name)))))
1440
1441 (syntax-case x ()
1442 ((_ type-name printer (field ...))
1443 (type #'type-name #'printer #'(field ...)))))))
1444
1445 ;; module-type
1446 ;;
1447 ;; A module is characterized by an obarray in which local symbols
1448 ;; are interned, a list of modules, "uses", from which non-local
1449 ;; bindings can be inherited, and an optional lazy-binder which
1450 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1451 ;; bindings that would otherwise not be found locally in the module.
1452 ;;
1453 ;; NOTE: If you change the set of fields or their order, you also need to
1454 ;; change the constants in libguile/modules.h.
1455 ;;
1456 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1457 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1458 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
4e48b495 1459 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
31ac29b6
AW
1460 ;;
1461 (define-record-type module
1462 (lambda (obj port) (%print-module obj port))
1463 (obarray
1464 uses
1465 binder
1466 eval-closure
1467 (transformer #:no-getter)
1468 (name #:no-getter)
1469 kind
1470 duplicates-handlers
1471 (import-obarray #:no-setter)
1472 observers
1473 (weak-observers #:no-setter)
f905381d 1474 version
81fc66cf 1475 submodules
4e48b495 1476 submodule-binder
78f79f18
AW
1477 public-interface
1478 filename)))
31ac29b6 1479
0f2d19dd 1480
8b718458 1481;; make-module &opt size uses binder
0f2d19dd 1482;;
8b718458
JB
1483;; Create a new module, perhaps with a particular size of obarray,
1484;; initial uses list, or binding procedure.
0f2d19dd 1485;;
e9729cbb
AW
1486(define* (make-module #:optional (size 31) (uses '()) (binder #f))
1487 (define %default-import-size
1488 ;; Typical number of imported bindings actually used by a module.
1489 600)
1490
1491 (if (not (integer? size))
1492 (error "Illegal size to make-module." size))
1493 (if (not (and (list? uses)
1494 (and-map module? uses)))
1495 (error "Incorrect use list." uses))
1496 (if (and binder (not (procedure? binder)))
1497 (error
1498 "Lazy-binder expected to be a procedure or #f." binder))
1499
1500 (let ((module (module-constructor (make-hash-table size)
1501 uses binder #f macroexpand
1502 #f #f #f
1503 (make-hash-table %default-import-size)
1504 '()
1505 (make-weak-key-hash-table 31) #f
1506 (make-hash-table 7) #f #f #f)))
1507
1508 ;; We can't pass this as an argument to module-constructor,
1509 ;; because we need it to close over a pointer to the module
1510 ;; itself.
1511 (set-module-eval-closure! module (standard-eval-closure module))
1512
1513 module))
0f2d19dd 1514
8b718458 1515
0f2d19dd 1516\f
3d2ada2f 1517
1777c18b
MD
1518;;; {Observer protocol}
1519;;;
1520
1521(define (module-observe module proc)
1522 (set-module-observers! module (cons proc (module-observers module)))
1523 (cons module proc))
1524
723ae5b3 1525(define* (module-observe-weak module observer-id #:optional (proc observer-id))
608860a5
LC
1526 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1527 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1528 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1529 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1530 ;; for instance).
1531
1532 ;; The two-argument version is kept for backward compatibility: when called
1533 ;; with two arguments, the observer gets unregistered when closure PROC
1534 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
723ae5b3 1535 (hashq-set! (module-weak-observers module) observer-id proc))
1777c18b
MD
1536
1537(define (module-unobserve token)
1538 (let ((module (car token))
9b5a0d84 1539 (id (cdr token)))
1777c18b 1540 (if (integer? id)
9b5a0d84
AW
1541 (hash-remove! (module-weak-observers module) id)
1542 (set-module-observers! module (delq1! id (module-observers module)))))
1777c18b
MD
1543 *unspecified*)
1544
d57da08b 1545(define module-defer-observers #f)
03d6cddc 1546(define module-defer-observers-mutex (make-mutex 'recursive))
d57da08b
MD
1547(define module-defer-observers-table (make-hash-table))
1548
1a961d7e 1549(define (module-modified m)
d57da08b
MD
1550 (if module-defer-observers
1551 (hash-set! module-defer-observers-table m #t)
1552 (module-call-observers m)))
1553
1554;;; This function can be used to delay calls to observers so that they
1555;;; can be called once only in the face of massive updating of modules.
1556;;;
1557(define (call-with-deferred-observers thunk)
1558 (dynamic-wind
1559 (lambda ()
9b5a0d84
AW
1560 (lock-mutex module-defer-observers-mutex)
1561 (set! module-defer-observers #t))
d57da08b
MD
1562 thunk
1563 (lambda ()
9b5a0d84
AW
1564 (set! module-defer-observers #f)
1565 (hash-for-each (lambda (m dummy)
1566 (module-call-observers m))
1567 module-defer-observers-table)
1568 (hash-clear! module-defer-observers-table)
1569 (unlock-mutex module-defer-observers-mutex))))
d57da08b
MD
1570
1571(define (module-call-observers m)
1777c18b 1572 (for-each (lambda (proc) (proc m)) (module-observers m))
608860a5
LC
1573
1574 ;; We assume that weak observers don't (un)register themselves as they are
1575 ;; called since this would preclude proper iteration over the hash table
1576 ;; elements.
1577 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1777c18b
MD
1578
1579\f
3d2ada2f 1580
0f2d19dd
JB
1581;;; {Module Searching in General}
1582;;;
1583;;; We sometimes want to look for properties of a symbol
1584;;; just within the obarray of one module. If the property
1585;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1586;;; DISPLAY is locally rebound in the module `safe-guile'.''
1587;;;
1588;;;
1589;;; Other times, we want to test for a symbol property in the obarray
1590;;; of M and, if it is not found there, try each of the modules in the
1591;;; uses list of M. This is the normal way of testing for some
1592;;; property, so we state these properties without qualification as
1593;;; in: ``The symbol 'fnord is interned in module M because it is
1594;;; interned locally in module M2 which is a member of the uses list
1595;;; of M.''
1596;;;
1597
1598;; module-search fn m
20edfbbd 1599;;
0f2d19dd
JB
1600;; return the first non-#f result of FN applied to M and then to
1601;; the modules in the uses of m, and so on recursively. If all applications
1602;; return #f, then so does this function.
1603;;
1604(define (module-search fn m v)
1605 (define (loop pos)
1606 (and (pair? pos)
9b5a0d84
AW
1607 (or (module-search fn (car pos) v)
1608 (loop (cdr pos)))))
0f2d19dd
JB
1609 (or (fn m v)
1610 (loop (module-uses m))))
1611
1612
1613;;; {Is a symbol bound in a module?}
1614;;;
1615;;; Symbol S in Module M is bound if S is interned in M and if the binding
1616;;; of S in M has been set to some well-defined value.
1617;;;
1618
1619;; module-locally-bound? module symbol
1620;;
1621;; Is a symbol bound (interned and defined) locally in a given module?
1622;;
1623(define (module-locally-bound? m v)
1624 (let ((var (module-local-variable m v)))
1625 (and var
9b5a0d84 1626 (variable-bound? var))))
0f2d19dd
JB
1627
1628;; module-bound? module symbol
1629;;
1630;; Is a symbol bound (interned and defined) anywhere in a given module
1631;; or its uses?
1632;;
1633(define (module-bound? m v)
f176c584
AW
1634 (let ((var (module-variable m v)))
1635 (and var
9b5a0d84 1636 (variable-bound? var))))
0f2d19dd
JB
1637
1638;;; {Is a symbol interned in a module?}
1639;;;
20edfbbd 1640;;; Symbol S in Module M is interned if S occurs in
0f2d19dd
JB
1641;;; of S in M has been set to some well-defined value.
1642;;;
1643;;; It is possible to intern a symbol in a module without providing
1644;;; an initial binding for the corresponding variable. This is done
1645;;; with:
1646;;; (module-add! module symbol (make-undefined-variable))
1647;;;
1648;;; In that case, the symbol is interned in the module, but not
1649;;; bound there. The unbound symbol shadows any binding for that
1650;;; symbol that might otherwise be inherited from a member of the uses list.
1651;;;
1652
1653(define (module-obarray-get-handle ob key)
1654 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1655
1656(define (module-obarray-ref ob key)
1657 ((if (symbol? key) hashq-ref hash-ref) ob key))
1658
1659(define (module-obarray-set! ob key val)
1660 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1661
1662(define (module-obarray-remove! ob key)
1663 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1664
1665;; module-symbol-locally-interned? module symbol
20edfbbd 1666;;
0f2d19dd
JB
1667;; is a symbol interned (not neccessarily defined) locally in a given module
1668;; or its uses? Interned symbols shadow inherited bindings even if
1669;; they are not themselves bound to a defined value.
1670;;
1671(define (module-symbol-locally-interned? m v)
1672 (not (not (module-obarray-get-handle (module-obarray m) v))))
1673
1674;; module-symbol-interned? module symbol
20edfbbd 1675;;
0f2d19dd
JB
1676;; is a symbol interned (not neccessarily defined) anywhere in a given module
1677;; or its uses? Interned symbols shadow inherited bindings even if
1678;; they are not themselves bound to a defined value.
1679;;
1680(define (module-symbol-interned? m v)
1681 (module-search module-symbol-locally-interned? m v))
1682
1683
1684;;; {Mapping modules x symbols --> variables}
1685;;;
1686
1687;; module-local-variable module symbol
1688;; return the local variable associated with a MODULE and SYMBOL.
1689;;
1690;;; This function is very important. It is the only function that can
1691;;; return a variable from a module other than the mutators that store
1692;;; new variables in modules. Therefore, this function is the location
1693;;; of the "lazy binder" hack.
1694;;;
1695;;; If symbol is defined in MODULE, and if the definition binds symbol
1696;;; to a variable, return that variable object.
1697;;;
1698;;; If the symbols is not found at first, but the module has a lazy binder,
1699;;; then try the binder.
1700;;;
1701;;; If the symbol is not found at all, return #f.
1702;;;
608860a5
LC
1703;;; (This is now written in C, see `modules.c'.)
1704;;;
0f2d19dd
JB
1705
1706;;; {Mapping modules x symbols --> bindings}
1707;;;
1708;;; These are similar to the mapping to variables, except that the
1709;;; variable is dereferenced.
1710;;;
1711
1712;; module-symbol-binding module symbol opt-value
20edfbbd 1713;;
0f2d19dd
JB
1714;; return the binding of a variable specified by name within
1715;; a given module, signalling an error if the variable is unbound.
1716;; If the OPT-VALUE is passed, then instead of signalling an error,
1717;; return OPT-VALUE.
1718;;
1719(define (module-symbol-local-binding m v . opt-val)
1720 (let ((var (module-local-variable m v)))
7b07e5ef 1721 (if (and var (variable-bound? var))
9b5a0d84
AW
1722 (variable-ref var)
1723 (if (not (null? opt-val))
1724 (car opt-val)
1725 (error "Locally unbound variable." v)))))
0f2d19dd
JB
1726
1727;; module-symbol-binding module symbol opt-value
20edfbbd 1728;;
0f2d19dd
JB
1729;; return the binding of a variable specified by name within
1730;; a given module, signalling an error if the variable is unbound.
1731;; If the OPT-VALUE is passed, then instead of signalling an error,
1732;; return OPT-VALUE.
1733;;
1734(define (module-symbol-binding m v . opt-val)
1735 (let ((var (module-variable m v)))
7b07e5ef 1736 (if (and var (variable-bound? var))
9b5a0d84
AW
1737 (variable-ref var)
1738 (if (not (null? opt-val))
1739 (car opt-val)
1740 (error "Unbound variable." v)))))
0f2d19dd
JB
1741
1742
1743\f
3d2ada2f 1744
0f2d19dd
JB
1745;;; {Adding Variables to Modules}
1746;;;
0f2d19dd
JB
1747
1748;; module-make-local-var! module symbol
20edfbbd 1749;;
0f2d19dd
JB
1750;; ensure a variable for V in the local namespace of M.
1751;; If no variable was already there, then create a new and uninitialzied
1752;; variable.
1753;;
d57da08b
MD
1754;; This function is used in modules.c.
1755;;
0f2d19dd
JB
1756(define (module-make-local-var! m v)
1757 (or (let ((b (module-obarray-ref (module-obarray m) v)))
9b5a0d84
AW
1758 (and (variable? b)
1759 (begin
1760 ;; Mark as modified since this function is called when
1761 ;; the standard eval closure defines a binding
1762 (module-modified m)
1763 b)))
0c5f718b 1764
608860a5
LC
1765 ;; Create a new local variable.
1766 (let ((local-var (make-undefined-variable)))
1767 (module-add! m v local-var)
1768 local-var)))
0f2d19dd 1769
89d06712 1770;; module-ensure-local-variable! module symbol
9540368e 1771;;
89d06712
MV
1772;; Ensure that there is a local variable in MODULE for SYMBOL. If
1773;; there is no binding for SYMBOL, create a new uninitialized
1774;; variable. Return the local variable.
9540368e 1775;;
89d06712
MV
1776(define (module-ensure-local-variable! module symbol)
1777 (or (module-local-variable module symbol)
9540368e 1778 (let ((var (make-undefined-variable)))
9b5a0d84
AW
1779 (module-add! module symbol var)
1780 var)))
9540368e 1781
0f2d19dd 1782;; module-add! module symbol var
20edfbbd 1783;;
0f2d19dd
JB
1784;; ensure a particular variable for V in the local namespace of M.
1785;;
1786(define (module-add! m v var)
1787 (if (not (variable? var))
1788 (error "Bad variable to module-add!" var))
1777c18b 1789 (module-obarray-set! (module-obarray m) v var)
1a961d7e 1790 (module-modified m))
0f2d19dd 1791
20edfbbd
TTN
1792;; module-remove!
1793;;
0f2d19dd
JB
1794;; make sure that a symbol is undefined in the local namespace of M.
1795;;
1796(define (module-remove! m v)
c35738c1 1797 (module-obarray-remove! (module-obarray m) v)
1a961d7e 1798 (module-modified m))
0f2d19dd
JB
1799
1800(define (module-clear! m)
c35738c1 1801 (hash-clear! (module-obarray m))
1a961d7e 1802 (module-modified m))
0f2d19dd
JB
1803
1804;; MODULE-FOR-EACH -- exported
20edfbbd 1805;;
0f2d19dd
JB
1806;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1807;;
1808(define (module-for-each proc module)
c35738c1 1809 (hash-for-each proc (module-obarray module)))
0f2d19dd
JB
1810
1811(define (module-map proc module)
711a9fd7 1812 (hash-map->list proc (module-obarray module)))
c35738c1 1813
0f27ab8a
AW
1814;; Submodules
1815;;
1816;; Modules exist in a separate namespace from values, because you generally do
1817;; not want the name of a submodule, which you might not even use, to collide
1818;; with local variables that happen to be named the same as the submodule.
1819;;
1820(define (module-ref-submodule module name)
81fc66cf
AW
1821 (or (hashq-ref (module-submodules module) name)
1822 (and (module-submodule-binder module)
1823 ((module-submodule-binder module) module name))))
0f27ab8a
AW
1824
1825(define (module-define-submodule! module name submodule)
f6a5308b 1826 (hashq-set! (module-submodules module) name submodule))
0f27ab8a 1827
dcb68c09
AW
1828;; It used to be, however, that module names were also present in the
1829;; value namespace. When we enable deprecated code, we preserve this
1830;; legacy behavior.
1831;;
1832;; These shims are defined here instead of in deprecated.scm because we
1833;; need their definitions before loading other modules.
1834;;
1835(begin-deprecated
1836 (define (module-ref-submodule module name)
1837 (or (hashq-ref (module-submodules module) name)
1838 (and (module-submodule-binder module)
1839 ((module-submodule-binder module) module name))
1840 (let ((var (module-local-variable module name)))
1841 (and var (variable-bound? var) (module? (variable-ref var))
1842 (begin
1843 (warn "module" module "not in submodules table")
1844 (variable-ref var))))))
1845
1846 (define (module-define-submodule! module name submodule)
1847 (let ((var (module-local-variable module name)))
1848 (if (and var
1849 (or (not (variable-bound? var))
1850 (not (module? (variable-ref var)))))
1851 (warn "defining module" module ": not overriding local definition" var)
1852 (module-define! module name submodule)))
1853 (hashq-set! (module-submodules module) name submodule)))
1854
0f2d19dd
JB
1855\f
1856
0f2d19dd
JB
1857;;; {Module-based Loading}
1858;;;
1859
1860(define (save-module-excursion thunk)
1861 (let ((inner-module (current-module))
9b5a0d84 1862 (outer-module #f))
0f2d19dd 1863 (dynamic-wind (lambda ()
9b5a0d84
AW
1864 (set! outer-module (current-module))
1865 (set-current-module inner-module)
1866 (set! inner-module #f))
1867 thunk
1868 (lambda ()
1869 (set! inner-module (current-module))
1870 (set-current-module outer-module)
1871 (set! outer-module #f)))))
0f2d19dd 1872
0f2d19dd
JB
1873(define basic-load load)
1874
5a662124 1875(define* (load-module filename #:optional reader)
c6775c40
MD
1876 (save-module-excursion
1877 (lambda ()
1878 (let ((oldname (and (current-load-port)
9b5a0d84 1879 (port-filename (current-load-port)))))
5a662124
AW
1880 (basic-load (if (and oldname
1881 (> (string-length filename) 0)
1882 (not (char=? (string-ref filename 0) #\/))
1883 (not (string=? (dirname oldname) ".")))
1884 (string-append (dirname oldname) "/" filename)
1885 filename)
1886 reader)))))
0f2d19dd
JB
1887
1888
1889\f
3d2ada2f 1890
44cf1f0f 1891;;; {MODULE-REF -- exported}
3d2ada2f
DH
1892;;;
1893
0f2d19dd
JB
1894;; Returns the value of a variable called NAME in MODULE or any of its
1895;; used modules. If there is no such variable, then if the optional third
1896;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
20edfbbd 1897;;
0f2d19dd
JB
1898(define (module-ref module name . rest)
1899 (let ((variable (module-variable module name)))
1900 (if (and variable (variable-bound? variable))
9b5a0d84
AW
1901 (variable-ref variable)
1902 (if (null? rest)
1903 (error "No variable named" name 'in module)
1904 (car rest) ; default value
1905 ))))
0f2d19dd
JB
1906
1907;; MODULE-SET! -- exported
1908;;
1909;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1910;; to VALUE; if there is no such variable, an error is signaled.
20edfbbd 1911;;
0f2d19dd
JB
1912(define (module-set! module name value)
1913 (let ((variable (module-variable module name)))
1914 (if variable
9b5a0d84
AW
1915 (variable-set! variable value)
1916 (error "No variable named" name 'in module))))
0f2d19dd
JB
1917
1918;; MODULE-DEFINE! -- exported
1919;;
1920;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1921;; variable, it is added first.
20edfbbd 1922;;
0f2d19dd
JB
1923(define (module-define! module name value)
1924 (let ((variable (module-local-variable module name)))
1925 (if variable
9b5a0d84
AW
1926 (begin
1927 (variable-set! variable value)
1928 (module-modified module))
1929 (let ((variable (make-variable value)))
1930 (module-add! module name variable)))))
0f2d19dd 1931
ed218d98
MV
1932;; MODULE-DEFINED? -- exported
1933;;
1934;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1935;; uses)
1936;;
1937(define (module-defined? module name)
1938 (let ((variable (module-variable module name)))
1939 (and variable (variable-bound? variable))))
1940
0f2d19dd
JB
1941;; MODULE-USE! module interface
1942;;
1943;; Add INTERFACE to the list of interfaces used by MODULE.
20edfbbd 1944;;
0f2d19dd 1945(define (module-use! module interface)
b1907902
AW
1946 (if (not (or (eq? module interface)
1947 (memq interface (module-uses module))))
608860a5
LC
1948 (begin
1949 ;; Newly used modules must be appended rather than consed, so that
1950 ;; `module-variable' traverses the use list starting from the first
1951 ;; used module.
1952 (set-module-uses! module
1953 (append (filter (lambda (m)
1954 (not
1955 (equal? (module-name m)
1956 (module-name interface))))
1957 (module-uses module))
1958 (list interface)))
8f44138a 1959 (hash-clear! (module-import-obarray module))
608860a5 1960 (module-modified module))))
0f2d19dd 1961
7b07e5ef
MD
1962;; MODULE-USE-INTERFACES! module interfaces
1963;;
1964;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1965;;
1966(define (module-use-interfaces! module interfaces)
608860a5
LC
1967 (set-module-uses! module
1968 (append (module-uses module) interfaces))
8f44138a 1969 (hash-clear! (module-import-obarray module))
608860a5 1970 (module-modified module))
7b07e5ef 1971
0f2d19dd 1972\f
3d2ada2f 1973
0f2d19dd
JB
1974;;; {Recursive Namespaces}
1975;;;
0f2d19dd 1976;;; A hierarchical namespace emerges if we consider some module to be
b910c4ac 1977;;; root, and submodules of that module to be nested namespaces.
0f2d19dd 1978;;;
b910c4ac 1979;;; The routines here manage variable names in hierarchical namespace.
0f2d19dd
JB
1980;;; Each variable name is a list of elements, looked up in successively nested
1981;;; modules.
1982;;;
9b5a0d84 1983;;; (nested-ref some-root-module '(foo bar baz))
b910c4ac
AW
1984;;; => <value of a variable named baz in the submodule bar of
1985;;; the submodule foo of some-root-module>
0f2d19dd
JB
1986;;;
1987;;;
1988;;; There are:
1989;;;
9b5a0d84
AW
1990;;; ;; a-root is a module
1991;;; ;; name is a list of symbols
0f2d19dd 1992;;;
9b5a0d84
AW
1993;;; nested-ref a-root name
1994;;; nested-set! a-root name val
1995;;; nested-define! a-root name val
1996;;; nested-remove! a-root name
0f2d19dd 1997;;;
b910c4ac
AW
1998;;; These functions manipulate values in namespaces. For referencing the
1999;;; namespaces themselves, use the following:
0f2d19dd 2000;;;
b910c4ac
AW
2001;;; nested-ref-module a-root name
2002;;; nested-define-module! a-root name mod
2003;;;
2004;;; (current-module) is a natural choice for a root so for convenience there are
0f2d19dd
JB
2005;;; also:
2006;;;
b910c4ac
AW
2007;;; local-ref name == nested-ref (current-module) name
2008;;; local-set! name val == nested-set! (current-module) name val
2009;;; local-define name val == nested-define! (current-module) name val
2010;;; local-remove name == nested-remove! (current-module) name
2011;;; local-ref-module name == nested-ref-module (current-module) name
2012;;; local-define-module! name m == nested-define-module! (current-module) name m
0f2d19dd
JB
2013;;;
2014
2015
0dd5491c 2016(define (nested-ref root names)
b910c4ac
AW
2017 (if (null? names)
2018 root
2019 (let loop ((cur root)
2020 (head (car names))
2021 (tail (cdr names)))
2022 (if (null? tail)
2023 (module-ref cur head #f)
2024 (let ((cur (module-ref-submodule cur head)))
2025 (and cur
2026 (loop cur (car tail) (cdr tail))))))))
0f2d19dd 2027
0dd5491c 2028(define (nested-set! root names val)
0f2d19dd 2029 (let loop ((cur root)
b910c4ac
AW
2030 (head (car names))
2031 (tail (cdr names)))
2032 (if (null? tail)
2033 (module-set! cur head val)
2034 (let ((cur (module-ref-submodule cur head)))
2035 (if (not cur)
2036 (error "failed to resolve module" names)
2037 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2038
0dd5491c 2039(define (nested-define! root names val)
0f2d19dd 2040 (let loop ((cur root)
b910c4ac
AW
2041 (head (car names))
2042 (tail (cdr names)))
2043 (if (null? tail)
2044 (module-define! cur head val)
2045 (let ((cur (module-ref-submodule cur head)))
2046 (if (not cur)
2047 (error "failed to resolve module" names)
2048 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2049
0dd5491c 2050(define (nested-remove! root names)
0f2d19dd 2051 (let loop ((cur root)
b910c4ac
AW
2052 (head (car names))
2053 (tail (cdr names)))
2054 (if (null? tail)
2055 (module-remove! cur head)
2056 (let ((cur (module-ref-submodule cur head)))
2057 (if (not cur)
2058 (error "failed to resolve module" names)
2059 (loop cur (car tail) (cdr tail)))))))
2060
2061
2062(define (nested-ref-module root names)
2063 (let loop ((cur root)
2064 (names names))
2065 (if (null? names)
2066 cur
2067 (let ((cur (module-ref-submodule cur (car names))))
2068 (and cur
2069 (loop cur (cdr names)))))))
2070
2071(define (nested-define-module! root names module)
2072 (if (null? names)
2073 (error "can't redefine root module" root module)
2074 (let loop ((cur root)
2075 (head (car names))
2076 (tail (cdr names)))
2077 (if (null? tail)
2078 (module-define-submodule! cur head module)
2079 (let ((cur (or (module-ref-submodule cur head)
2080 (let ((m (make-module 31)))
2081 (set-module-kind! m 'directory)
2082 (set-module-name! m (append (module-name cur)
2083 (list head)))
2084 (module-define-submodule! cur head m)
2085 m))))
2086 (loop cur (car tail) (cdr tail)))))))
2087
0f2d19dd 2088
1623ca68
AW
2089(define (local-ref names)
2090 (nested-ref (current-module) names))
2091
2092(define (local-set! names val)
2093 (nested-set! (current-module) names val))
2094
2095(define (local-define names val)
2096 (nested-define! (current-module) names val))
2097
2098(define (local-remove names)
2099 (nested-remove! (current-module) names))
2100
2101(define (local-ref-module names)
2102 (nested-ref-module (current-module) names))
2103
2104(define (local-define-module names mod)
2105 (nested-define-module! (current-module) names mod))
b910c4ac 2106
0f2d19dd
JB
2107
2108
2109\f
3d2ada2f 2110
cb67c838 2111;;; {The (guile) module}
0f2d19dd 2112;;;
cb67c838
AW
2113;;; The standard module, which has the core Guile bindings. Also called the
2114;;; "root module", as it is imported by many other modules, but it is not
2115;;; necessarily the root of anything; and indeed, the module named '() might be
2116;;; better thought of as a root.
0f2d19dd 2117;;;
bbd1d133 2118
edc185c7
MD
2119(define (set-system-module! m s)
2120 (set-procedure-property! (module-eval-closure m) 'system-module s))
0f2d19dd 2121
76aea207
AW
2122;; The root module uses the pre-modules-obarray as its obarray. This
2123;; special obarray accumulates all bindings that have been established
2124;; before the module system is fully booted.
2125;;
2126;; (The obarray continues to be used by code that has been closed over
2127;; before the module system has been booted.)
2128;;
2129(define the-root-module
2130 (let ((m (make-module 0)))
2131 (set-module-obarray! m (%get-pre-modules-obarray))
2132 (set-module-name! m '(guile))
2133 (set-system-module! m #t)
2134 m))
2135
2136;; The root interface is a module that uses the same obarray as the
2137;; root module. It does not allow new definitions, tho.
2138;;
2139(define the-scm-module
2140 (let ((m (make-module 0)))
2141 (set-module-obarray! m (%get-pre-modules-obarray))
2142 (set-module-eval-closure! m (standard-interface-eval-closure m))
2143 (set-module-name! m '(guile))
2144 (set-module-kind! m 'interface)
2145 (set-system-module! m #t)
2146 m))
2147
2148(set-module-public-interface! the-root-module the-scm-module)
bbd1d133
AW
2149
2150\f
2151
2152;; Now that we have a root module, even though modules aren't fully booted,
2153;; expand the definition of resolve-module.
2154;;
2155(define (resolve-module name . args)
2156 (if (equal? name '(guile))
2157 the-root-module
2158 (error "unexpected module to resolve during module boot" name)))
2159
2160;; Cheat. These bindings are needed by modules.c, but we don't want
2161;; to move their real definition here because that would be unnatural.
2162;;
57ced5b9 2163(define define-module* #f)
bbd1d133
AW
2164(define process-use-modules #f)
2165(define module-export! #f)
2166(define default-duplicate-binding-procedures #f)
2167
2168;; This boots the module system. All bindings needed by modules.c
2169;; must have been defined by now.
296ff5e7 2170;;
bbd1d133
AW
2171(set-current-module the-root-module)
2172
2173
2174\f
2175
2176;; Now that modules are booted, give module-name its final definition.
2177;;
2178(define module-name
2179 (let ((accessor (record-accessor module-type 'name)))
2180 (lambda (mod)
2181 (or (accessor mod)
2182 (let ((name (list (gensym))))
cb67c838
AW
2183 ;; Name MOD and bind it in the module root so that it's visible to
2184 ;; `resolve-module'. This is important as `psyntax' stores module
2185 ;; names and relies on being able to `resolve-module' them.
bbd1d133 2186 (set-module-name! mod name)
9e0bfdba 2187 (nested-define-module! (resolve-module '() #f) name mod)
bbd1d133
AW
2188 (accessor mod))))))
2189
296ff5e7 2190(define (make-modules-in module name)
9e0bfdba
AW
2191 (or (nested-ref-module module name)
2192 (let ((m (make-module 31)))
2193 (set-module-kind! m 'directory)
2194 (set-module-name! m (append (module-name module) name))
2195 (nested-define-module! module name m)
2196 m)))
0f2d19dd 2197
296ff5e7
MV
2198(define (beautify-user-module! module)
2199 (let ((interface (module-public-interface module)))
2200 (if (or (not interface)
9b5a0d84
AW
2201 (eq? interface module))
2202 (let ((interface (make-module 31)))
2203 (set-module-name! interface (module-name module))
dca14012 2204 (set-module-version! interface (module-version module))
9b5a0d84
AW
2205 (set-module-kind! interface 'interface)
2206 (set-module-public-interface! module interface))))
296ff5e7 2207 (if (and (not (memq the-scm-module (module-uses module)))
9b5a0d84 2208 (not (eq? module the-root-module)))
608860a5
LC
2209 ;; Import the default set of bindings (from the SCM module) in MODULE.
2210 (module-use! module the-scm-module)))
432558b9 2211
dca14012 2212(define (version-matches? version-ref target)
dca14012
JG
2213 (define (sub-versions-match? v-refs t)
2214 (define (sub-version-matches? v-ref t)
befd1df9
AW
2215 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2216 (cond
2217 ((number? v-ref) (eqv? v-ref t))
2218 ((list? v-ref)
2219 (case (car v-ref)
2220 ((>=) (>= t (cadr v-ref)))
2221 ((<=) (<= t (cadr v-ref)))
2222 ((and) (and-map matches? (cdr v-ref)))
2223 ((or) (or-map matches? (cdr v-ref)))
2224 ((not) (not (matches? (cadr v-ref))))
2225 (else (error "Invalid sub-version reference" v-ref))))
2226 (else (error "Invalid sub-version reference" v-ref)))))
dca14012
JG
2227 (or (null? v-refs)
2228 (and (not (null? t))
2229 (sub-version-matches? (car v-refs) (car t))
2230 (sub-versions-match? (cdr v-refs) (cdr t)))))
befd1df9
AW
2231
2232 (let ((matches? (lambda (v) (version-matches? v target))))
2233 (or (null? version-ref)
2234 (case (car version-ref)
2235 ((and) (and-map matches? (cdr version-ref)))
2236 ((or) (or-map matches? (cdr version-ref)))
2237 ((not) (not (matches? (cadr version-ref))))
2238 (else (sub-versions-match? version-ref target))))))
dca14012 2239
f95f82f8
AW
2240(define (make-fresh-user-module)
2241 (let ((m (make-module)))
2242 (beautify-user-module! m)
2243 m))
2244
1f60d9d2
MD
2245;; NOTE: This binding is used in libguile/modules.c.
2246;;
53f84bc8 2247(define resolve-module
cb67c838
AW
2248 (let ((root (make-module)))
2249 (set-module-name! root '())
2250 ;; Define the-root-module as '(guile).
d58ccc66 2251 (module-define-submodule! root 'guile the-root-module)
cb67c838 2252
7e314766 2253 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
6b7d701e 2254 (let ((already (nested-ref-module root name)))
cb67c838 2255 (cond
d58ccc66 2256 ((and already
cb67c838
AW
2257 (or (not autoload) (module-public-interface already)))
2258 ;; A hit, a palpable hit.
e44d2e4d 2259 (if (and version
cb67c838
AW
2260 (not (version-matches? version (module-version already))))
2261 (error "incompatible module version already loaded" name))
2262 already)
2263 (autoload
2264 ;; Try to autoload the module, and recurse.
2265 (try-load-module name version)
7e314766 2266 (resolve-module name #f #:ensure ensure))
cb67c838 2267 (else
51b22dbb 2268 ;; No module found (or if one was, it had no public interface), and
7e314766
AW
2269 ;; we're not autoloading. Make an empty module if #:ensure is true.
2270 (or already
2271 (and ensure
2272 (make-modules-in root name)))))))))
cb67c838 2273
296ff5e7 2274
dca14012
JG
2275(define (try-load-module name version)
2276 (try-module-autoload name version))
0f2d19dd 2277
c9b16cee
AW
2278(define (reload-module m)
2279 (let ((f (module-filename m)))
2280 (if f
2281 (save-module-excursion
2282 (lambda ()
2283 ;; Re-set the initial environment, as in try-module-autoload.
2284 (set-current-module (make-fresh-user-module))
2285 (primitive-load-path f)
2286 m))
2287 ;; Though we could guess, we *should* know it.
2288 (error "unknown file name for module" m))))
2289
90847923
MD
2290(define (purify-module! module)
2291 "Removes bindings in MODULE which are inherited from the (guile) module."
2292 (let ((use-list (module-uses module)))
2293 (if (and (pair? use-list)
9b5a0d84
AW
2294 (eq? (car (last-pair use-list)) the-scm-module))
2295 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
90847923 2296
4eecfeb7 2297;; Return a module that is an interface to the module designated by
532cf805
MV
2298;; NAME.
2299;;
c614a00b 2300;; `resolve-interface' takes four keyword arguments:
532cf805
MV
2301;;
2302;; #:select SELECTION
2303;;
2304;; SELECTION is a list of binding-specs to be imported; A binding-spec
2305;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2306;; is the name in the used module and SEEN is the name in the using
2307;; module. Note that SEEN is also passed through RENAMER, below. The
2308;; default is to select all bindings. If you specify no selection but
4eecfeb7 2309;; a renamer, only the bindings that already exist in the used module
532cf805
MV
2310;; are made available in the interface. Bindings that are added later
2311;; are not picked up.
2312;;
c614a00b 2313;; #:hide BINDINGS
532cf805 2314;;
c614a00b 2315;; BINDINGS is a list of bindings which should not be imported.
f595ccfe
MD
2316;;
2317;; #:prefix PREFIX
2318;;
2319;; PREFIX is a symbol that will be appended to each exported name.
2320;; The default is to not perform any renaming.
532cf805 2321;;
c614a00b
MD
2322;; #:renamer RENAMER
2323;;
2324;; RENAMER is a procedure that takes a symbol and returns its new
2325;; name. The default is not perform any renaming.
2326;;
532cf805
MV
2327;; Signal "no code for module" error if module name is not resolvable
2328;; or its public interface is not available. Signal "no binding"
2329;; error if selected binding does not exist in the used module.
2330;;
36d58fc3
AW
2331(define* (resolve-interface name #:key
2332 (select #f)
2333 (hide '())
2334 (prefix #f)
2335 (renamer (if prefix
2336 (symbol-prefix-proc prefix)
2337 identity))
2338 version)
47aabe86 2339 (let* ((module (resolve-module name #t version #:ensure #f))
b622dec7
TTN
2340 (public-i (and module (module-public-interface module))))
2341 (and (or (not module) (not public-i))
2342 (error "no code for module" name))
c614a00b 2343 (if (and (not select) (null? hide) (eq? renamer identity))
b622dec7 2344 public-i
532cf805 2345 (let ((selection (or select (module-map (lambda (sym var) sym)
9b5a0d84 2346 public-i)))
b622dec7 2347 (custom-i (make-module 31)))
c614a00b 2348 (set-module-kind! custom-i 'custom-interface)
9b5a0d84
AW
2349 (set-module-name! custom-i name)
2350 ;; XXX - should use a lazy binder so that changes to the
2351 ;; used module are picked up automatically.
2352 (for-each (lambda (bspec)
2353 (let* ((direct? (symbol? bspec))
2354 (orig (if direct? bspec (car bspec)))
2355 (seen (if direct? bspec (cdr bspec)))
2356 (var (or (module-local-variable public-i orig)
2357 (module-local-variable module orig)
2358 (error
2359 ;; fixme: format manually for now
2360 (simple-format
2361 #f "no binding `~A' in module ~A"
2362 orig name)))))
2363 (if (memq orig hide)
2364 (set! hide (delq! orig hide))
2365 (module-add! custom-i
2366 (renamer seen)
2367 var))))
2368 selection)
2369 ;; Check that we are not hiding bindings which don't exist
2370 (for-each (lambda (binding)
2371 (if (not (module-local-variable public-i binding))
2372 (error
2373 (simple-format
2374 #f "no binding `~A' to hide in module ~A"
2375 binding name))))
2376 hide)
b622dec7 2377 custom-i))))
fb1b76f4
TTN
2378
2379(define (symbol-prefix-proc prefix)
2380 (lambda (symbol)
2381 (symbol-append prefix symbol)))
0f2d19dd 2382
57ced5b9
AW
2383;; This function is called from "modules.c". If you change it, be
2384;; sure to update "modules.c" as well.
2385
f7f62d3a
AW
2386(define* (define-module* name
2387 #:key filename pure version (duplicates '())
2388 (imports '()) (exports '()) (replacements '())
2389 (re-exports '()) (autoloads '()) transformer)
2390 (define (list-of pred l)
2391 (or (null? l)
2392 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2393 (define (valid-export? x)
2394 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2395 (define (valid-autoload? x)
2396 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
2397
2398 (define (resolve-imports imports)
2399 (define (resolve-import import-spec)
2400 (if (list? import-spec)
2401 (apply resolve-interface import-spec)
2402 (error "unexpected use-module specification" import-spec)))
2403 (let lp ((imports imports) (out '()))
2404 (cond
2405 ((null? imports) (reverse! out))
2406 ((pair? imports)
2407 (lp (cdr imports)
2408 (cons (resolve-import (car imports)) out)))
2409 (else (error "unexpected tail of imports list" imports)))))
2410
2411 ;; We could add a #:no-check arg, set by the define-module macro, if
2412 ;; these checks are taking too much time.
2413 ;;
2414 (let ((module (resolve-module name #f)))
2415 (beautify-user-module! module)
2416 (if filename
2417 (set-module-filename! module filename))
2418 (if pure
2419 (purify-module! module))
2420 (if version
2421 (begin
2422 (if (not (list-of integer? version))
2423 (error "expected list of integers for version"))
2424 (set-module-version! module version)
2425 (set-module-version! (module-public-interface module) version)))
2426 (if (pair? duplicates)
2427 (let ((handlers (lookup-duplicates-handlers duplicates)))
2428 (set-module-duplicates-handlers! module handlers)))
2429
2430 (let ((imports (resolve-imports imports)))
2431 (call-with-deferred-observers
2432 (lambda ()
2433 (if (pair? imports)
2434 (module-use-interfaces! module imports))
2435 (if (list-of valid-export? exports)
2436 (if (pair? exports)
2437 (module-export! module exports))
2438 (error "expected exports to be a list of symbols or symbol pairs"))
2439 (if (list-of valid-export? replacements)
2440 (if (pair? replacements)
2441 (module-replace! module replacements))
2442 (error "expected replacements to be a list of symbols or symbol pairs"))
2443 (if (list-of valid-export? re-exports)
2444 (if (pair? re-exports)
2445 (module-re-export! module re-exports))
2446 (error "expected re-exports to be a list of symbols or symbol pairs"))
2447 ;; FIXME
2448 (if (not (null? autoloads))
2449 (apply module-autoload! module autoloads)))))
2450
2451 (if transformer
2452 (if (and (pair? transformer) (list-of symbol? transformer))
2453 (let ((iface (resolve-interface transformer))
2454 (sym (car (last-pair transformer))))
2455 (set-module-transformer! module (module-ref iface sym)))
2456 (error "expected transformer to be a module name" transformer)))
2457
2458 (run-hook module-defined-hook module)
2459 module))
2460
db853761
NJ
2461;; `module-defined-hook' is a hook that is run whenever a new module
2462;; is defined. Its members are called with one argument, the new
2463;; module.
2464(define module-defined-hook (make-hook 1))
2465
3d2ada2f
DH
2466\f
2467
71225060 2468;;; {Autoload}
3d2ada2f 2469;;;
71225060
MD
2470
2471(define (make-autoload-interface module name bindings)
2472 (let ((b (lambda (a sym definep)
9b5a0d84
AW
2473 (and (memq sym bindings)
2474 (let ((i (module-public-interface (resolve-module name))))
2475 (if (not i)
2476 (error "missing interface for module" name))
2477 (let ((autoload (memq a (module-uses module))))
2478 ;; Replace autoload-interface with actual interface if
2479 ;; that has not happened yet.
2480 (if (pair? autoload)
2481 (set-car! autoload i)))
2482 (module-local-variable i sym))))))
608860a5 2483 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
f905381d 2484 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
78f79f18 2485 (make-hash-table 0) #f #f #f)))
608860a5
LC
2486
2487(define (module-autoload! module . args)
2488 "Have @var{module} automatically load the module named @var{name} when one
2489of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2490list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2491module '(ice-9 q) '(make-q q-length))}."
2492 (let loop ((args args))
2493 (cond ((null? args)
2494 #t)
2495 ((null? (cdr args))
2496 (error "invalid name+binding autoload list" args))
2497 (else
2498 (let ((name (car args))
2499 (bindings (cadr args)))
2500 (module-use! module (make-autoload-interface module
2501 name bindings))
2502 (loop (cddr args)))))))
2503
71225060 2504
0f2d19dd 2505\f
3d2ada2f 2506
44cf1f0f 2507;;; {Autoloading modules}
3d2ada2f 2508;;;
0f2d19dd
JB
2509
2510(define autoloads-in-progress '())
2511
482a28f9
MV
2512;; This function is called from "modules.c". If you change it, be
2513;; sure to update "modules.c" as well.
2514
d9113d47 2515(define* (try-module-autoload module-name #:optional version)
0f2d19dd 2516 (let* ((reverse-name (reverse module-name))
9b5a0d84
AW
2517 (name (symbol->string (car reverse-name)))
2518 (dir-hint-module-name (reverse (cdr reverse-name)))
2519 (dir-hint (apply string-append
2520 (map (lambda (elt)
2521 (string-append (symbol->string elt) "/"))
2522 dir-hint-module-name))))
0209ca9a 2523 (resolve-module dir-hint-module-name #f)
0f2d19dd 2524 (and (not (autoload-done-or-in-progress? dir-hint name))
9b5a0d84
AW
2525 (let ((didit #f))
2526 (dynamic-wind
2527 (lambda () (autoload-in-progress! dir-hint name))
2528 (lambda ()
eddd16d7
AW
2529 (with-fluids ((current-reader #f))
2530 (save-module-excursion
2531 (lambda ()
39392995
AW
2532 ;; The initial environment when loading a module is a fresh
2533 ;; user module.
2534 (set-current-module (make-fresh-user-module))
e44d2e4d
AW
2535 ;; Here we could allow some other search strategy (other than
2536 ;; primitive-load-path), for example using versions encoded
2537 ;; into the file system -- but then we would have to figure
2538 ;; out how to locate the compiled file, do autocompilation,
2539 ;; etc. Punt for now, and don't use versions when locating
2540 ;; the file.
2541 (primitive-load-path (in-vicinity dir-hint name) #f)
eddd16d7 2542 (set! didit #t)))))
9b5a0d84
AW
2543 (lambda () (set-autoloaded! dir-hint name didit)))
2544 didit))))
0f2d19dd 2545
71225060 2546\f
3d2ada2f
DH
2547
2548;;; {Dynamic linking of modules}
2549;;;
d0cbd20c 2550
0f2d19dd
JB
2551(define autoloads-done '((guile . guile)))
2552
2553(define (autoload-done-or-in-progress? p m)
2554 (let ((n (cons p m)))
2555 (->bool (or (member n autoloads-done)
9b5a0d84 2556 (member n autoloads-in-progress)))))
0f2d19dd
JB
2557
2558(define (autoload-done! p m)
2559 (let ((n (cons p m)))
2560 (set! autoloads-in-progress
9b5a0d84 2561 (delete! n autoloads-in-progress))
0f2d19dd 2562 (or (member n autoloads-done)
9b5a0d84 2563 (set! autoloads-done (cons n autoloads-done)))))
0f2d19dd
JB
2564
2565(define (autoload-in-progress! p m)
2566 (let ((n (cons p m)))
2567 (set! autoloads-done
9b5a0d84 2568 (delete! n autoloads-done))
0f2d19dd
JB
2569 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2570
2571(define (set-autoloaded! p m done?)
2572 (if done?
2573 (autoload-done! p m)
2574 (let ((n (cons p m)))
9b5a0d84
AW
2575 (set! autoloads-done (delete! n autoloads-done))
2576 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
0f2d19dd 2577
0f2d19dd
JB
2578\f
2579
83b38198 2580;;; {Run-time options}
3d2ada2f 2581;;;
83b38198 2582
122f296d
AW
2583(define-syntax define-option-interface
2584 (syntax-rules ()
2585 ((_ (interface (options enable disable) (option-set!)))
2586 (begin
2587 (define options
2588 (case-lambda
2589 (() (interface))
2590 ((arg)
2591 (if (list? arg)
2592 (begin (interface arg) (interface))
2593 (for-each
2594 (lambda (option)
2595 (apply (lambda (name value documentation)
2596 (display name)
2597 (if (< (string-length (symbol->string name)) 8)
2598 (display #\tab))
2599 (display #\tab)
2600 (display value)
2601 (display #\tab)
2602 (display documentation)
2603 (newline))
2604 option))
2605 (interface #t))))))
2606 (define (enable . flags)
2607 (interface (append flags (interface)))
2608 (interface))
2609 (define (disable . flags)
2610 (let ((options (interface)))
2611 (for-each (lambda (flag) (set! options (delq! flag options)))
2612 flags)
2613 (interface options)
2614 (interface)))
2615 (define-syntax option-set!
2616 (syntax-rules ()
2617 ((_ opt val)
e79caaa6
AW
2618 (eval-when (eval load compile expand)
2619 (options (append (options) (list 'opt val)))))))))))
e9bab9df 2620
e9bab9df
DH
2621(define-option-interface
2622 (debug-options-interface
2623 (debug-options debug-enable debug-disable)
2624 (debug-set!)))
2625
e9bab9df
DH
2626(define-option-interface
2627 (read-options-interface
2628 (read-options read-enable read-disable)
2629 (read-set!)))
2630
2631(define-option-interface
2632 (print-options-interface
2633 (print-options print-enable print-disable)
2634 (print-set!)))
83b38198
MD
2635
2636\f
2637
410e83c0
AW
2638;;; {The Unspecified Value}
2639;;;
2640;;; Currently Guile represents unspecified values via one particular value,
2641;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2642;;; future if we could replace this with a return of 0 values, though.
9346b857 2643;;;
410e83c0
AW
2644
2645(define-syntax *unspecified*
2646 (identifier-syntax (if #f #f)))
2647
2648(define (unspecified? v) (eq? v *unspecified*))
2649
2650
2651\f
2652
0f2d19dd
JB
2653;;; {Running Repls}
2654;;;
2655
652f48c0 2656(define *repl-stack* (make-fluid))
1fdd5bec 2657
9346b857
AW
2658;; Programs can call `batch-mode?' to see if they are running as part of a
2659;; script or if they are running interactively. REPL implementations ensure that
2660;; `batch-mode?' returns #f during their extent.
2661;;
1fdd5bec 2662(define (batch-mode?)
652f48c0 2663 (null? (or (fluid-ref *repl-stack*) '())))
1fdd5bec 2664
9346b857 2665;; Programs can re-enter batch mode, for example after a fork, by calling
0feb833d
AW
2666;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
2667;; to abort to the outermost prompt, and call a thunk there.
1fdd5bec 2668;;
9346b857 2669(define (ensure-batch-mode!)
9d2136ba 2670 (set! batch-mode? (lambda () #t)))
4bbbcd5c 2671
0f2d19dd
JB
2672(define (quit . args)
2673 (apply throw 'quit args))
2674
7950df7c
GH
2675(define exit quit)
2676
0f2d19dd
JB
2677(define (gc-run-time)
2678 (cdr (assq 'gc-time-taken (gc-stats))))
2679
8942e7a1
AW
2680(define abort-hook (make-hook))
2681(define before-error-hook (make-hook))
2682(define after-error-hook (make-hook))
2683(define before-backtrace-hook (make-hook))
2684(define after-backtrace-hook (make-hook))
2685
3e3cec45
MD
2686(define before-read-hook (make-hook))
2687(define after-read-hook (make-hook))
870777d7
KN
2688(define before-eval-hook (make-hook 1))
2689(define after-eval-hook (make-hook 1))
2690(define before-print-hook (make-hook 1))
2691(define after-print-hook (make-hook 1))
1c6cd8e8 2692
c592de96
AW
2693;;; This hook is run at the very end of an interactive session.
2694;;;
2695(define exit-hook (make-hook))
2696
dc5c2038
MD
2697;;; The default repl-reader function. We may override this if we've
2698;;; the readline library.
2699(define repl-reader
17ee350c 2700 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
0becb8f3
AW
2701 (if (not (char-ready?))
2702 (display (if (string? prompt) prompt (prompt))))
dc5c2038 2703 (force-output)
04efd24d 2704 (run-hook before-read-hook)
17ee350c 2705 ((or reader read) (current-input-port))))
dc5c2038 2706
0f2d19dd 2707
0f2d19dd 2708\f
3d2ada2f 2709
44cf1f0f 2710;;; {IOTA functions: generating lists of numbers}
3d2ada2f 2711;;;
0f2d19dd 2712
e69cd299
MD
2713(define (iota n)
2714 (let loop ((count (1- n)) (result '()))
2715 (if (< count 0) result
2716 (loop (1- count) (cons count result)))))
0f2d19dd
JB
2717
2718\f
3d2ada2f 2719
773abfbb
KR
2720;;; {While}
2721;;;
2722;;; with `continue' and `break'.
2723;;;
2724
10e69149
AW
2725;; The inliner will remove the prompts at compile-time if it finds that
2726;; `continue' or `break' are not used.
2727;;
2728(define-syntax while
2729 (lambda (x)
2730 (syntax-case x ()
2731 ((while cond body ...)
2732 #`(let ((break-tag (make-prompt-tag "break"))
2733 (continue-tag (make-prompt-tag "continue")))
2734 (call-with-prompt
2735 break-tag
2736 (lambda ()
2737 (define-syntax #,(datum->syntax #'while 'break)
2738 (lambda (x)
2739 (syntax-case x ()
2740 ((_)
2741 #'(abort-to-prompt break-tag))
2742 ((_ . args)
2743 (syntax-violation 'break "too many arguments" x))
2744 (_
2745 #'(lambda ()
2746 (abort-to-prompt break-tag))))))
2747 (let lp ()
2748 (call-with-prompt
2749 continue-tag
2750 (lambda ()
2751 (define-syntax #,(datum->syntax #'while 'continue)
2752 (lambda (x)
2753 (syntax-case x ()
2754 ((_)
2755 #'(abort-to-prompt continue-tag))
2756 ((_ . args)
2757 (syntax-violation 'continue "too many arguments" x))
2758 (_
2759 #'(lambda args
2760 (apply abort-to-prompt continue-tag args))))))
2761 (do () ((not cond)) body ...))
2762 (lambda (k) (lp)))))
2763 (lambda (k)
2764 #t)))))))
5578a53f 2765
773abfbb 2766
0f2d19dd 2767\f
3d2ada2f 2768
0f2d19dd
JB
2769;;; {Module System Macros}
2770;;;
2771
532cf805
MV
2772;; Return a list of expressions that evaluate to the appropriate
2773;; arguments for resolve-interface according to SPEC.
2774
1fdd5bec
AW
2775(eval-when (compile)
2776 (if (memq 'prefix (read-options))
2777 (error "boot-9 must be compiled with #:kw, not :kw")))
1a1a10d3 2778
532cf805
MV
2779(define (keyword-like-symbol->keyword sym)
2780 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2781
074e036e
AW
2782(define-syntax define-module
2783 (lambda (x)
2784 (define (keyword-like? stx)
2785 (let ((dat (syntax->datum stx)))
2786 (and (symbol? dat)
2787 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2788 (define (->keyword sym)
2789 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2790
cd8c3519 2791 (define (parse-iface args)
074e036e
AW
2792 (let loop ((in args) (out '()))
2793 (syntax-case in ()
2794 (() (reverse! out))
2795 ;; The user wanted #:foo, but wrote :foo. Fix it.
2796 ((sym . in) (keyword-like? #'sym)
2797 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2798 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2799 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2800 ((#:renamer renamer . in)
cd8c3519 2801 (loop #'in (cons* #',renamer #:renamer out)))
074e036e 2802 ((kw val . in)
cd8c3519 2803 (loop #'in (cons* #'val #'kw out))))))
074e036e 2804
cd8c3519 2805 (define (parse args imp exp rex rep aut)
074e036e
AW
2806 ;; Just quote everything except #:use-module and #:use-syntax. We
2807 ;; need to know about all arguments regardless since we want to turn
2808 ;; symbols that look like keywords into real keywords, and the
2809 ;; keyword args in a define-module form are not regular
2810 ;; (i.e. no-backtrace doesn't take a value).
cd8c3519
AW
2811 (syntax-case args ()
2812 (()
2813 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
2814 (exp (if (null? exp) '() #`(#:exports '#,exp)))
2815 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
2816 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
2817 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
2818 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
2819 ;; The user wanted #:foo, but wrote :foo. Fix it.
2820 ((sym . args) (keyword-like? #'sym)
2821 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
2822 imp exp rex rep aut))
2823 ((kw . args) (not (keyword? (syntax->datum #'kw)))
2824 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2825 ((#:no-backtrace . args)
2826 ;; Ignore this one.
2827 (parse #'args imp exp rex rep aut))
2828 ((#:pure . args)
2829 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
2830 ((kw)
2831 (syntax-violation 'define-module "keyword arg without value" x #'kw))
2832 ((#:version (v ...) . args)
2833 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
2834 ((#:duplicates (d ...) . args)
2835 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
2836 ((#:filename f . args)
2837 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
2838 ((#:use-module (name name* ...) . args)
2839 (and (and-map symbol? (syntax->datum #'(name name* ...))))
2840 (parse #'args (cons #'((name name* ...)) imp) exp rex rep aut))
2841 ((#:use-syntax (name name* ...) . args)
2842 (and (and-map symbol? (syntax->datum #'(name name* ...))))
2843 #`(#:transformer '(name name* ...)
2844 . #,(parse #'args (cons #'((name name* ...)) imp) exp rex rep aut)))
2845 ((#:use-module ((name name* ...) arg ...) . args)
2846 (and (and-map symbol? (syntax->datum #'(name name* ...))))
2847 (parse #'args
2848 (cons #`((name name* ...) #,@(parse-iface #'(arg ...))) imp)
2849 exp rex rep aut))
2850 ((#:export (ex ...) . args)
2851 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
2852 ((#:export-syntax (ex ...) . args)
2853 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
2854 ((#:re-export (re ...) . args)
2855 (parse #'args imp exp #`(#,@rex re ...) rep aut))
2856 ((#:re-export-syntax (re ...) . args)
2857 (parse #'args imp exp #`(#,@rex re ...) rep aut))
2858 ((#:replace (r ...) . args)
2859 (parse #'args imp exp rex #`(#,@rep r ...) aut))
2860 ((#:replace-syntax (r ...) . args)
2861 (parse #'args imp exp rex #`(#,@rep r ...) aut))
2862 ((#:autoload name bindings . args)
2863 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
2864 ((kw val . args)
2865 (syntax-violation 'define-module "unknown keyword or bad argument"
2866 #'kw #'val))))
074e036e
AW
2867
2868 (syntax-case x ()
2869 ((_ (name name* ...) arg ...)
cd8c3519
AW
2870 (and-map symbol? (syntax->datum #'(name name* ...)))
2871 (with-syntax (((quoted-arg ...)
2872 (parse #'(arg ...) '() '() '() '() '()))
2873 (filename (assq-ref (or (syntax-source x) '())
2874 'filename)))
d9b1c71a 2875 #'(eval-when (eval load compile expand)
cd8c3519
AW
2876 (let ((m (define-module* '(name name* ...)
2877 #:filename filename quoted-arg ...)))
074e036e
AW
2878 (set-current-module m)
2879 m)))))))
0f2d19dd 2880
532cf805
MV
2881;; The guts of the use-modules macro. Add the interfaces of the named
2882;; modules to the use-list of the current module, in order.
2883
482a28f9
MV
2884;; This function is called by "modules.c". If you change it, be sure
2885;; to change scm_c_use_module as well.
2886
532cf805 2887(define (process-use-modules module-interface-args)
d57da08b 2888 (let ((interfaces (map (lambda (mif-args)
9b5a0d84
AW
2889 (or (apply resolve-interface mif-args)
2890 (error "no such module" mif-args)))
2891 module-interface-args)))
d57da08b
MD
2892 (call-with-deferred-observers
2893 (lambda ()
2894 (module-use-interfaces! (current-module) interfaces)))))
89da9036 2895
4e3328ce
AW
2896(define-syntax use-modules
2897 (lambda (x)
2898 (define (keyword-like? stx)
2899 (let ((dat (syntax->datum stx)))
2900 (and (symbol? dat)
2901 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2902 (define (->keyword sym)
2903 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2904
2905 (define (quotify-iface args)
2906 (let loop ((in args) (out '()))
2907 (syntax-case in ()
2908 (() (reverse! out))
2909 ;; The user wanted #:foo, but wrote :foo. Fix it.
2910 ((sym . in) (keyword-like? #'sym)
2911 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2912 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2913 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2914 ((#:renamer renamer . in)
2915 (loop #'in (cons* #'renamer #:renamer out)))
2916 ((kw val . in)
2917 (loop #'in (cons* #''val #'kw out))))))
2918
2919 (define (quotify specs)
2920 (let lp ((in specs) (out '()))
2921 (syntax-case in ()
2922 (() (reverse out))
2923 (((name name* ...) . in)
2924 (and-map symbol? (syntax->datum #'(name name* ...)))
2925 (lp #'in (cons #''((name name* ...)) out)))
2926 ((((name name* ...) arg ...) . in)
2927 (and-map symbol? (syntax->datum #'(name name* ...)))
2928 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
2929 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
2930 out)))))))
2931
2932 (syntax-case x ()
2933 ((_ spec ...)
2934 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
520caaeb 2935 #'(eval-when (eval load compile expand)
4e3328ce
AW
2936 (process-use-modules (list quoted-args ...))
2937 *unspecified*))))))
2938
2939(define-syntax use-syntax
2940 (syntax-rules ()
2941 ((_ spec ...)
2942 (begin
520caaeb 2943 (eval-when (eval load compile expand)
4e3328ce
AW
2944 (issue-deprecation-warning
2945 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
2946 (use-modules spec ...)))))
0f2d19dd 2947
b1e4c7cc
JG
2948(include-from-path "ice-9/r6rs-libraries")
2949
13182603
AW
2950(define-syntax define-private
2951 (syntax-rules ()
2952 ((_ foo bar)
2953 (define foo bar))))
2954
2955(define-syntax define-public
2956 (syntax-rules ()
2957 ((_ (name . args) . body)
2958 (define-public name (lambda args . body)))
2959 ((_ name val)
2960 (begin
2961 (define name val)
2962 (export name)))))
2963
2964(define-syntax defmacro-public
2965 (syntax-rules ()
2966 ((_ name args . body)
2967 (begin
2968 (defmacro name args . body)
2969 (export-syntax name)))))
0f2d19dd 2970
87e00370
LC
2971;; And now for the most important macro.
2972(define-syntax λ
2973 (syntax-rules ()
2974 ((_ formals body ...)
2975 (lambda formals body ...))))
2976
2977\f
89d06712 2978;; Export a local variable
482a28f9
MV
2979
2980;; This function is called from "modules.c". If you change it, be
2981;; sure to update "modules.c" as well.
2982
90847923
MD
2983(define (module-export! m names)
2984 (let ((public-i (module-public-interface m)))
2985 (for-each (lambda (name)
78c22f5e
JG
2986 (let* ((internal-name (if (pair? name) (car name) name))
2987 (external-name (if (pair? name) (cdr name) name))
2988 (var (module-ensure-local-variable! m internal-name)))
2989 (module-add! public-i external-name var)))
9b5a0d84 2990 names)))
89d06712 2991
f595ccfe
MD
2992(define (module-replace! m names)
2993 (let ((public-i (module-public-interface m)))
2994 (for-each (lambda (name)
78c22f5e
JG
2995 (let* ((internal-name (if (pair? name) (car name) name))
2996 (external-name (if (pair? name) (cdr name) name))
2997 (var (module-ensure-local-variable! m internal-name)))
9b5a0d84 2998 (set-object-property! var 'replace #t)
78c22f5e 2999 (module-add! public-i external-name var)))
9b5a0d84 3000 names)))
f595ccfe 3001
d2b7b761
AW
3002;; Export all local variables from a module
3003;;
3004(define (module-export-all! mod)
3005 (define (fresh-interface!)
3006 (let ((iface (make-module)))
3007 (set-module-name! iface (module-name mod))
e5602ce7 3008 (set-module-version! iface (module-version mod))
d2b7b761
AW
3009 (set-module-kind! iface 'interface)
3010 (set-module-public-interface! mod iface)
3011 iface))
3012 (let ((iface (or (module-public-interface mod)
3013 (fresh-interface!))))
3014 (set-module-obarray! iface (module-obarray mod))))
3015
89d06712
MV
3016;; Re-export a imported variable
3017;;
3018(define (module-re-export! m names)
3019 (let ((public-i (module-public-interface m)))
3020 (for-each (lambda (name)
78c22f5e
JG
3021 (let* ((internal-name (if (pair? name) (car name) name))
3022 (external-name (if (pair? name) (cdr name) name))
3023 (var (module-variable m internal-name)))
9b5a0d84 3024 (cond ((not var)
78c22f5e
JG
3025 (error "Undefined variable:" internal-name))
3026 ((eq? var (module-local-variable m internal-name))
3027 (error "re-exporting local variable:" internal-name))
9b5a0d84 3028 (else
78c22f5e 3029 (module-add! public-i external-name var)))))
9b5a0d84 3030 names)))
90847923 3031
d6151723
AW
3032(define-syntax export
3033 (syntax-rules ()
3034 ((_ name ...)
520caaeb 3035 (eval-when (eval load compile expand)
d6151723
AW
3036 (call-with-deferred-observers
3037 (lambda ()
3038 (module-export! (current-module) '(name ...))))))))
a0cc0a01 3039
d6151723
AW
3040(define-syntax re-export
3041 (syntax-rules ()
3042 ((_ name ...)
520caaeb 3043 (eval-when (eval load compile expand)
d6151723
AW
3044 (call-with-deferred-observers
3045 (lambda ()
3046 (module-re-export! (current-module) '(name ...))))))))
89d06712 3047
1052739b
AW
3048(define-syntax export!
3049 (syntax-rules ()
3050 ((_ name ...)
3051 (eval-when (eval load compile expand)
3052 (call-with-deferred-observers
3053 (lambda ()
3054 (module-replace! (current-module) '(name ...))))))))
3055
d6151723
AW
3056(define-syntax export-syntax
3057 (syntax-rules ()
3058 ((_ name ...)
3059 (export name ...))))
a0cc0a01 3060
d6151723
AW
3061(define-syntax re-export-syntax
3062 (syntax-rules ()
3063 ((_ name ...)
3064 (re-export name ...))))
a0cc0a01 3065
0f2d19dd
JB
3066(define load load-module)
3067
3de80ed5
AW
3068\f
3069
f595ccfe
MD
3070;;; {Parameters}
3071;;;
3072
e9729cbb
AW
3073(define* (make-mutable-parameter init #:optional (converter identity))
3074 (let ((fluid (make-fluid)))
3075 (fluid-set! fluid (converter init))
3076 (case-lambda
3077 (() (fluid-ref fluid))
3078 ((val) (fluid-set! fluid (converter val))))))
3079
f595ccfe
MD
3080
3081\f
3d2ada2f 3082
7b07e5ef
MD
3083;;; {Handling of duplicate imported bindings}
3084;;;
3085
3086;; Duplicate handlers take the following arguments:
3087;;
3088;; module importing module
9b5a0d84
AW
3089;; name conflicting name
3090;; int1 old interface where name occurs
3091;; val1 value of binding in old interface
3092;; int2 new interface where name occurs
3093;; val2 value of binding in new interface
3094;; var previous resolution or #f
3095;; val value of previous resolution
7b07e5ef
MD
3096;;
3097;; A duplicate handler can take three alternative actions:
3098;;
3099;; 1. return #f => leave responsibility to next handler
3100;; 2. exit with an error
3101;; 3. return a variable resolving the conflict
3102;;
3103
3104(define duplicate-handlers
3105 (let ((m (make-module 7)))
f595ccfe
MD
3106
3107 (define (check module name int1 val1 int2 val2 var val)
3108 (scm-error 'misc-error
9b5a0d84
AW
3109 #f
3110 "~A: `~A' imported from both ~A and ~A"
3111 (list (module-name module)
3112 name
3113 (module-name int1)
3114 (module-name int2))
3115 #f))
f595ccfe 3116
65bed4aa 3117 (define (warn module name int1 val1 int2 val2 var val)
d7c0c26d 3118 (format (current-error-port)
9b5a0d84
AW
3119 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3120 (module-name module)
3121 name
3122 (module-name int1)
3123 (module-name int2))
65bed4aa 3124 #f)
f595ccfe
MD
3125
3126 (define (replace module name int1 val1 int2 val2 var val)
3127 (let ((old (or (and var (object-property var 'replace) var)
9b5a0d84
AW
3128 (module-variable int1 name)))
3129 (new (module-variable int2 name)))
3130 (if (object-property old 'replace)
3131 (and (or (eq? old new)
3132 (not (object-property new 'replace)))
3133 old)
3134 (and (object-property new 'replace)
3135 new))))
f595ccfe 3136
65bed4aa
MD
3137 (define (warn-override-core module name int1 val1 int2 val2 var val)
3138 (and (eq? int1 the-scm-module)
9b5a0d84
AW
3139 (begin
3140 (format (current-error-port)
3141 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3142 (module-name module)
3143 (module-name int2)
3144 name)
3145 (module-local-variable int2 name))))
f595ccfe 3146
65bed4aa
MD
3147 (define (first module name int1 val1 int2 val2 var val)
3148 (or var (module-local-variable int1 name)))
f595ccfe 3149
65bed4aa
MD
3150 (define (last module name int1 val1 int2 val2 var val)
3151 (module-local-variable int2 name))
f595ccfe 3152
65bed4aa
MD
3153 (define (noop module name int1 val1 int2 val2 var val)
3154 #f)
3155
7b07e5ef
MD
3156 (set-module-name! m 'duplicate-handlers)
3157 (set-module-kind! m 'interface)
f595ccfe
MD
3158 (module-define! m 'check check)
3159 (module-define! m 'warn warn)
3160 (module-define! m 'replace replace)
3161 (module-define! m 'warn-override-core warn-override-core)
3162 (module-define! m 'first first)
3163 (module-define! m 'last last)
65bed4aa
MD
3164 (module-define! m 'merge-generics noop)
3165 (module-define! m 'merge-accessors noop)
7b07e5ef
MD
3166 m))
3167
f595ccfe 3168(define (lookup-duplicates-handlers handler-names)
109c2c9f
MD
3169 (and handler-names
3170 (map (lambda (handler-name)
9b5a0d84
AW
3171 (or (module-symbol-local-binding
3172 duplicate-handlers handler-name #f)
3173 (error "invalid duplicate handler name:"
3174 handler-name)))
3175 (if (list? handler-names)
3176 handler-names
3177 (list handler-names)))))
f595ccfe 3178
70a459e3
MD
3179(define default-duplicate-binding-procedures
3180 (make-mutable-parameter #f))
3181
3182(define default-duplicate-binding-handler
6496a663 3183 (make-mutable-parameter '(replace warn-override-core warn last)
9b5a0d84
AW
3184 (lambda (handler-names)
3185 (default-duplicate-binding-procedures
3186 (lookup-duplicates-handlers handler-names))
3187 handler-names)))
f595ccfe 3188
7b07e5ef 3189\f
7f24bc58
MG
3190
3191;;; {`cond-expand' for SRFI-0 support.}
3192;;;
3193;;; This syntactic form expands into different commands or
3194;;; definitions, depending on the features provided by the Scheme
3195;;; implementation.
3196;;;
3197;;; Syntax:
3198;;;
3199;;; <cond-expand>
3200;;; --> (cond-expand <cond-expand-clause>+)
3201;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3202;;; <cond-expand-clause>
3203;;; --> (<feature-requirement> <command-or-definition>*)
3204;;; <feature-requirement>
3205;;; --> <feature-identifier>
3206;;; | (and <feature-requirement>*)
3207;;; | (or <feature-requirement>*)
3208;;; | (not <feature-requirement>)
3209;;; <feature-identifier>
3210;;; --> <a symbol which is the name or alias of a SRFI>
3211;;;
3212;;; Additionally, this implementation provides the
3213;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3214;;; determine the implementation type and the supported standard.
3215;;;
3216;;; Currently, the following feature identifiers are supported:
3217;;;
08b609aa 3218;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
7f24bc58
MG
3219;;;
3220;;; Remember to update the features list when adding more SRFIs.
3d2ada2f 3221;;;
7f24bc58 3222
b9b8f9da 3223(define %cond-expand-features
f41be016 3224 ;; Adjust the above comment when changing this.
018733ff 3225 '(guile
60c8ad9e 3226 guile-2
018733ff
KR
3227 r5rs
3228 srfi-0 ;; cond-expand itself
85acb35f 3229 srfi-4 ;; homogenous numeric vectors
018733ff 3230 srfi-6 ;; open-input-string etc, in the guile core
4a276c08
MV
3231 srfi-13 ;; string library
3232 srfi-14 ;; character sets
344d68d5 3233 srfi-55 ;; require-extension
08b609aa 3234 srfi-61 ;; general cond clause
018733ff 3235 ))
1d00af09 3236
b9b8f9da
MG
3237;; This table maps module public interfaces to the list of features.
3238;;
3239(define %cond-expand-table (make-hash-table 31))
3240
3241;; Add one or more features to the `cond-expand' feature list of the
3242;; module `module'.
3243;;
3244(define (cond-expand-provide module features)
3245 (let ((mod (module-public-interface module)))
3246 (and mod
9b5a0d84
AW
3247 (hashq-set! %cond-expand-table mod
3248 (append (hashq-ref %cond-expand-table mod '())
3249 features)))))
b9b8f9da 3250
1fdd5bec
AW
3251(define-syntax cond-expand
3252 (lambda (x)
3253 (define (module-has-feature? mod sym)
3254 (or-map (lambda (mod)
3255 (memq sym (hashq-ref %cond-expand-table mod '())))
3256 (module-uses mod)))
3257
3258 (define (condition-matches? condition)
3259 (syntax-case condition (and or not)
3260 ((and c ...)
3261 (and-map condition-matches? #'(c ...)))
3262 ((or c ...)
3263 (or-map condition-matches? #'(c ...)))
3264 ((not c)
3265 (if (condition-matches? #'c) #f #t))
3266 (c
3267 (identifier? #'c)
3268 (let ((sym (syntax->datum #'c)))
3269 (if (memq sym %cond-expand-features)
3270 #t
3271 (module-has-feature? (current-module) sym))))))
3272
3273 (define (match clauses alternate)
3274 (syntax-case clauses ()
3275 (((condition form ...) . rest)
3276 (if (condition-matches? #'condition)
3277 #'(begin form ...)
3278 (match #'rest alternate)))
3279 (() (alternate))))
3280
3281 (syntax-case x (else)
3282 ((_ clause ... (else form ...))
3283 (match #'(clause ...)
3284 (lambda ()
3285 #'(begin form ...))))
3286 ((_ clause ...)
3287 (match #'(clause ...)
3288 (lambda ()
3289 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
0f2d19dd 3290
f41be016
MG
3291;; This procedure gets called from the startup code with a list of
3292;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3293;;
3294(define (use-srfis srfis)
9a18d8d4
KR
3295 (process-use-modules
3296 (map (lambda (num)
9b5a0d84
AW
3297 (list (list 'srfi (string->symbol
3298 (string-append "srfi-" (number->string num))))))
3299 srfis)))
f8a502cb 3300
0f2d19dd 3301\f
9d774814 3302
344d68d5
RB
3303;;; srfi-55: require-extension
3304;;;
3305
6669cd81
AW
3306(define-syntax require-extension
3307 (lambda (x)
3308 (syntax-case x (srfi)
3309 ((_ (srfi n ...))
3310 (and-map integer? (syntax->datum #'(n ...)))
3311 (with-syntax
3312 (((srfi-n ...)
3313 (map (lambda (n)
3314 (datum->syntax x (symbol-append 'srfi- n)))
3315 (map string->symbol
3316 (map number->string (syntax->datum #'(n ...)))))))
3317 #'(use-modules (srfi srfi-n) ...)))
3318 ((_ (type arg ...))
3319 (identifier? #'type)
3320 (syntax-violation 'require-extension "Not a recognized extension type"
3321 x)))))
344d68d5
RB
3322
3323\f
3324
755457ec
MD
3325(define using-readline?
3326 (let ((using-readline? (make-fluid)))
3327 (make-procedure-with-setter
3328 (lambda () (fluid-ref using-readline?))
3329 (lambda (v) (fluid-set! using-readline? v)))))
3330
4d31f0da 3331\f
3d2ada2f
DH
3332
3333;;; {Deprecated stuff}
3334;;;
3335
3d2ada2f 3336(begin-deprecated
0ea72faa 3337 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3d2ada2f
DH
3338
3339\f
3340
3341;;; Place the user in the guile-user module.
3342;;;
6eb396fe 3343
a2689737
AW
3344;; FIXME:
3345(module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3346
68623e8e 3347(define-module (guile-user)
9c933e1d 3348 #:autoload (system base compile) (compile compile-file))
6d36532c 3349
7385dc12
LC
3350;; Remain in the `(guile)' module at compilation-time so that the
3351;; `-Wunused-toplevel' warning works as expected.
3352(eval-when (compile) (set-current-module the-root-module))
3353
20edfbbd 3354;;; boot-9.scm ends here