deprecate turn-on-debugging, it is obsolete
[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)
132e5fac 534(define (and=> value procedure) (and value (procedure value)))
e8ed460e 535(define call/cc call-with-current-continuation)
79451588 536
27ae3651
AW
537(define-syntax false-if-exception
538 (syntax-rules ()
539 ((_ expr)
540 (catch #t
541 (lambda () expr)
542 (lambda (k . args) #f)))))
3d2ada2f
DH
543
544\f
545
546;;; {General Properties}
547;;;
548
02b582ce
AW
549;; Properties are a lispy way to associate random info with random objects.
550;; Traditionally properties are implemented as an alist or a plist actually
551;; pertaining to the object in question.
552;;
553;; These "object properties" have the advantage that they can be associated with
554;; any object, even if the object has no plist. Object properties are good when
555;; you are extending pre-existing objects in unexpected ways. They also present
556;; a pleasing, uniform procedure-with-setter interface. But if you have a data
557;; type that always has properties, it's often still best to store those
558;; properties within the object itself.
3d2ada2f
DH
559
560(define (make-object-property)
561 (let ((prop (primitive-make-property #f)))
562 (make-procedure-with-setter
563 (lambda (obj) (primitive-property-ref prop obj))
564 (lambda (obj val) (primitive-property-set! prop obj val)))))
565
0f2d19dd 566\f
6b08d75b 567
0f2d19dd
JB
568;;; {Symbol Properties}
569;;;
570
02b582ce
AW
571;;; Symbol properties are something you see in old Lisp code. In most current
572;;; Guile code, symbols are not used as a data structure -- they are used as
573;;; keys into other data structures.
574
0f2d19dd
JB
575(define (symbol-property sym prop)
576 (let ((pair (assoc prop (symbol-pref sym))))
577 (and pair (cdr pair))))
578
579(define (set-symbol-property! sym prop val)
580 (let ((pair (assoc prop (symbol-pref sym))))
581 (if pair
9b5a0d84
AW
582 (set-cdr! pair val)
583 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
0f2d19dd
JB
584
585(define (symbol-property-remove! sym prop)
586 (let ((pair (assoc prop (symbol-pref sym))))
587 (if pair
9b5a0d84 588 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
0f2d19dd
JB
589
590\f
1e531c3a 591
0f2d19dd
JB
592;;; {Arrays}
593;;;
594
2042e178
MV
595(define (array-shape a)
596 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
597 (array-dimensions a)))
0f2d19dd
JB
598
599\f
3d2ada2f 600
0f2d19dd
JB
601;;; {Keywords}
602;;;
603
010b159f
AW
604;;; It's much better if you can use lambda* / define*, of course.
605
0f2d19dd
JB
606(define (kw-arg-ref args kw)
607 (let ((rem (member kw args)))
608 (and rem (pair? (cdr rem)) (cadr rem))))
609
610\f
fa7e9274 611
9f9aa47b 612;;; {Structs}
3d2ada2f 613;;;
fa7e9274
MV
614
615(define (struct-layout s)
9f9aa47b 616 (struct-ref (struct-vtable s) vtable-index-layout))
fa7e9274
MV
617
618\f
d7faeb2e 619
0f2d19dd
JB
620;;; {Records}
621;;;
622
fa7e9274
MV
623;; Printing records: by default, records are printed as
624;;
625;; #<type-name field1: val1 field2: val2 ...>
626;;
627;; You can change that by giving a custom printing function to
628;; MAKE-RECORD-TYPE (after the list of field symbols). This function
629;; will be called like
630;;
631;; (<printer> object port)
632;;
633;; It should print OBJECT to PORT.
634
cf8f1a90 635(define (inherit-print-state old-port new-port)
8a30733e
MD
636 (if (get-print-state old-port)
637 (port-with-print-state new-port (get-print-state old-port))
cf8f1a90
MV
638 new-port))
639
e31f22eb 640;; 0: type-name, 1: fields, 2: constructor
20edfbbd 641(define record-type-vtable
e31f22eb
AW
642 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
643 ;; that we need to expose the bare vtable-vtable to Scheme.
644 (make-vtable-vtable "prprpw" 0
9b5a0d84
AW
645 (lambda (s p)
646 (cond ((eq? s record-type-vtable)
647 (display "#<record-type-vtable>" p))
648 (else
649 (display "#<record-type " p)
650 (display (record-type-name s) p)
651 (display ">" p))))))
0f2d19dd
JB
652
653(define (record-type? obj)
654 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
655
b2669c41 656(define* (make-record-type type-name fields #:optional printer)
31ac29b6 657 ;; Pre-generate constructors for nfields < 20.
e31f22eb
AW
658 (define-syntax make-constructor
659 (lambda (x)
660 (define *max-static-argument-count* 20)
661 (define (make-formals n)
662 (let lp ((i 0))
663 (if (< i n)
664 (cons (datum->syntax
665 x
666 (string->symbol
667 (string (integer->char (+ (char->integer #\a) i)))))
668 (lp (1+ i)))
669 '())))
670 (syntax-case x ()
671 ((_ rtd exp) (not (identifier? #'exp))
672 #'(let ((n exp))
673 (make-constructor rtd n)))
674 ((_ rtd nfields)
675 #`(case nfields
676 #,@(let lp ((n 0))
677 (if (< n *max-static-argument-count*)
678 (cons (with-syntax (((formal ...) (make-formals n))
679 (n n))
680 #'((n)
681 (lambda (formal ...)
682 (make-struct rtd 0 formal ...))))
683 (lp (1+ n)))
684 '()))
685 (else
686 (lambda args
687 (if (= (length args) nfields)
688 (apply make-struct rtd 0 args)
689 (scm-error 'wrong-number-of-args
690 (format #f "make-~a" type-name)
691 "Wrong number of arguments" '() #f)))))))))
692
51797cec
AW
693 (define (default-record-printer s p)
694 (display "#<" p)
695 (display (record-type-name (record-type-descriptor s)) p)
696 (let loop ((fields (record-type-fields (record-type-descriptor s)))
697 (off 0))
698 (cond
699 ((not (null? fields))
700 (display " " p)
701 (display (car fields) p)
702 (display ": " p)
703 (display (struct-ref s off) p)
704 (loop (cdr fields) (+ 1 off)))))
705 (display ">" p))
706
e31f22eb
AW
707 (let ((rtd (make-struct record-type-vtable 0
708 (make-struct-layout
709 (apply string-append
710 (map (lambda (f) "pw") fields)))
b2669c41 711 (or printer default-record-printer)
e31f22eb
AW
712 type-name
713 (copy-tree fields))))
714 (struct-set! rtd (+ vtable-offset-user 2)
715 (make-constructor rtd (length fields)))
51797cec
AW
716 ;; Temporary solution: Associate a name to the record type descriptor
717 ;; so that the object system can create a wrapper class for it.
e31f22eb
AW
718 (set-struct-vtable-name! rtd (if (symbol? type-name)
719 type-name
720 (string->symbol type-name)))
721 rtd))
0f2d19dd
JB
722
723(define (record-type-name obj)
724 (if (record-type? obj)
9f9aa47b 725 (struct-ref obj vtable-offset-user)
0f2d19dd
JB
726 (error 'not-a-record-type obj)))
727
728(define (record-type-fields obj)
729 (if (record-type? obj)
9f9aa47b 730 (struct-ref obj (+ 1 vtable-offset-user))
0f2d19dd
JB
731 (error 'not-a-record-type obj)))
732
d44a0d12
AW
733(define* (record-constructor rtd #:optional field-names)
734 (if (not field-names)
e31f22eb 735 (struct-ref rtd (+ 2 vtable-offset-user))
d44a0d12
AW
736 (primitive-eval
737 `(lambda ,field-names
738 (make-struct ',rtd 0 ,@(map (lambda (f)
739 (if (memq f field-names)
740 f
741 #f))
742 (record-type-fields rtd)))))))
3bf27608 743
0f2d19dd
JB
744(define (record-predicate rtd)
745 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
746
3ba9acb1 747(define (%record-type-error rtd obj) ;; private helper
afc4ccd4
KR
748 (or (eq? rtd (record-type-descriptor obj))
749 (scm-error 'wrong-type-arg "%record-type-check"
9b5a0d84
AW
750 "Wrong type record (want `~S'): ~S"
751 (list (record-type-name rtd) obj)
752 #f)))
afc4ccd4 753
0f2d19dd 754(define (record-accessor rtd field-name)
3bf27608 755 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 756 (if (not pos)
9b5a0d84 757 (error 'no-such-field field-name))
3bf27608
AW
758 (lambda (obj)
759 (if (eq? (struct-vtable obj) rtd)
760 (struct-ref obj pos)
761 (%record-type-error rtd obj)))))
0f2d19dd
JB
762
763(define (record-modifier rtd field-name)
3bf27608 764 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 765 (if (not pos)
9b5a0d84 766 (error 'no-such-field field-name))
3bf27608
AW
767 (lambda (obj val)
768 (if (eq? (struct-vtable obj) rtd)
769 (struct-set! obj pos val)
770 (%record-type-error rtd obj)))))
0f2d19dd
JB
771
772(define (record? obj)
773 (and (struct? obj) (record-type? (struct-vtable obj))))
774
775(define (record-type-descriptor obj)
776 (if (struct? obj)
777 (struct-vtable obj)
778 (error 'not-a-record obj)))
779
21ed9efe
MD
780(provide 'record)
781
0f2d19dd 782\f
3d2ada2f 783
0f2d19dd
JB
784;;; {Booleans}
785;;;
786
787(define (->bool x) (not (not x)))
788
789\f
3d2ada2f 790
0f2d19dd
JB
791;;; {Symbols}
792;;;
793
794(define (symbol-append . args)
06f0414c 795 (string->symbol (apply string-append (map symbol->string args))))
0f2d19dd
JB
796
797(define (list->symbol . args)
798 (string->symbol (apply list->string args)))
799
800(define (symbol . args)
801 (string->symbol (apply string args)))
802
0f2d19dd 803\f
3d2ada2f 804
0f2d19dd
JB
805;;; {Lists}
806;;;
807
808(define (list-index l k)
809 (let loop ((n 0)
9b5a0d84 810 (l l))
0f2d19dd 811 (and (not (null? l))
9b5a0d84
AW
812 (if (eq? (car l) k)
813 n
814 (loop (+ n 1) (cdr l))))))
0f2d19dd 815
1729d8ff 816\f
3d2ada2f 817
52cfc69b 818(if (provided? 'posix)
1e6ebf54 819 (primitive-load-path "ice-9/posix"))
6fa8995c 820
52cfc69b 821(if (provided? 'socket)
1e6ebf54 822 (primitive-load-path "ice-9/networking"))
3afb28ce 823
f3197274 824;; For reference, Emacs file-exists-p uses stat in this same way.
6fa8995c 825(define file-exists?
52cfc69b 826 (if (provided? 'posix)
6fa8995c 827 (lambda (str)
9b5a0d84 828 (->bool (stat str #f)))
6fa8995c 829 (lambda (str)
9b5a0d84
AW
830 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
831 (lambda args #f))))
832 (if port (begin (close-port port) #t)
833 #f)))))
6fa8995c
GH
834
835(define file-is-directory?
52cfc69b 836 (if (provided? 'posix)
6fa8995c 837 (lambda (str)
9b5a0d84 838 (eq? (stat:type (stat str)) 'directory))
6fa8995c 839 (lambda (str)
9b5a0d84
AW
840 (let ((port (catch 'system-error
841 (lambda () (open-file (string-append str "/.")
842 OPEN_READ))
843 (lambda args #f))))
844 (if port (begin (close-port port) #t)
845 #f)))))
0f2d19dd 846
019ac1c9
MV
847(define (system-error-errno args)
848 (if (eq? (car args) 'system-error)
849 (car (list-ref args 4))
850 #f))
851
0f2d19dd 852\f
3d2ada2f 853
0f2d19dd
JB
854;;; {Error Handling}
855;;;
856
4eeaf67c
AW
857(define error
858 (case-lambda
859 (()
4eeaf67c
AW
860 (scm-error 'misc-error #f "?" #f #f))
861 ((message . args)
4eeaf67c
AW
862 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
863 (scm-error 'misc-error #f msg (cons message args) #f)))))
be2d2c70 864
0f2d19dd 865\f
bce074ee 866
b38507c1
AW
867;;; {Time Structures}
868;;;
869
708bf0f3
GH
870(define (tm:sec obj) (vector-ref obj 0))
871(define (tm:min obj) (vector-ref obj 1))
872(define (tm:hour obj) (vector-ref obj 2))
873(define (tm:mday obj) (vector-ref obj 3))
874(define (tm:mon obj) (vector-ref obj 4))
875(define (tm:year obj) (vector-ref obj 5))
876(define (tm:wday obj) (vector-ref obj 6))
877(define (tm:yday obj) (vector-ref obj 7))
878(define (tm:isdst obj) (vector-ref obj 8))
879(define (tm:gmtoff obj) (vector-ref obj 9))
880(define (tm:zone obj) (vector-ref obj 10))
881
882(define (set-tm:sec obj val) (vector-set! obj 0 val))
883(define (set-tm:min obj val) (vector-set! obj 1 val))
884(define (set-tm:hour obj val) (vector-set! obj 2 val))
885(define (set-tm:mday obj val) (vector-set! obj 3 val))
886(define (set-tm:mon obj val) (vector-set! obj 4 val))
887(define (set-tm:year obj val) (vector-set! obj 5 val))
888(define (set-tm:wday obj val) (vector-set! obj 6 val))
889(define (set-tm:yday obj val) (vector-set! obj 7 val))
890(define (set-tm:isdst obj val) (vector-set! obj 8 val))
891(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
892(define (set-tm:zone obj val) (vector-set! obj 10 val))
893
6afcd3b2
GH
894(define (tms:clock obj) (vector-ref obj 0))
895(define (tms:utime obj) (vector-ref obj 1))
896(define (tms:stime obj) (vector-ref obj 2))
897(define (tms:cutime obj) (vector-ref obj 3))
898(define (tms:cstime obj) (vector-ref obj 4))
899
b38507c1
AW
900\f
901
902;;; {File Descriptors and Ports}
903;;;
904
1334c61a 905(define file-position ftell)
52c9a338
AW
906(define* (file-set-position port offset #:optional (whence SEEK_SET))
907 (seek port offset whence))
8b13c6b3 908
e38303a2
GH
909(define (move->fdes fd/port fd)
910 (cond ((integer? fd/port)
9b5a0d84
AW
911 (dup->fdes fd/port fd)
912 (close fd/port)
913 fd)
914 (else
915 (primitive-move->fdes fd/port fd)
916 (set-port-revealed! fd/port 1)
917 fd/port)))
8b13c6b3
GH
918
919(define (release-port-handle port)
920 (let ((revealed (port-revealed port)))
921 (if (> revealed 0)
9b5a0d84 922 (set-port-revealed! port (- revealed 1)))))
0f2d19dd 923
02851b26
AW
924(define dup->port
925 (case-lambda
926 ((port/fd mode)
927 (fdopen (dup->fdes port/fd) mode))
928 ((port/fd mode new-fd)
929 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
930 (set-port-revealed! port 1)
931 port))))
932
933(define dup->inport
934 (case-lambda
935 ((port/fd)
936 (dup->port port/fd "r"))
937 ((port/fd new-fd)
938 (dup->port port/fd "r" new-fd))))
939
940(define dup->outport
941 (case-lambda
942 ((port/fd)
943 (dup->port port/fd "w"))
944 ((port/fd new-fd)
945 (dup->port port/fd "w" new-fd))))
946
947(define dup
948 (case-lambda
949 ((port/fd)
950 (if (integer? port/fd)
951 (dup->fdes port/fd)
952 (dup->port port/fd (port-mode port/fd))))
953 ((port/fd new-fd)
954 (if (integer? port/fd)
955 (dup->fdes port/fd new-fd)
956 (dup->port port/fd (port-mode port/fd) new-fd)))))
e38303a2
GH
957
958(define (duplicate-port port modes)
959 (dup->port port modes))
960
961(define (fdes->inport fdes)
962 (let loop ((rest-ports (fdes->ports fdes)))
963 (cond ((null? rest-ports)
9b5a0d84
AW
964 (let ((result (fdopen fdes "r")))
965 (set-port-revealed! result 1)
966 result))
967 ((input-port? (car rest-ports))
968 (set-port-revealed! (car rest-ports)
969 (+ (port-revealed (car rest-ports)) 1))
970 (car rest-ports))
971 (else
972 (loop (cdr rest-ports))))))
e38303a2
GH
973
974(define (fdes->outport fdes)
975 (let loop ((rest-ports (fdes->ports fdes)))
976 (cond ((null? rest-ports)
9b5a0d84
AW
977 (let ((result (fdopen fdes "w")))
978 (set-port-revealed! result 1)
979 result))
980 ((output-port? (car rest-ports))
981 (set-port-revealed! (car rest-ports)
982 (+ (port-revealed (car rest-ports)) 1))
983 (car rest-ports))
984 (else
985 (loop (cdr rest-ports))))))
e38303a2
GH
986
987(define (port->fdes port)
988 (set-port-revealed! port (+ (port-revealed port) 1))
989 (fileno port))
990
956055a9
GH
991(define (setenv name value)
992 (if value
993 (putenv (string-append name "=" value))
994 (putenv name)))
995
5c1254da
MV
996(define (unsetenv name)
997 "Remove the entry for NAME from the environment."
998 (putenv name))
999
0f2d19dd 1000\f
3d2ada2f 1001
0f2d19dd
JB
1002;;; {Load Paths}
1003;;;
1004
3cab8392
JB
1005(define (in-vicinity vicinity file)
1006 (let ((tail (let ((len (string-length vicinity)))
9b5a0d84
AW
1007 (if (zero? len)
1008 #f
1009 (string-ref vicinity (- len 1))))))
3cab8392 1010 (string-append vicinity
9b5a0d84
AW
1011 (if (or (not tail)
1012 (eq? tail #\/))
1013 ""
1014 "/")
1015 file)))
02ceadb8 1016
0f2d19dd 1017\f
3d2ada2f 1018
ef00e7f4 1019;;; {Help for scm_shell}
3d2ada2f 1020;;;
ef00e7f4
JB
1021;;; The argument-processing code used by Guile-based shells generates
1022;;; Scheme code based on the argument list. This page contains help
1023;;; functions for the code it generates.
3d2ada2f 1024;;;
ef00e7f4 1025
ef00e7f4
JB
1026(define (command-line) (program-arguments))
1027
5aa7fe69
JB
1028;; This is mostly for the internal use of the code generated by
1029;; scm_compile_shell_switches.
eef6519b 1030
ef00e7f4 1031(define (load-user-init)
1f08acd9 1032 (let* ((home (or (getenv "HOME")
9b5a0d84
AW
1033 (false-if-exception (passwd:dir (getpwuid (getuid))))
1034 "/")) ;; fallback for cygwin etc.
1035 (init-file (in-vicinity home ".guile")))
1f08acd9 1036 (if (file-exists? init-file)
9b5a0d84 1037 (primitive-load init-file))))
ef00e7f4
JB
1038
1039\f
3d2ada2f 1040
107139ea
AW
1041;;; {The interpreter stack}
1042;;;
1043
06dcb9df 1044;; %stacks defined in stacks.c
a6cd3555 1045(define (%start-stack tag thunk)
8fc43b12
AW
1046 (let ((prompt-tag (make-prompt-tag "start-stack")))
1047 (call-with-prompt
1048 prompt-tag
1049 (lambda ()
1050 (with-fluids ((%stacks (acons tag prompt-tag
1051 (or (fluid-ref %stacks) '()))))
1052 (thunk)))
1053 (lambda (k . args)
52738540 1054 (%start-stack tag (lambda () (apply k args)))))))
a6cd3555
AW
1055(define-syntax start-stack
1056 (syntax-rules ()
1057 ((_ tag exp)
1058 (%start-stack tag (lambda () exp)))))
107139ea
AW
1059
1060\f
1061
a06181a2 1062;;; {Loading by paths}
3d2ada2f 1063;;;
a06181a2
JB
1064
1065;;; Load a Scheme source file named NAME, searching for it in the
1066;;; directories listed in %load-path, and applying each of the file
1067;;; name extensions listed in %load-extensions.
1068(define (load-from-path name)
1069 (start-stack 'load-stack
9b5a0d84 1070 (primitive-load-path name)))
0f2d19dd 1071
85e95b47
AW
1072(define %load-verbosely #f)
1073(define (assert-load-verbosity v) (set! %load-verbosely v))
1074
1075(define (%load-announce file)
1076 (if %load-verbosely
1077 (with-output-to-port (current-error-port)
9b5a0d84
AW
1078 (lambda ()
1079 (display ";;; ")
1080 (display "loading ")
1081 (display file)
1082 (newline)
1083 (force-output)))))
85e95b47
AW
1084
1085(set! %load-hook %load-announce)
1086
d6e70467 1087(define* (load name #:optional reader)
1ab3976e
AW
1088 ;; Returns the .go file corresponding to `name'. Does not search load
1089 ;; paths, only the fallback path. If the .go file is missing or out of
1090 ;; date, and autocompilation is enabled, will try autocompilation, just
1091 ;; as primitive-load-path does internally. primitive-load is
1092 ;; unaffected. Returns #f if autocompilation failed or was disabled.
04af4c4c
AW
1093 ;;
1094 ;; NB: Unless we need to compile the file, this function should not cause
1095 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1096 ;; partially duplicates functionality from (system base compile).
1097 (define (compiled-file-name canon-path)
1098 (and %compile-fallback-path
1099 (string-append
1100 %compile-fallback-path
1101 ;; no need for '/' separator here, canon-path is absolute
1102 canon-path
1103 (cond ((or (null? %load-compiled-extensions)
1104 (string-null? (car %load-compiled-extensions)))
1105 (warn "invalid %load-compiled-extensions"
1106 %load-compiled-extensions)
1107 ".go")
1108 (else (car %load-compiled-extensions))))))
1109 (define (fresh-compiled-file-name go-path)
1ab3976e
AW
1110 (catch #t
1111 (lambda ()
04af4c4c 1112 (let* ((scmstat (stat name))
abca59fe
LC
1113 (gostat (stat go-path #f)))
1114 (if (and gostat
1115 (or (> (stat:mtime gostat) (stat:mtime scmstat))
1116 (and (= (stat:mtime gostat) (stat:mtime scmstat))
1117 (>= (stat:mtimensec gostat)
1118 (stat:mtimensec scmstat)))))
04af4c4c 1119 go-path
1ab3976e
AW
1120 (begin
1121 (if gostat
1122 (format (current-error-port)
1123 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
04af4c4c 1124 name go-path))
1ab3976e
AW
1125 (cond
1126 (%load-should-autocompile
1127 (%warn-autocompilation-enabled)
1128 (format (current-error-port) ";;; compiling ~a\n" name)
02fcbf78
AW
1129 ;; This use of @ is (ironically?) boot-safe, as modules have
1130 ;; not been booted yet, so the resolve-module call in psyntax
1131 ;; doesn't try to load a module, and compile-file will be
1132 ;; treated as a function, not a macro.
1ab3976e
AW
1133 (let ((cfn ((@ (system base compile) compile-file) name
1134 #:env (current-module))))
1135 (format (current-error-port) ";;; compiled ~a\n" cfn)
1136 cfn))
1137 (else #f))))))
1138 (lambda (k . args)
1139 (format (current-error-port)
1140 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1141 name k args)
1142 #f)))
d6e70467 1143 (with-fluids ((current-reader reader))
eddd16d7
AW
1144 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1145 compiled-file-name)
1146 fresh-compiled-file-name)))
1147 (if cfn
1148 (load-compiled cfn)
1149 (start-stack 'load-stack
1150 (primitive-load name))))))
5552355a 1151
0f2d19dd 1152\f
3d2ada2f 1153
0f2d19dd
JB
1154;;; {Reader Extensions}
1155;;;
0f2d19dd
JB
1156;;; Reader code for various "#c" forms.
1157;;;
1158
600c9584
RB
1159(define read-eval? (make-fluid))
1160(fluid-set! read-eval? #f)
1161(read-hash-extend #\.
1162 (lambda (c port)
1163 (if (fluid-ref read-eval?)
1164 (eval (read port) (interaction-environment))
1165 (error
71335c0d 1166 "#. read expansion found and read-eval? is #f."))))
75a97b92 1167
0f2d19dd 1168\f
3d2ada2f 1169
0f2d19dd
JB
1170;;; {Low Level Modules}
1171;;;
1172;;; These are the low level data structures for modules.
1173;;;
37f5dfe5
DH
1174;;; Every module object is of the type 'module-type', which is a record
1175;;; consisting of the following members:
1176;;;
1177;;; - eval-closure: the function that defines for its module the strategy that
1178;;; shall be followed when looking up symbols in the module.
1179;;;
1180;;; An eval-closure is a function taking two arguments: the symbol to be
1181;;; looked up and a boolean value telling whether a binding for the symbol
1182;;; should be created if it does not exist yet. If the symbol lookup
1183;;; succeeded (either because an existing binding was found or because a new
1184;;; binding was created), a variable object representing the binding is
1185;;; returned. Otherwise, the value #f is returned. Note that the eval
1186;;; closure does not take the module to be searched as an argument: During
1187;;; construction of the eval-closure, the eval-closure has to store the
1188;;; module it belongs to in its environment. This means, that any
1189;;; eval-closure can belong to only one module.
1190;;;
1191;;; The eval-closure of a module can be defined arbitrarily. However, three
1192;;; special cases of eval-closures are to be distinguished: During startup
1193;;; the module system is not yet activated. In this phase, no modules are
1194;;; defined and all bindings are automatically stored by the system in the
1195;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1196;;; functions which require an eval-closure as their argument need to be
1197;;; passed the value #f.
1198;;;
1199;;; The other two special cases of eval-closures are the
1200;;; standard-eval-closure and the standard-interface-eval-closure. Both
1201;;; behave equally for the case that no new binding is to be created. The
1202;;; difference between the two comes in, when the boolean argument to the
1203;;; eval-closure indicates that a new binding shall be created if it is not
1204;;; found.
1205;;;
1206;;; Given that no new binding shall be created, both standard eval-closures
1207;;; define the following standard strategy of searching bindings in the
1208;;; module: First, the module's obarray is searched for the symbol. Second,
1209;;; if no binding for the symbol was found in the module's obarray, the
1210;;; module's binder procedure is exececuted. If this procedure did not
1211;;; return a binding for the symbol, the modules referenced in the module's
1212;;; uses list are recursively searched for a binding of the symbol. If the
1213;;; binding can not be found in these modules also, the symbol lookup has
1214;;; failed.
1215;;;
1216;;; If a new binding shall be created, the standard-interface-eval-closure
1217;;; immediately returns indicating failure. That is, it does not even try
1218;;; to look up the symbol. In contrast, the standard-eval-closure would
1219;;; first search the obarray, and if no binding was found there, would
1220;;; create a new binding in the obarray, therefore not calling the binder
1221;;; procedure or searching the modules in the uses list.
1222;;;
1223;;; The explanation of the following members obarray, binder and uses
1224;;; assumes that the symbol lookup follows the strategy that is defined in
1225;;; the standard-eval-closure and the standard-interface-eval-closure.
1226;;;
1227;;; - obarray: a hash table that maps symbols to variable objects. In this
1228;;; hash table, the definitions are found that are local to the module (that
1229;;; is, not imported from other modules). When looking up bindings in the
1230;;; module, this hash table is searched first.
1231;;;
1232;;; - binder: either #f or a function taking a module and a symbol argument.
1233;;; If it is a function it is called after the obarray has been
1234;;; unsuccessfully searched for a binding. It then can provide bindings
1235;;; that would otherwise not be found locally in the module.
1236;;;
1237;;; - uses: a list of modules from which non-local bindings can be inherited.
1238;;; These modules are the third place queried for bindings after the obarray
1239;;; has been unsuccessfully searched and the binder function did not deliver
1240;;; a result either.
1241;;;
1242;;; - transformer: either #f or a function taking a scheme expression as
1243;;; delivered by read. If it is a function, it will be called to perform
1244;;; syntax transformations (e. g. makro expansion) on the given scheme
1245;;; expression. The output of the transformer function will then be passed
1246;;; to Guile's internal memoizer. This means that the output must be valid
1247;;; scheme code. The only exception is, that the output may make use of the
1248;;; syntax extensions provided to identify the modules that a binding
1249;;; belongs to.
1250;;;
1251;;; - name: the name of the module. This is used for all kinds of printing
1252;;; outputs. In certain places the module name also serves as a way of
1253;;; identification. When adding a module to the uses list of another
1254;;; module, it is made sure that the new uses list will not contain two
1255;;; modules of the same name.
1256;;;
1257;;; - kind: classification of the kind of module. The value is (currently?)
1258;;; only used for printing. It has no influence on how a module is treated.
1259;;; Currently the following values are used when setting the module kind:
1260;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1261;;; is set, it defaults to 'module.
1262;;;
608860a5
LC
1263;;; - duplicates-handlers: a list of procedures that get called to make a
1264;;; choice between two duplicate bindings when name clashes occur. See the
1265;;; `duplicate-handlers' global variable below.
37f5dfe5 1266;;;
608860a5
LC
1267;;; - observers: a list of procedures that get called when the module is
1268;;; modified.
37f5dfe5 1269;;;
608860a5
LC
1270;;; - weak-observers: a weak-key hash table of procedures that get called
1271;;; when the module is modified. See `module-observe-weak' for details.
37f5dfe5
DH
1272;;;
1273;;; In addition, the module may (must?) contain a binding for
608860a5
LC
1274;;; `%module-public-interface'. This variable should be bound to a module
1275;;; representing the exported interface of a module. See the
1276;;; `module-public-interface' and `module-export!' procedures.
37f5dfe5 1277;;;
0f2d19dd
JB
1278;;; !!! warning: The interface to lazy binder procedures is going
1279;;; to be changed in an incompatible way to permit all the basic
1280;;; module ops to be virtualized.
1281;;;
1282;;; (make-module size use-list lazy-binding-proc) => module
1283;;; module-{obarray,uses,binder}[|-set!]
1284;;; (module? obj) => [#t|#f]
1285;;; (module-locally-bound? module symbol) => [#t|#f]
1286;;; (module-bound? module symbol) => [#t|#f]
1287;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1288;;; (module-symbol-interned? module symbol) => [#t|#f]
1289;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1290;;; (module-variable module symbol) => [#<variable ...> | #f]
1291;;; (module-symbol-binding module symbol opt-value)
9b5a0d84 1292;;; => [ <obj> | opt-value | an error occurs ]
0f2d19dd
JB
1293;;; (module-make-local-var! module symbol) => #<variable...>
1294;;; (module-add! module symbol var) => unspecified
1295;;; (module-remove! module symbol) => unspecified
1296;;; (module-for-each proc module) => unspecified
1297;;; (make-scm-module) => module ; a lazy copy of the symhash module
1298;;; (set-current-module module) => unspecified
1299;;; (current-module) => #<module...>
1300;;;
1301;;;
1302
1303\f
3d2ada2f 1304
44cf1f0f 1305;;; {Printing Modules}
3d2ada2f
DH
1306;;;
1307
44cf1f0f 1308;; This is how modules are printed. You can re-define it.
31ac29b6 1309(define (%print-module mod port)
0f2d19dd
JB
1310 (display "#<" port)
1311 (display (or (module-kind mod) "module") port)
dc1eed52
AW
1312 (display " " port)
1313 (display (module-name mod) port)
0f2d19dd
JB
1314 (display " " port)
1315 (display (number->string (object-address mod) 16) port)
1316 (display ">" port))
1317
31ac29b6
AW
1318(letrec-syntax
1319 ;; Locally extend the syntax to allow record accessors to be defined at
1320 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1321 ;; the setters, in order to allow for redefinition of the record type; not
1322 ;; relevant in the case of modules, but perhaps if we make this public, it
1323 ;; could matter.
1324
1325 ((define-record-type
1326 (lambda (x)
1327 (define (make-id scope . fragments)
1328 (datum->syntax #'scope
1329 (apply symbol-append
1330 (map (lambda (x)
1331 (if (symbol? x) x (syntax->datum x)))
1332 fragments))))
1333
1334 (define (getter rtd type-name field slot)
1335 #`(define #,(make-id rtd type-name '- field)
1336 (let ((rtd #,rtd))
1337 (lambda (#,type-name)
1338 (if (eq? (struct-vtable #,type-name) rtd)
1339 (struct-ref #,type-name #,slot)
1340 (%record-type-error rtd #,type-name))))))
1341
1342 (define (setter rtd type-name field slot)
1343 #`(define #,(make-id rtd 'set- type-name '- field '!)
1344 (let ((rtd #,rtd))
1345 (lambda (#,type-name val)
1346 (if (eq? (struct-vtable #,type-name) rtd)
1347 (struct-set! #,type-name #,slot val)
1348 (%record-type-error rtd #,type-name))))))
1349
1350 (define (accessors rtd type-name fields n exp)
1351 (syntax-case fields ()
1352 (() exp)
1353 (((field #:no-accessors) field* ...) (identifier? #'field)
1354 (accessors rtd type-name #'(field* ...) (1+ n)
1355 exp))
1356 (((field #:no-setter) field* ...) (identifier? #'field)
1357 (accessors rtd type-name #'(field* ...) (1+ n)
1358 #`(begin #,exp
1359 #,(getter rtd type-name #'field n))))
1360 (((field #:no-getter) field* ...) (identifier? #'field)
1361 (accessors rtd type-name #'(field* ...) (1+ n)
1362 #`(begin #,exp
1363 #,(setter rtd type-name #'field n))))
1364 ((field field* ...) (identifier? #'field)
1365 (accessors rtd type-name #'(field* ...) (1+ n)
1366 #`(begin #,exp
1367 #,(getter rtd type-name #'field n)
1368 #,(setter rtd type-name #'field n))))))
1369
1370 (define (predicate rtd type-name fields exp)
1371 (accessors
1372 rtd type-name fields 0
1373 #`(begin
1374 #,exp
1375 (define (#,(make-id rtd type-name '?) obj)
1376 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1377
1378 (define (field-list fields)
1379 (syntax-case fields ()
1380 (() '())
1381 (((f . opts) . rest) (identifier? #'f)
1382 (cons #'f (field-list #'rest)))
1383 ((f . rest) (identifier? #'f)
1384 (cons #'f (field-list #'rest)))))
1385
1386 (define (constructor rtd type-name fields exp)
1387 (let ((ctor (make-id rtd type-name '-constructor))
1388 (args (field-list fields)))
1389 (predicate rtd type-name fields
1390 #`(begin #,exp
1391 (define #,ctor
1392 (let ((rtd #,rtd))
1393 (lambda #,args
1394 (make-struct rtd 0 #,@args))))
1395 (struct-set! #,rtd (+ vtable-offset-user 2)
1396 #,ctor)))))
1397
1398 (define (type type-name printer fields)
1399 (define (make-layout)
1400 (let lp ((fields fields) (slots '()))
1401 (syntax-case fields ()
1402 (() (datum->syntax #'here
1403 (make-struct-layout
1404 (apply string-append slots))))
1405 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1406
1407 (let ((rtd (make-id type-name type-name '-type)))
1408 (constructor rtd type-name fields
1409 #`(begin
1410 (define #,rtd
1411 (make-struct record-type-vtable 0
1412 '#,(make-layout)
1413 #,printer
1414 '#,type-name
1415 '#,(field-list fields)))
1416 (set-struct-vtable-name! #,rtd '#,type-name)))))
1417
1418 (syntax-case x ()
1419 ((_ type-name printer (field ...))
1420 (type #'type-name #'printer #'(field ...)))))))
1421
1422 ;; module-type
1423 ;;
1424 ;; A module is characterized by an obarray in which local symbols
1425 ;; are interned, a list of modules, "uses", from which non-local
1426 ;; bindings can be inherited, and an optional lazy-binder which
1427 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1428 ;; bindings that would otherwise not be found locally in the module.
1429 ;;
1430 ;; NOTE: If you change the set of fields or their order, you also need to
1431 ;; change the constants in libguile/modules.h.
1432 ;;
1433 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1434 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1435 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
4e48b495 1436 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
31ac29b6
AW
1437 ;;
1438 (define-record-type module
1439 (lambda (obj port) (%print-module obj port))
1440 (obarray
1441 uses
1442 binder
1443 eval-closure
1444 (transformer #:no-getter)
1445 (name #:no-getter)
1446 kind
1447 duplicates-handlers
1448 (import-obarray #:no-setter)
1449 observers
1450 (weak-observers #:no-setter)
f905381d 1451 version
81fc66cf 1452 submodules
4e48b495 1453 submodule-binder
78f79f18
AW
1454 public-interface
1455 filename)))
31ac29b6 1456
0f2d19dd 1457
8b718458 1458;; make-module &opt size uses binder
0f2d19dd 1459;;
8b718458
JB
1460;; Create a new module, perhaps with a particular size of obarray,
1461;; initial uses list, or binding procedure.
0f2d19dd 1462;;
e9729cbb
AW
1463(define* (make-module #:optional (size 31) (uses '()) (binder #f))
1464 (define %default-import-size
1465 ;; Typical number of imported bindings actually used by a module.
1466 600)
1467
1468 (if (not (integer? size))
1469 (error "Illegal size to make-module." size))
1470 (if (not (and (list? uses)
1471 (and-map module? uses)))
1472 (error "Incorrect use list." uses))
1473 (if (and binder (not (procedure? binder)))
1474 (error
1475 "Lazy-binder expected to be a procedure or #f." binder))
1476
1477 (let ((module (module-constructor (make-hash-table size)
1478 uses binder #f macroexpand
1479 #f #f #f
1480 (make-hash-table %default-import-size)
1481 '()
1482 (make-weak-key-hash-table 31) #f
1483 (make-hash-table 7) #f #f #f)))
1484
1485 ;; We can't pass this as an argument to module-constructor,
1486 ;; because we need it to close over a pointer to the module
1487 ;; itself.
1488 (set-module-eval-closure! module (standard-eval-closure module))
1489
1490 module))
0f2d19dd 1491
8b718458 1492
0f2d19dd 1493\f
3d2ada2f 1494
1777c18b
MD
1495;;; {Observer protocol}
1496;;;
1497
1498(define (module-observe module proc)
1499 (set-module-observers! module (cons proc (module-observers module)))
1500 (cons module proc))
1501
723ae5b3 1502(define* (module-observe-weak module observer-id #:optional (proc observer-id))
608860a5
LC
1503 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1504 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1505 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1506 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1507 ;; for instance).
1508
1509 ;; The two-argument version is kept for backward compatibility: when called
1510 ;; with two arguments, the observer gets unregistered when closure PROC
1511 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
723ae5b3 1512 (hashq-set! (module-weak-observers module) observer-id proc))
1777c18b
MD
1513
1514(define (module-unobserve token)
1515 (let ((module (car token))
9b5a0d84 1516 (id (cdr token)))
1777c18b 1517 (if (integer? id)
9b5a0d84
AW
1518 (hash-remove! (module-weak-observers module) id)
1519 (set-module-observers! module (delq1! id (module-observers module)))))
1777c18b
MD
1520 *unspecified*)
1521
d57da08b 1522(define module-defer-observers #f)
03d6cddc 1523(define module-defer-observers-mutex (make-mutex 'recursive))
d57da08b
MD
1524(define module-defer-observers-table (make-hash-table))
1525
1a961d7e 1526(define (module-modified m)
d57da08b
MD
1527 (if module-defer-observers
1528 (hash-set! module-defer-observers-table m #t)
1529 (module-call-observers m)))
1530
1531;;; This function can be used to delay calls to observers so that they
1532;;; can be called once only in the face of massive updating of modules.
1533;;;
1534(define (call-with-deferred-observers thunk)
1535 (dynamic-wind
1536 (lambda ()
9b5a0d84
AW
1537 (lock-mutex module-defer-observers-mutex)
1538 (set! module-defer-observers #t))
d57da08b
MD
1539 thunk
1540 (lambda ()
9b5a0d84
AW
1541 (set! module-defer-observers #f)
1542 (hash-for-each (lambda (m dummy)
1543 (module-call-observers m))
1544 module-defer-observers-table)
1545 (hash-clear! module-defer-observers-table)
1546 (unlock-mutex module-defer-observers-mutex))))
d57da08b
MD
1547
1548(define (module-call-observers m)
1777c18b 1549 (for-each (lambda (proc) (proc m)) (module-observers m))
608860a5
LC
1550
1551 ;; We assume that weak observers don't (un)register themselves as they are
1552 ;; called since this would preclude proper iteration over the hash table
1553 ;; elements.
1554 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1777c18b
MD
1555
1556\f
3d2ada2f 1557
0f2d19dd
JB
1558;;; {Module Searching in General}
1559;;;
1560;;; We sometimes want to look for properties of a symbol
1561;;; just within the obarray of one module. If the property
1562;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1563;;; DISPLAY is locally rebound in the module `safe-guile'.''
1564;;;
1565;;;
1566;;; Other times, we want to test for a symbol property in the obarray
1567;;; of M and, if it is not found there, try each of the modules in the
1568;;; uses list of M. This is the normal way of testing for some
1569;;; property, so we state these properties without qualification as
1570;;; in: ``The symbol 'fnord is interned in module M because it is
1571;;; interned locally in module M2 which is a member of the uses list
1572;;; of M.''
1573;;;
1574
1575;; module-search fn m
20edfbbd 1576;;
0f2d19dd
JB
1577;; return the first non-#f result of FN applied to M and then to
1578;; the modules in the uses of m, and so on recursively. If all applications
1579;; return #f, then so does this function.
1580;;
1581(define (module-search fn m v)
1582 (define (loop pos)
1583 (and (pair? pos)
9b5a0d84
AW
1584 (or (module-search fn (car pos) v)
1585 (loop (cdr pos)))))
0f2d19dd
JB
1586 (or (fn m v)
1587 (loop (module-uses m))))
1588
1589
1590;;; {Is a symbol bound in a module?}
1591;;;
1592;;; Symbol S in Module M is bound if S is interned in M and if the binding
1593;;; of S in M has been set to some well-defined value.
1594;;;
1595
1596;; module-locally-bound? module symbol
1597;;
1598;; Is a symbol bound (interned and defined) locally in a given module?
1599;;
1600(define (module-locally-bound? m v)
1601 (let ((var (module-local-variable m v)))
1602 (and var
9b5a0d84 1603 (variable-bound? var))))
0f2d19dd
JB
1604
1605;; module-bound? module symbol
1606;;
1607;; Is a symbol bound (interned and defined) anywhere in a given module
1608;; or its uses?
1609;;
1610(define (module-bound? m v)
f176c584
AW
1611 (let ((var (module-variable m v)))
1612 (and var
9b5a0d84 1613 (variable-bound? var))))
0f2d19dd
JB
1614
1615;;; {Is a symbol interned in a module?}
1616;;;
20edfbbd 1617;;; Symbol S in Module M is interned if S occurs in
0f2d19dd
JB
1618;;; of S in M has been set to some well-defined value.
1619;;;
1620;;; It is possible to intern a symbol in a module without providing
1621;;; an initial binding for the corresponding variable. This is done
1622;;; with:
1623;;; (module-add! module symbol (make-undefined-variable))
1624;;;
1625;;; In that case, the symbol is interned in the module, but not
1626;;; bound there. The unbound symbol shadows any binding for that
1627;;; symbol that might otherwise be inherited from a member of the uses list.
1628;;;
1629
1630(define (module-obarray-get-handle ob key)
1631 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1632
1633(define (module-obarray-ref ob key)
1634 ((if (symbol? key) hashq-ref hash-ref) ob key))
1635
1636(define (module-obarray-set! ob key val)
1637 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1638
1639(define (module-obarray-remove! ob key)
1640 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1641
1642;; module-symbol-locally-interned? module symbol
20edfbbd 1643;;
0f2d19dd
JB
1644;; is a symbol interned (not neccessarily defined) locally in a given module
1645;; or its uses? Interned symbols shadow inherited bindings even if
1646;; they are not themselves bound to a defined value.
1647;;
1648(define (module-symbol-locally-interned? m v)
1649 (not (not (module-obarray-get-handle (module-obarray m) v))))
1650
1651;; module-symbol-interned? module symbol
20edfbbd 1652;;
0f2d19dd
JB
1653;; is a symbol interned (not neccessarily defined) anywhere in a given module
1654;; or its uses? Interned symbols shadow inherited bindings even if
1655;; they are not themselves bound to a defined value.
1656;;
1657(define (module-symbol-interned? m v)
1658 (module-search module-symbol-locally-interned? m v))
1659
1660
1661;;; {Mapping modules x symbols --> variables}
1662;;;
1663
1664;; module-local-variable module symbol
1665;; return the local variable associated with a MODULE and SYMBOL.
1666;;
1667;;; This function is very important. It is the only function that can
1668;;; return a variable from a module other than the mutators that store
1669;;; new variables in modules. Therefore, this function is the location
1670;;; of the "lazy binder" hack.
1671;;;
1672;;; If symbol is defined in MODULE, and if the definition binds symbol
1673;;; to a variable, return that variable object.
1674;;;
1675;;; If the symbols is not found at first, but the module has a lazy binder,
1676;;; then try the binder.
1677;;;
1678;;; If the symbol is not found at all, return #f.
1679;;;
608860a5
LC
1680;;; (This is now written in C, see `modules.c'.)
1681;;;
0f2d19dd
JB
1682
1683;;; {Mapping modules x symbols --> bindings}
1684;;;
1685;;; These are similar to the mapping to variables, except that the
1686;;; variable is dereferenced.
1687;;;
1688
1689;; module-symbol-binding module symbol opt-value
20edfbbd 1690;;
0f2d19dd
JB
1691;; return the binding of a variable specified by name within
1692;; a given module, signalling an error if the variable is unbound.
1693;; If the OPT-VALUE is passed, then instead of signalling an error,
1694;; return OPT-VALUE.
1695;;
1696(define (module-symbol-local-binding m v . opt-val)
1697 (let ((var (module-local-variable m v)))
7b07e5ef 1698 (if (and var (variable-bound? var))
9b5a0d84
AW
1699 (variable-ref var)
1700 (if (not (null? opt-val))
1701 (car opt-val)
1702 (error "Locally unbound variable." v)))))
0f2d19dd
JB
1703
1704;; module-symbol-binding module symbol opt-value
20edfbbd 1705;;
0f2d19dd
JB
1706;; return the binding of a variable specified by name within
1707;; a given module, signalling an error if the variable is unbound.
1708;; If the OPT-VALUE is passed, then instead of signalling an error,
1709;; return OPT-VALUE.
1710;;
1711(define (module-symbol-binding m v . opt-val)
1712 (let ((var (module-variable m v)))
7b07e5ef 1713 (if (and var (variable-bound? var))
9b5a0d84
AW
1714 (variable-ref var)
1715 (if (not (null? opt-val))
1716 (car opt-val)
1717 (error "Unbound variable." v)))))
0f2d19dd
JB
1718
1719
1720\f
3d2ada2f 1721
0f2d19dd
JB
1722;;; {Adding Variables to Modules}
1723;;;
0f2d19dd
JB
1724
1725;; module-make-local-var! module symbol
20edfbbd 1726;;
0f2d19dd
JB
1727;; ensure a variable for V in the local namespace of M.
1728;; If no variable was already there, then create a new and uninitialzied
1729;; variable.
1730;;
d57da08b
MD
1731;; This function is used in modules.c.
1732;;
0f2d19dd
JB
1733(define (module-make-local-var! m v)
1734 (or (let ((b (module-obarray-ref (module-obarray m) v)))
9b5a0d84
AW
1735 (and (variable? b)
1736 (begin
1737 ;; Mark as modified since this function is called when
1738 ;; the standard eval closure defines a binding
1739 (module-modified m)
1740 b)))
0c5f718b 1741
608860a5
LC
1742 ;; Create a new local variable.
1743 (let ((local-var (make-undefined-variable)))
1744 (module-add! m v local-var)
1745 local-var)))
0f2d19dd 1746
89d06712 1747;; module-ensure-local-variable! module symbol
9540368e 1748;;
89d06712
MV
1749;; Ensure that there is a local variable in MODULE for SYMBOL. If
1750;; there is no binding for SYMBOL, create a new uninitialized
1751;; variable. Return the local variable.
9540368e 1752;;
89d06712
MV
1753(define (module-ensure-local-variable! module symbol)
1754 (or (module-local-variable module symbol)
9540368e 1755 (let ((var (make-undefined-variable)))
9b5a0d84
AW
1756 (module-add! module symbol var)
1757 var)))
9540368e 1758
0f2d19dd 1759;; module-add! module symbol var
20edfbbd 1760;;
0f2d19dd
JB
1761;; ensure a particular variable for V in the local namespace of M.
1762;;
1763(define (module-add! m v var)
1764 (if (not (variable? var))
1765 (error "Bad variable to module-add!" var))
1777c18b 1766 (module-obarray-set! (module-obarray m) v var)
1a961d7e 1767 (module-modified m))
0f2d19dd 1768
20edfbbd
TTN
1769;; module-remove!
1770;;
0f2d19dd
JB
1771;; make sure that a symbol is undefined in the local namespace of M.
1772;;
1773(define (module-remove! m v)
c35738c1 1774 (module-obarray-remove! (module-obarray m) v)
1a961d7e 1775 (module-modified m))
0f2d19dd
JB
1776
1777(define (module-clear! m)
c35738c1 1778 (hash-clear! (module-obarray m))
1a961d7e 1779 (module-modified m))
0f2d19dd
JB
1780
1781;; MODULE-FOR-EACH -- exported
20edfbbd 1782;;
0f2d19dd
JB
1783;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1784;;
1785(define (module-for-each proc module)
c35738c1 1786 (hash-for-each proc (module-obarray module)))
0f2d19dd
JB
1787
1788(define (module-map proc module)
711a9fd7 1789 (hash-map->list proc (module-obarray module)))
c35738c1 1790
0f27ab8a
AW
1791;; Submodules
1792;;
1793;; Modules exist in a separate namespace from values, because you generally do
1794;; not want the name of a submodule, which you might not even use, to collide
1795;; with local variables that happen to be named the same as the submodule.
1796;;
1797(define (module-ref-submodule module name)
81fc66cf
AW
1798 (or (hashq-ref (module-submodules module) name)
1799 (and (module-submodule-binder module)
1800 ((module-submodule-binder module) module name))))
0f27ab8a
AW
1801
1802(define (module-define-submodule! module name submodule)
f6a5308b 1803 (hashq-set! (module-submodules module) name submodule))
0f27ab8a 1804
dcb68c09
AW
1805;; It used to be, however, that module names were also present in the
1806;; value namespace. When we enable deprecated code, we preserve this
1807;; legacy behavior.
1808;;
1809;; These shims are defined here instead of in deprecated.scm because we
1810;; need their definitions before loading other modules.
1811;;
1812(begin-deprecated
1813 (define (module-ref-submodule module name)
1814 (or (hashq-ref (module-submodules module) name)
1815 (and (module-submodule-binder module)
1816 ((module-submodule-binder module) module name))
1817 (let ((var (module-local-variable module name)))
1818 (and var (variable-bound? var) (module? (variable-ref var))
1819 (begin
1820 (warn "module" module "not in submodules table")
1821 (variable-ref var))))))
1822
1823 (define (module-define-submodule! module name submodule)
1824 (let ((var (module-local-variable module name)))
1825 (if (and var
1826 (or (not (variable-bound? var))
1827 (not (module? (variable-ref var)))))
1828 (warn "defining module" module ": not overriding local definition" var)
1829 (module-define! module name submodule)))
1830 (hashq-set! (module-submodules module) name submodule)))
1831
0f2d19dd
JB
1832\f
1833
0f2d19dd
JB
1834;;; {Module-based Loading}
1835;;;
1836
1837(define (save-module-excursion thunk)
1838 (let ((inner-module (current-module))
9b5a0d84 1839 (outer-module #f))
0f2d19dd 1840 (dynamic-wind (lambda ()
9b5a0d84
AW
1841 (set! outer-module (current-module))
1842 (set-current-module inner-module)
1843 (set! inner-module #f))
1844 thunk
1845 (lambda ()
1846 (set! inner-module (current-module))
1847 (set-current-module outer-module)
1848 (set! outer-module #f)))))
0f2d19dd 1849
0f2d19dd
JB
1850(define basic-load load)
1851
5a662124 1852(define* (load-module filename #:optional reader)
c6775c40
MD
1853 (save-module-excursion
1854 (lambda ()
1855 (let ((oldname (and (current-load-port)
9b5a0d84 1856 (port-filename (current-load-port)))))
5a662124
AW
1857 (basic-load (if (and oldname
1858 (> (string-length filename) 0)
1859 (not (char=? (string-ref filename 0) #\/))
1860 (not (string=? (dirname oldname) ".")))
1861 (string-append (dirname oldname) "/" filename)
1862 filename)
1863 reader)))))
0f2d19dd
JB
1864
1865
1866\f
3d2ada2f 1867
44cf1f0f 1868;;; {MODULE-REF -- exported}
3d2ada2f
DH
1869;;;
1870
0f2d19dd
JB
1871;; Returns the value of a variable called NAME in MODULE or any of its
1872;; used modules. If there is no such variable, then if the optional third
1873;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
20edfbbd 1874;;
0f2d19dd
JB
1875(define (module-ref module name . rest)
1876 (let ((variable (module-variable module name)))
1877 (if (and variable (variable-bound? variable))
9b5a0d84
AW
1878 (variable-ref variable)
1879 (if (null? rest)
1880 (error "No variable named" name 'in module)
1881 (car rest) ; default value
1882 ))))
0f2d19dd
JB
1883
1884;; MODULE-SET! -- exported
1885;;
1886;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1887;; to VALUE; if there is no such variable, an error is signaled.
20edfbbd 1888;;
0f2d19dd
JB
1889(define (module-set! module name value)
1890 (let ((variable (module-variable module name)))
1891 (if variable
9b5a0d84
AW
1892 (variable-set! variable value)
1893 (error "No variable named" name 'in module))))
0f2d19dd
JB
1894
1895;; MODULE-DEFINE! -- exported
1896;;
1897;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1898;; variable, it is added first.
20edfbbd 1899;;
0f2d19dd
JB
1900(define (module-define! module name value)
1901 (let ((variable (module-local-variable module name)))
1902 (if variable
9b5a0d84
AW
1903 (begin
1904 (variable-set! variable value)
1905 (module-modified module))
1906 (let ((variable (make-variable value)))
1907 (module-add! module name variable)))))
0f2d19dd 1908
ed218d98
MV
1909;; MODULE-DEFINED? -- exported
1910;;
1911;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1912;; uses)
1913;;
1914(define (module-defined? module name)
1915 (let ((variable (module-variable module name)))
1916 (and variable (variable-bound? variable))))
1917
0f2d19dd
JB
1918;; MODULE-USE! module interface
1919;;
1920;; Add INTERFACE to the list of interfaces used by MODULE.
20edfbbd 1921;;
0f2d19dd 1922(define (module-use! module interface)
b1907902
AW
1923 (if (not (or (eq? module interface)
1924 (memq interface (module-uses module))))
608860a5
LC
1925 (begin
1926 ;; Newly used modules must be appended rather than consed, so that
1927 ;; `module-variable' traverses the use list starting from the first
1928 ;; used module.
1929 (set-module-uses! module
1930 (append (filter (lambda (m)
1931 (not
1932 (equal? (module-name m)
1933 (module-name interface))))
1934 (module-uses module))
1935 (list interface)))
8f44138a 1936 (hash-clear! (module-import-obarray module))
608860a5 1937 (module-modified module))))
0f2d19dd 1938
7b07e5ef
MD
1939;; MODULE-USE-INTERFACES! module interfaces
1940;;
1941;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1942;;
1943(define (module-use-interfaces! module interfaces)
608860a5
LC
1944 (set-module-uses! module
1945 (append (module-uses module) interfaces))
8f44138a 1946 (hash-clear! (module-import-obarray module))
608860a5 1947 (module-modified module))
7b07e5ef 1948
0f2d19dd 1949\f
3d2ada2f 1950
0f2d19dd
JB
1951;;; {Recursive Namespaces}
1952;;;
0f2d19dd 1953;;; A hierarchical namespace emerges if we consider some module to be
b910c4ac 1954;;; root, and submodules of that module to be nested namespaces.
0f2d19dd 1955;;;
b910c4ac 1956;;; The routines here manage variable names in hierarchical namespace.
0f2d19dd
JB
1957;;; Each variable name is a list of elements, looked up in successively nested
1958;;; modules.
1959;;;
9b5a0d84 1960;;; (nested-ref some-root-module '(foo bar baz))
b910c4ac
AW
1961;;; => <value of a variable named baz in the submodule bar of
1962;;; the submodule foo of some-root-module>
0f2d19dd
JB
1963;;;
1964;;;
1965;;; There are:
1966;;;
9b5a0d84
AW
1967;;; ;; a-root is a module
1968;;; ;; name is a list of symbols
0f2d19dd 1969;;;
9b5a0d84
AW
1970;;; nested-ref a-root name
1971;;; nested-set! a-root name val
1972;;; nested-define! a-root name val
1973;;; nested-remove! a-root name
0f2d19dd 1974;;;
b910c4ac
AW
1975;;; These functions manipulate values in namespaces. For referencing the
1976;;; namespaces themselves, use the following:
0f2d19dd 1977;;;
b910c4ac
AW
1978;;; nested-ref-module a-root name
1979;;; nested-define-module! a-root name mod
1980;;;
1981;;; (current-module) is a natural choice for a root so for convenience there are
0f2d19dd
JB
1982;;; also:
1983;;;
b910c4ac
AW
1984;;; local-ref name == nested-ref (current-module) name
1985;;; local-set! name val == nested-set! (current-module) name val
1986;;; local-define name val == nested-define! (current-module) name val
1987;;; local-remove name == nested-remove! (current-module) name
1988;;; local-ref-module name == nested-ref-module (current-module) name
1989;;; local-define-module! name m == nested-define-module! (current-module) name m
0f2d19dd
JB
1990;;;
1991
1992
0dd5491c 1993(define (nested-ref root names)
b910c4ac
AW
1994 (if (null? names)
1995 root
1996 (let loop ((cur root)
1997 (head (car names))
1998 (tail (cdr names)))
1999 (if (null? tail)
2000 (module-ref cur head #f)
2001 (let ((cur (module-ref-submodule cur head)))
2002 (and cur
2003 (loop cur (car tail) (cdr tail))))))))
0f2d19dd 2004
0dd5491c 2005(define (nested-set! root names val)
0f2d19dd 2006 (let loop ((cur root)
b910c4ac
AW
2007 (head (car names))
2008 (tail (cdr names)))
2009 (if (null? tail)
2010 (module-set! cur head val)
2011 (let ((cur (module-ref-submodule cur head)))
2012 (if (not cur)
2013 (error "failed to resolve module" names)
2014 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2015
0dd5491c 2016(define (nested-define! root names val)
0f2d19dd 2017 (let loop ((cur root)
b910c4ac
AW
2018 (head (car names))
2019 (tail (cdr names)))
2020 (if (null? tail)
2021 (module-define! cur head val)
2022 (let ((cur (module-ref-submodule cur head)))
2023 (if (not cur)
2024 (error "failed to resolve module" names)
2025 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2026
0dd5491c 2027(define (nested-remove! root names)
0f2d19dd 2028 (let loop ((cur root)
b910c4ac
AW
2029 (head (car names))
2030 (tail (cdr names)))
2031 (if (null? tail)
2032 (module-remove! cur head)
2033 (let ((cur (module-ref-submodule cur head)))
2034 (if (not cur)
2035 (error "failed to resolve module" names)
2036 (loop cur (car tail) (cdr tail)))))))
2037
2038
2039(define (nested-ref-module root names)
2040 (let loop ((cur root)
2041 (names names))
2042 (if (null? names)
2043 cur
2044 (let ((cur (module-ref-submodule cur (car names))))
2045 (and cur
2046 (loop cur (cdr names)))))))
2047
2048(define (nested-define-module! root names module)
2049 (if (null? names)
2050 (error "can't redefine root module" root module)
2051 (let loop ((cur root)
2052 (head (car names))
2053 (tail (cdr names)))
2054 (if (null? tail)
2055 (module-define-submodule! cur head module)
2056 (let ((cur (or (module-ref-submodule cur head)
2057 (let ((m (make-module 31)))
2058 (set-module-kind! m 'directory)
2059 (set-module-name! m (append (module-name cur)
2060 (list head)))
2061 (module-define-submodule! cur head m)
2062 m))))
2063 (loop cur (car tail) (cdr tail)))))))
2064
0f2d19dd 2065
1623ca68
AW
2066(define (local-ref names)
2067 (nested-ref (current-module) names))
2068
2069(define (local-set! names val)
2070 (nested-set! (current-module) names val))
2071
2072(define (local-define names val)
2073 (nested-define! (current-module) names val))
2074
2075(define (local-remove names)
2076 (nested-remove! (current-module) names))
2077
2078(define (local-ref-module names)
2079 (nested-ref-module (current-module) names))
2080
2081(define (local-define-module names mod)
2082 (nested-define-module! (current-module) names mod))
b910c4ac 2083
0f2d19dd
JB
2084
2085
2086\f
3d2ada2f 2087
cb67c838 2088;;; {The (guile) module}
0f2d19dd 2089;;;
cb67c838
AW
2090;;; The standard module, which has the core Guile bindings. Also called the
2091;;; "root module", as it is imported by many other modules, but it is not
2092;;; necessarily the root of anything; and indeed, the module named '() might be
2093;;; better thought of as a root.
0f2d19dd 2094;;;
bbd1d133 2095
edc185c7
MD
2096(define (set-system-module! m s)
2097 (set-procedure-property! (module-eval-closure m) 'system-module s))
0f2d19dd 2098
76aea207
AW
2099;; The root module uses the pre-modules-obarray as its obarray. This
2100;; special obarray accumulates all bindings that have been established
2101;; before the module system is fully booted.
2102;;
2103;; (The obarray continues to be used by code that has been closed over
2104;; before the module system has been booted.)
2105;;
2106(define the-root-module
2107 (let ((m (make-module 0)))
2108 (set-module-obarray! m (%get-pre-modules-obarray))
2109 (set-module-name! m '(guile))
2110 (set-system-module! m #t)
2111 m))
2112
2113;; The root interface is a module that uses the same obarray as the
2114;; root module. It does not allow new definitions, tho.
2115;;
2116(define the-scm-module
2117 (let ((m (make-module 0)))
2118 (set-module-obarray! m (%get-pre-modules-obarray))
2119 (set-module-eval-closure! m (standard-interface-eval-closure m))
2120 (set-module-name! m '(guile))
2121 (set-module-kind! m 'interface)
2122 (set-system-module! m #t)
2123 m))
2124
2125(set-module-public-interface! the-root-module the-scm-module)
bbd1d133
AW
2126
2127\f
2128
2129;; Now that we have a root module, even though modules aren't fully booted,
2130;; expand the definition of resolve-module.
2131;;
2132(define (resolve-module name . args)
2133 (if (equal? name '(guile))
2134 the-root-module
2135 (error "unexpected module to resolve during module boot" name)))
2136
2137;; Cheat. These bindings are needed by modules.c, but we don't want
2138;; to move their real definition here because that would be unnatural.
2139;;
2140(define process-define-module #f)
2141(define process-use-modules #f)
2142(define module-export! #f)
2143(define default-duplicate-binding-procedures #f)
2144
2145;; This boots the module system. All bindings needed by modules.c
2146;; must have been defined by now.
296ff5e7 2147;;
bbd1d133
AW
2148(set-current-module the-root-module)
2149
2150
2151\f
2152
2153;; Now that modules are booted, give module-name its final definition.
2154;;
2155(define module-name
2156 (let ((accessor (record-accessor module-type 'name)))
2157 (lambda (mod)
2158 (or (accessor mod)
2159 (let ((name (list (gensym))))
cb67c838
AW
2160 ;; Name MOD and bind it in the module root so that it's visible to
2161 ;; `resolve-module'. This is important as `psyntax' stores module
2162 ;; names and relies on being able to `resolve-module' them.
bbd1d133 2163 (set-module-name! mod name)
9e0bfdba 2164 (nested-define-module! (resolve-module '() #f) name mod)
bbd1d133
AW
2165 (accessor mod))))))
2166
296ff5e7 2167(define (make-modules-in module name)
9e0bfdba
AW
2168 (or (nested-ref-module module name)
2169 (let ((m (make-module 31)))
2170 (set-module-kind! m 'directory)
2171 (set-module-name! m (append (module-name module) name))
2172 (nested-define-module! module name m)
2173 m)))
0f2d19dd 2174
296ff5e7
MV
2175(define (beautify-user-module! module)
2176 (let ((interface (module-public-interface module)))
2177 (if (or (not interface)
9b5a0d84
AW
2178 (eq? interface module))
2179 (let ((interface (make-module 31)))
2180 (set-module-name! interface (module-name module))
dca14012 2181 (set-module-version! interface (module-version module))
9b5a0d84
AW
2182 (set-module-kind! interface 'interface)
2183 (set-module-public-interface! module interface))))
296ff5e7 2184 (if (and (not (memq the-scm-module (module-uses module)))
9b5a0d84 2185 (not (eq? module the-root-module)))
608860a5
LC
2186 ;; Import the default set of bindings (from the SCM module) in MODULE.
2187 (module-use! module the-scm-module)))
432558b9 2188
dca14012 2189(define (version-matches? version-ref target)
dca14012
JG
2190 (define (sub-versions-match? v-refs t)
2191 (define (sub-version-matches? v-ref t)
befd1df9
AW
2192 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2193 (cond
2194 ((number? v-ref) (eqv? v-ref t))
2195 ((list? v-ref)
2196 (case (car v-ref)
2197 ((>=) (>= t (cadr v-ref)))
2198 ((<=) (<= t (cadr v-ref)))
2199 ((and) (and-map matches? (cdr v-ref)))
2200 ((or) (or-map matches? (cdr v-ref)))
2201 ((not) (not (matches? (cadr v-ref))))
2202 (else (error "Invalid sub-version reference" v-ref))))
2203 (else (error "Invalid sub-version reference" v-ref)))))
dca14012
JG
2204 (or (null? v-refs)
2205 (and (not (null? t))
2206 (sub-version-matches? (car v-refs) (car t))
2207 (sub-versions-match? (cdr v-refs) (cdr t)))))
befd1df9
AW
2208
2209 (let ((matches? (lambda (v) (version-matches? v target))))
2210 (or (null? version-ref)
2211 (case (car version-ref)
2212 ((and) (and-map matches? (cdr version-ref)))
2213 ((or) (or-map matches? (cdr version-ref)))
2214 ((not) (not (matches? (cadr version-ref))))
2215 (else (sub-versions-match? version-ref target))))))
dca14012 2216
f95f82f8
AW
2217(define (make-fresh-user-module)
2218 (let ((m (make-module)))
2219 (beautify-user-module! m)
2220 m))
2221
1f60d9d2
MD
2222;; NOTE: This binding is used in libguile/modules.c.
2223;;
53f84bc8 2224(define resolve-module
cb67c838
AW
2225 (let ((root (make-module)))
2226 (set-module-name! root '())
2227 ;; Define the-root-module as '(guile).
d58ccc66 2228 (module-define-submodule! root 'guile the-root-module)
cb67c838 2229
7e314766 2230 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
6b7d701e 2231 (let ((already (nested-ref-module root name)))
cb67c838 2232 (cond
d58ccc66 2233 ((and already
cb67c838
AW
2234 (or (not autoload) (module-public-interface already)))
2235 ;; A hit, a palpable hit.
e44d2e4d 2236 (if (and version
cb67c838
AW
2237 (not (version-matches? version (module-version already))))
2238 (error "incompatible module version already loaded" name))
2239 already)
2240 (autoload
2241 ;; Try to autoload the module, and recurse.
2242 (try-load-module name version)
7e314766 2243 (resolve-module name #f #:ensure ensure))
cb67c838 2244 (else
51b22dbb 2245 ;; No module found (or if one was, it had no public interface), and
7e314766
AW
2246 ;; we're not autoloading. Make an empty module if #:ensure is true.
2247 (or already
2248 (and ensure
2249 (make-modules-in root name)))))))))
cb67c838 2250
296ff5e7 2251
dca14012
JG
2252(define (try-load-module name version)
2253 (try-module-autoload name version))
0f2d19dd 2254
90847923
MD
2255(define (purify-module! module)
2256 "Removes bindings in MODULE which are inherited from the (guile) module."
2257 (let ((use-list (module-uses module)))
2258 (if (and (pair? use-list)
9b5a0d84
AW
2259 (eq? (car (last-pair use-list)) the-scm-module))
2260 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
90847923 2261
4eecfeb7 2262;; Return a module that is an interface to the module designated by
532cf805
MV
2263;; NAME.
2264;;
c614a00b 2265;; `resolve-interface' takes four keyword arguments:
532cf805
MV
2266;;
2267;; #:select SELECTION
2268;;
2269;; SELECTION is a list of binding-specs to be imported; A binding-spec
2270;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2271;; is the name in the used module and SEEN is the name in the using
2272;; module. Note that SEEN is also passed through RENAMER, below. The
2273;; default is to select all bindings. If you specify no selection but
4eecfeb7 2274;; a renamer, only the bindings that already exist in the used module
532cf805
MV
2275;; are made available in the interface. Bindings that are added later
2276;; are not picked up.
2277;;
c614a00b 2278;; #:hide BINDINGS
532cf805 2279;;
c614a00b 2280;; BINDINGS is a list of bindings which should not be imported.
f595ccfe
MD
2281;;
2282;; #:prefix PREFIX
2283;;
2284;; PREFIX is a symbol that will be appended to each exported name.
2285;; The default is to not perform any renaming.
532cf805 2286;;
c614a00b
MD
2287;; #:renamer RENAMER
2288;;
2289;; RENAMER is a procedure that takes a symbol and returns its new
2290;; name. The default is not perform any renaming.
2291;;
532cf805
MV
2292;; Signal "no code for module" error if module name is not resolvable
2293;; or its public interface is not available. Signal "no binding"
2294;; error if selected binding does not exist in the used module.
2295;;
36d58fc3
AW
2296(define* (resolve-interface name #:key
2297 (select #f)
2298 (hide '())
2299 (prefix #f)
2300 (renamer (if prefix
2301 (symbol-prefix-proc prefix)
2302 identity))
2303 version)
47aabe86 2304 (let* ((module (resolve-module name #t version #:ensure #f))
b622dec7
TTN
2305 (public-i (and module (module-public-interface module))))
2306 (and (or (not module) (not public-i))
2307 (error "no code for module" name))
c614a00b 2308 (if (and (not select) (null? hide) (eq? renamer identity))
b622dec7 2309 public-i
532cf805 2310 (let ((selection (or select (module-map (lambda (sym var) sym)
9b5a0d84 2311 public-i)))
b622dec7 2312 (custom-i (make-module 31)))
c614a00b 2313 (set-module-kind! custom-i 'custom-interface)
9b5a0d84
AW
2314 (set-module-name! custom-i name)
2315 ;; XXX - should use a lazy binder so that changes to the
2316 ;; used module are picked up automatically.
2317 (for-each (lambda (bspec)
2318 (let* ((direct? (symbol? bspec))
2319 (orig (if direct? bspec (car bspec)))
2320 (seen (if direct? bspec (cdr bspec)))
2321 (var (or (module-local-variable public-i orig)
2322 (module-local-variable module orig)
2323 (error
2324 ;; fixme: format manually for now
2325 (simple-format
2326 #f "no binding `~A' in module ~A"
2327 orig name)))))
2328 (if (memq orig hide)
2329 (set! hide (delq! orig hide))
2330 (module-add! custom-i
2331 (renamer seen)
2332 var))))
2333 selection)
2334 ;; Check that we are not hiding bindings which don't exist
2335 (for-each (lambda (binding)
2336 (if (not (module-local-variable public-i binding))
2337 (error
2338 (simple-format
2339 #f "no binding `~A' to hide in module ~A"
2340 binding name))))
2341 hide)
b622dec7 2342 custom-i))))
fb1b76f4
TTN
2343
2344(define (symbol-prefix-proc prefix)
2345 (lambda (symbol)
2346 (symbol-append prefix symbol)))
0f2d19dd 2347
482a28f9
MV
2348;; This function is called from "modules.c". If you change it, be
2349;; sure to update "modules.c" as well.
2350
0f2d19dd 2351(define (process-define-module args)
f8a502cb
TTN
2352 (let* ((module-id (car args))
2353 (module (resolve-module module-id #f))
2354 (kws (cdr args))
2355 (unrecognized (lambda (arg)
2356 (error "unrecognized define-module argument" arg))))
0f2d19dd 2357 (beautify-user-module! module)
0209ca9a 2358 (let loop ((kws kws)
1b92d94c
AW
2359 (reversed-interfaces '())
2360 (exports '())
2361 (re-exports '())
2362 (replacements '())
608860a5 2363 (autoloads '()))
e4da0740 2364
0209ca9a 2365 (if (null? kws)
1b92d94c
AW
2366 (call-with-deferred-observers
2367 (lambda ()
2368 (module-use-interfaces! module (reverse reversed-interfaces))
2369 (module-export! module exports)
2370 (module-replace! module replacements)
2371 (module-re-export! module re-exports)
608860a5
LC
2372 (if (not (null? autoloads))
2373 (apply module-autoload! module autoloads))))
1b92d94c
AW
2374 (case (car kws)
2375 ((#:use-module #:use-syntax)
2376 (or (pair? (cdr kws))
2377 (unrecognized kws))
13182603
AW
2378 (cond
2379 ((equal? (caadr kws) '(ice-9 syncase))
2380 (issue-deprecation-warning
2381 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
1b92d94c 2382 (loop (cddr kws)
13182603 2383 reversed-interfaces
1b92d94c
AW
2384 exports
2385 re-exports
2386 replacements
13182603
AW
2387 autoloads))
2388 (else
2389 (let* ((interface-args (cadr kws))
2390 (interface (apply resolve-interface interface-args)))
2391 (and (eq? (car kws) #:use-syntax)
2392 (or (symbol? (caar interface-args))
2393 (error "invalid module name for use-syntax"
2394 (car interface-args)))
2395 (set-module-transformer!
2396 module
2397 (module-ref interface
2398 (car (last-pair (car interface-args)))
2399 #f)))
2400 (loop (cddr kws)
2401 (cons interface reversed-interfaces)
2402 exports
2403 re-exports
2404 replacements
2405 autoloads)))))
1b92d94c
AW
2406 ((#:autoload)
2407 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2408 (unrecognized kws))
2409 (loop (cdddr kws)
608860a5 2410 reversed-interfaces
1b92d94c
AW
2411 exports
2412 re-exports
2413 replacements
608860a5
LC
2414 (let ((name (cadr kws))
2415 (bindings (caddr kws)))
2416 (cons* name bindings autoloads))))
1b92d94c
AW
2417 ((#:no-backtrace)
2418 (set-system-module! module #t)
2419 (loop (cdr kws) reversed-interfaces exports re-exports
608860a5 2420 replacements autoloads))
1b92d94c
AW
2421 ((#:pure)
2422 (purify-module! module)
2423 (loop (cdr kws) reversed-interfaces exports re-exports
608860a5 2424 replacements autoloads))
dca14012
JG
2425 ((#:version)
2426 (or (pair? (cdr kws))
2427 (unrecognized kws))
2428 (let ((version (cadr kws)))
2429 (set-module-version! module version)
2430 (set-module-version! (module-public-interface module) version))
2431 (loop (cddr kws) reversed-interfaces exports re-exports
2432 replacements autoloads))
1b92d94c
AW
2433 ((#:duplicates)
2434 (if (not (pair? (cdr kws)))
2435 (unrecognized kws))
2436 (set-module-duplicates-handlers!
2437 module
2438 (lookup-duplicates-handlers (cadr kws)))
2439 (loop (cddr kws) reversed-interfaces exports re-exports
608860a5 2440 replacements autoloads))
1b92d94c
AW
2441 ((#:export #:export-syntax)
2442 (or (pair? (cdr kws))
2443 (unrecognized kws))
2444 (loop (cddr kws)
2445 reversed-interfaces
2446 (append (cadr kws) exports)
2447 re-exports
2448 replacements
608860a5 2449 autoloads))
1b92d94c
AW
2450 ((#:re-export #:re-export-syntax)
2451 (or (pair? (cdr kws))
2452 (unrecognized kws))
2453 (loop (cddr kws)
2454 reversed-interfaces
2455 exports
2456 (append (cadr kws) re-exports)
2457 replacements
608860a5 2458 autoloads))
1b92d94c
AW
2459 ((#:replace #:replace-syntax)
2460 (or (pair? (cdr kws))
2461 (unrecognized kws))
2462 (loop (cddr kws)
2463 reversed-interfaces
2464 exports
2465 re-exports
2466 (append (cadr kws) replacements)
608860a5 2467 autoloads))
78f79f18
AW
2468 ((#:filename)
2469 (or (pair? (cdr kws))
2470 (unrecognized kws))
2471 (set-module-filename! module (cadr kws))
2472 (loop (cddr kws)
2473 reversed-interfaces
2474 exports
2475 re-exports
2476 replacements
2477 autoloads))
1b92d94c
AW
2478 (else
2479 (unrecognized kws)))))
db853761 2480 (run-hook module-defined-hook module)
0f2d19dd 2481 module))
71225060 2482
db853761
NJ
2483;; `module-defined-hook' is a hook that is run whenever a new module
2484;; is defined. Its members are called with one argument, the new
2485;; module.
2486(define module-defined-hook (make-hook 1))
2487
3d2ada2f
DH
2488\f
2489
71225060 2490;;; {Autoload}
3d2ada2f 2491;;;
71225060
MD
2492
2493(define (make-autoload-interface module name bindings)
2494 (let ((b (lambda (a sym definep)
9b5a0d84
AW
2495 (and (memq sym bindings)
2496 (let ((i (module-public-interface (resolve-module name))))
2497 (if (not i)
2498 (error "missing interface for module" name))
2499 (let ((autoload (memq a (module-uses module))))
2500 ;; Replace autoload-interface with actual interface if
2501 ;; that has not happened yet.
2502 (if (pair? autoload)
2503 (set-car! autoload i)))
2504 (module-local-variable i sym))))))
608860a5 2505 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
f905381d 2506 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
78f79f18 2507 (make-hash-table 0) #f #f #f)))
608860a5
LC
2508
2509(define (module-autoload! module . args)
2510 "Have @var{module} automatically load the module named @var{name} when one
2511of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2512list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2513module '(ice-9 q) '(make-q q-length))}."
2514 (let loop ((args args))
2515 (cond ((null? args)
2516 #t)
2517 ((null? (cdr args))
2518 (error "invalid name+binding autoload list" args))
2519 (else
2520 (let ((name (car args))
2521 (bindings (cadr args)))
2522 (module-use! module (make-autoload-interface module
2523 name bindings))
2524 (loop (cddr args)))))))
2525
71225060 2526
0f2d19dd 2527\f
3d2ada2f 2528
44cf1f0f 2529;;; {Autoloading modules}
3d2ada2f 2530;;;
0f2d19dd
JB
2531
2532(define autoloads-in-progress '())
2533
482a28f9
MV
2534;; This function is called from "modules.c". If you change it, be
2535;; sure to update "modules.c" as well.
2536
d9113d47 2537(define* (try-module-autoload module-name #:optional version)
0f2d19dd 2538 (let* ((reverse-name (reverse module-name))
9b5a0d84
AW
2539 (name (symbol->string (car reverse-name)))
2540 (dir-hint-module-name (reverse (cdr reverse-name)))
2541 (dir-hint (apply string-append
2542 (map (lambda (elt)
2543 (string-append (symbol->string elt) "/"))
2544 dir-hint-module-name))))
0209ca9a 2545 (resolve-module dir-hint-module-name #f)
0f2d19dd 2546 (and (not (autoload-done-or-in-progress? dir-hint name))
9b5a0d84
AW
2547 (let ((didit #f))
2548 (dynamic-wind
2549 (lambda () (autoload-in-progress! dir-hint name))
2550 (lambda ()
eddd16d7
AW
2551 (with-fluids ((current-reader #f))
2552 (save-module-excursion
2553 (lambda ()
39392995
AW
2554 ;; The initial environment when loading a module is a fresh
2555 ;; user module.
2556 (set-current-module (make-fresh-user-module))
e44d2e4d
AW
2557 ;; Here we could allow some other search strategy (other than
2558 ;; primitive-load-path), for example using versions encoded
2559 ;; into the file system -- but then we would have to figure
2560 ;; out how to locate the compiled file, do autocompilation,
2561 ;; etc. Punt for now, and don't use versions when locating
2562 ;; the file.
2563 (primitive-load-path (in-vicinity dir-hint name) #f)
eddd16d7 2564 (set! didit #t)))))
9b5a0d84
AW
2565 (lambda () (set-autoloaded! dir-hint name didit)))
2566 didit))))
0f2d19dd 2567
71225060 2568\f
3d2ada2f
DH
2569
2570;;; {Dynamic linking of modules}
2571;;;
d0cbd20c 2572
0f2d19dd
JB
2573(define autoloads-done '((guile . guile)))
2574
2575(define (autoload-done-or-in-progress? p m)
2576 (let ((n (cons p m)))
2577 (->bool (or (member n autoloads-done)
9b5a0d84 2578 (member n autoloads-in-progress)))))
0f2d19dd
JB
2579
2580(define (autoload-done! p m)
2581 (let ((n (cons p m)))
2582 (set! autoloads-in-progress
9b5a0d84 2583 (delete! n autoloads-in-progress))
0f2d19dd 2584 (or (member n autoloads-done)
9b5a0d84 2585 (set! autoloads-done (cons n autoloads-done)))))
0f2d19dd
JB
2586
2587(define (autoload-in-progress! p m)
2588 (let ((n (cons p m)))
2589 (set! autoloads-done
9b5a0d84 2590 (delete! n autoloads-done))
0f2d19dd
JB
2591 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2592
2593(define (set-autoloaded! p m done?)
2594 (if done?
2595 (autoload-done! p m)
2596 (let ((n (cons p m)))
9b5a0d84
AW
2597 (set! autoloads-done (delete! n autoloads-done))
2598 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
0f2d19dd 2599
0f2d19dd
JB
2600\f
2601
83b38198 2602;;; {Run-time options}
3d2ada2f 2603;;;
83b38198 2604
122f296d
AW
2605(define-syntax define-option-interface
2606 (syntax-rules ()
2607 ((_ (interface (options enable disable) (option-set!)))
2608 (begin
2609 (define options
2610 (case-lambda
2611 (() (interface))
2612 ((arg)
2613 (if (list? arg)
2614 (begin (interface arg) (interface))
2615 (for-each
2616 (lambda (option)
2617 (apply (lambda (name value documentation)
2618 (display name)
2619 (if (< (string-length (symbol->string name)) 8)
2620 (display #\tab))
2621 (display #\tab)
2622 (display value)
2623 (display #\tab)
2624 (display documentation)
2625 (newline))
2626 option))
2627 (interface #t))))))
2628 (define (enable . flags)
2629 (interface (append flags (interface)))
2630 (interface))
2631 (define (disable . flags)
2632 (let ((options (interface)))
2633 (for-each (lambda (flag) (set! options (delq! flag options)))
2634 flags)
2635 (interface options)
2636 (interface)))
2637 (define-syntax option-set!
2638 (syntax-rules ()
2639 ((_ opt val)
2640 (options (append (options) (list 'opt val))))))))))
e9bab9df 2641
e9bab9df
DH
2642(define-option-interface
2643 (debug-options-interface
2644 (debug-options debug-enable debug-disable)
2645 (debug-set!)))
2646
e9bab9df
DH
2647(define-option-interface
2648 (read-options-interface
2649 (read-options read-enable read-disable)
2650 (read-set!)))
2651
2652(define-option-interface
2653 (print-options-interface
2654 (print-options print-enable print-disable)
2655 (print-set!)))
83b38198
MD
2656
2657\f
2658
410e83c0
AW
2659;;; {The Unspecified Value}
2660;;;
2661;;; Currently Guile represents unspecified values via one particular value,
2662;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2663;;; future if we could replace this with a return of 0 values, though.
9346b857 2664;;;
410e83c0
AW
2665
2666(define-syntax *unspecified*
2667 (identifier-syntax (if #f #f)))
2668
2669(define (unspecified? v) (eq? v *unspecified*))
2670
2671
2672\f
2673
0f2d19dd
JB
2674;;; {Running Repls}
2675;;;
2676
652f48c0 2677(define *repl-stack* (make-fluid))
1fdd5bec 2678
9346b857
AW
2679;; Programs can call `batch-mode?' to see if they are running as part of a
2680;; script or if they are running interactively. REPL implementations ensure that
2681;; `batch-mode?' returns #f during their extent.
2682;;
1fdd5bec 2683(define (batch-mode?)
652f48c0 2684 (null? (or (fluid-ref *repl-stack*) '())))
1fdd5bec 2685
9346b857 2686;; Programs can re-enter batch mode, for example after a fork, by calling
0feb833d
AW
2687;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
2688;; to abort to the outermost prompt, and call a thunk there.
1fdd5bec 2689;;
9346b857 2690(define (ensure-batch-mode!)
9d2136ba 2691 (set! batch-mode? (lambda () #t)))
4bbbcd5c 2692
0f2d19dd
JB
2693(define (quit . args)
2694 (apply throw 'quit args))
2695
7950df7c
GH
2696(define exit quit)
2697
0f2d19dd
JB
2698(define (gc-run-time)
2699 (cdr (assq 'gc-time-taken (gc-stats))))
2700
8942e7a1
AW
2701(define abort-hook (make-hook))
2702(define before-error-hook (make-hook))
2703(define after-error-hook (make-hook))
2704(define before-backtrace-hook (make-hook))
2705(define after-backtrace-hook (make-hook))
2706
3e3cec45
MD
2707(define before-read-hook (make-hook))
2708(define after-read-hook (make-hook))
870777d7
KN
2709(define before-eval-hook (make-hook 1))
2710(define after-eval-hook (make-hook 1))
2711(define before-print-hook (make-hook 1))
2712(define after-print-hook (make-hook 1))
1c6cd8e8 2713
c592de96
AW
2714;;; This hook is run at the very end of an interactive session.
2715;;;
2716(define exit-hook (make-hook))
2717
dc5c2038
MD
2718;;; The default repl-reader function. We may override this if we've
2719;;; the readline library.
2720(define repl-reader
17ee350c 2721 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
0becb8f3
AW
2722 (if (not (char-ready?))
2723 (display (if (string? prompt) prompt (prompt))))
dc5c2038 2724 (force-output)
04efd24d 2725 (run-hook before-read-hook)
17ee350c 2726 ((or reader read) (current-input-port))))
dc5c2038 2727
0f2d19dd 2728
0f2d19dd 2729\f
3d2ada2f 2730
44cf1f0f 2731;;; {IOTA functions: generating lists of numbers}
3d2ada2f 2732;;;
0f2d19dd 2733
e69cd299
MD
2734(define (iota n)
2735 (let loop ((count (1- n)) (result '()))
2736 (if (< count 0) result
2737 (loop (1- count) (cons count result)))))
0f2d19dd
JB
2738
2739\f
3d2ada2f 2740
773abfbb
KR
2741;;; {While}
2742;;;
2743;;; with `continue' and `break'.
2744;;;
2745
10e69149
AW
2746;; The inliner will remove the prompts at compile-time if it finds that
2747;; `continue' or `break' are not used.
2748;;
2749(define-syntax while
2750 (lambda (x)
2751 (syntax-case x ()
2752 ((while cond body ...)
2753 #`(let ((break-tag (make-prompt-tag "break"))
2754 (continue-tag (make-prompt-tag "continue")))
2755 (call-with-prompt
2756 break-tag
2757 (lambda ()
2758 (define-syntax #,(datum->syntax #'while 'break)
2759 (lambda (x)
2760 (syntax-case x ()
2761 ((_)
2762 #'(abort-to-prompt break-tag))
2763 ((_ . args)
2764 (syntax-violation 'break "too many arguments" x))
2765 (_
2766 #'(lambda ()
2767 (abort-to-prompt break-tag))))))
2768 (let lp ()
2769 (call-with-prompt
2770 continue-tag
2771 (lambda ()
2772 (define-syntax #,(datum->syntax #'while 'continue)
2773 (lambda (x)
2774 (syntax-case x ()
2775 ((_)
2776 #'(abort-to-prompt continue-tag))
2777 ((_ . args)
2778 (syntax-violation 'continue "too many arguments" x))
2779 (_
2780 #'(lambda args
2781 (apply abort-to-prompt continue-tag args))))))
2782 (do () ((not cond)) body ...))
2783 (lambda (k) (lp)))))
2784 (lambda (k)
2785 #t)))))))
5578a53f 2786
773abfbb 2787
0f2d19dd 2788\f
3d2ada2f 2789
0f2d19dd
JB
2790;;; {Module System Macros}
2791;;;
2792
532cf805
MV
2793;; Return a list of expressions that evaluate to the appropriate
2794;; arguments for resolve-interface according to SPEC.
2795
1fdd5bec
AW
2796(eval-when (compile)
2797 (if (memq 'prefix (read-options))
2798 (error "boot-9 must be compiled with #:kw, not :kw")))
1a1a10d3 2799
532cf805
MV
2800(define (keyword-like-symbol->keyword sym)
2801 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2802
074e036e
AW
2803;; FIXME: we really need to clean up the guts of the module system.
2804;; We can compile to something better than process-define-module.
1fdd5bec 2805;;
074e036e
AW
2806(define-syntax define-module
2807 (lambda (x)
2808 (define (keyword-like? stx)
2809 (let ((dat (syntax->datum stx)))
2810 (and (symbol? dat)
2811 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2812 (define (->keyword sym)
2813 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2814
2815 (define (quotify-iface args)
2816 (let loop ((in args) (out '()))
2817 (syntax-case in ()
2818 (() (reverse! out))
2819 ;; The user wanted #:foo, but wrote :foo. Fix it.
2820 ((sym . in) (keyword-like? #'sym)
2821 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2822 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2823 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2824 ((#:renamer renamer . in)
2825 (loop #'in (cons* #'renamer #:renamer out)))
2826 ((kw val . in)
2827 (loop #'in (cons* #''val #'kw out))))))
2828
2829 (define (quotify args)
2830 ;; Just quote everything except #:use-module and #:use-syntax. We
2831 ;; need to know about all arguments regardless since we want to turn
2832 ;; symbols that look like keywords into real keywords, and the
2833 ;; keyword args in a define-module form are not regular
2834 ;; (i.e. no-backtrace doesn't take a value).
2835 (let loop ((in args) (out '()))
2836 (syntax-case in ()
2837 (() (reverse! out))
2838 ;; The user wanted #:foo, but wrote :foo. Fix it.
2839 ((sym . in) (keyword-like? #'sym)
2840 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2841 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2842 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2843 ((#:no-backtrace . in)
2844 (loop #'in (cons #:no-backtrace out)))
2845 ((#:pure . in)
2846 (loop #'in (cons #:pure out)))
2847 ((kw)
2848 (syntax-violation 'define-module "keyword arg without value" x #'kw))
2849 ((use-module (name name* ...) . in)
2850 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2851 (and-map symbol? (syntax->datum #'(name name* ...))))
2852 (loop #'in
2853 (cons* #''((name name* ...))
2854 #'use-module
2855 out)))
2856 ((use-module ((name name* ...) arg ...) . in)
2857 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2858 (and-map symbol? (syntax->datum #'(name name* ...))))
2859 (loop #'in
2860 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
2861 #'use-module
2862 out)))
2863 ((#:autoload name bindings . in)
2864 (loop #'in (cons* #''bindings #''name #:autoload out)))
2865 ((kw val . in)
2866 (loop #'in (cons* #''val #'kw out))))))
2867
2868 (syntax-case x ()
2869 ((_ (name name* ...) arg ...)
2870 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
d9b1c71a 2871 #'(eval-when (eval load compile expand)
074e036e 2872 (let ((m (process-define-module
78f79f18
AW
2873 (list '(name name* ...)
2874 #:filename (assq-ref
2875 (or (current-source-location) '())
2876 'filename)
2877 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
AW
3347(define-module (guile-user)
3348 #:autoload (system base compile) (compile))
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