don't unconditionally restore signals in ensure-batch-mode!
[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;;;
519;;; Depends on: defmacro
520;;;
521
522(defmacro begin-deprecated forms
523 (if (include-deprecated-features)
1b68d041 524 `(begin ,@forms)
b1e93821 525 `(begin)))
0f2d19dd
JB
526
527\f
3d2ada2f 528
79451588 529;;; {Trivial Functions}
0f2d19dd 530;;;
79451588 531
6b08d75b 532(define (identity x) x)
132e5fac 533(define (and=> value procedure) (and value (procedure value)))
e8ed460e 534(define call/cc call-with-current-continuation)
79451588 535
27ae3651
AW
536(define-syntax false-if-exception
537 (syntax-rules ()
538 ((_ expr)
539 (catch #t
540 (lambda () expr)
541 (lambda (k . args) #f)))))
3d2ada2f
DH
542
543\f
544
545;;; {General Properties}
546;;;
547
02b582ce
AW
548;; Properties are a lispy way to associate random info with random objects.
549;; Traditionally properties are implemented as an alist or a plist actually
550;; pertaining to the object in question.
551;;
552;; These "object properties" have the advantage that they can be associated with
553;; any object, even if the object has no plist. Object properties are good when
554;; you are extending pre-existing objects in unexpected ways. They also present
555;; a pleasing, uniform procedure-with-setter interface. But if you have a data
556;; type that always has properties, it's often still best to store those
557;; properties within the object itself.
3d2ada2f
DH
558
559(define (make-object-property)
560 (let ((prop (primitive-make-property #f)))
561 (make-procedure-with-setter
562 (lambda (obj) (primitive-property-ref prop obj))
563 (lambda (obj val) (primitive-property-set! prop obj val)))))
564
0f2d19dd 565\f
6b08d75b 566
0f2d19dd
JB
567;;; {Symbol Properties}
568;;;
569
02b582ce
AW
570;;; Symbol properties are something you see in old Lisp code. In most current
571;;; Guile code, symbols are not used as a data structure -- they are used as
572;;; keys into other data structures.
573
0f2d19dd
JB
574(define (symbol-property sym prop)
575 (let ((pair (assoc prop (symbol-pref sym))))
576 (and pair (cdr pair))))
577
578(define (set-symbol-property! sym prop val)
579 (let ((pair (assoc prop (symbol-pref sym))))
580 (if pair
9b5a0d84
AW
581 (set-cdr! pair val)
582 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
0f2d19dd
JB
583
584(define (symbol-property-remove! sym prop)
585 (let ((pair (assoc prop (symbol-pref sym))))
586 (if pair
9b5a0d84 587 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
0f2d19dd
JB
588
589\f
1e531c3a 590
0f2d19dd
JB
591;;; {Arrays}
592;;;
593
2042e178
MV
594(define (array-shape a)
595 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
596 (array-dimensions a)))
0f2d19dd
JB
597
598\f
3d2ada2f 599
0f2d19dd
JB
600;;; {Keywords}
601;;;
602
010b159f
AW
603;;; It's much better if you can use lambda* / define*, of course.
604
0f2d19dd
JB
605(define (kw-arg-ref args kw)
606 (let ((rem (member kw args)))
607 (and rem (pair? (cdr rem)) (cadr rem))))
608
609\f
fa7e9274 610
9f9aa47b 611;;; {Structs}
3d2ada2f 612;;;
fa7e9274
MV
613
614(define (struct-layout s)
9f9aa47b 615 (struct-ref (struct-vtable s) vtable-index-layout))
fa7e9274
MV
616
617\f
d7faeb2e 618
0f2d19dd
JB
619;;; {Records}
620;;;
621
fa7e9274
MV
622;; Printing records: by default, records are printed as
623;;
624;; #<type-name field1: val1 field2: val2 ...>
625;;
626;; You can change that by giving a custom printing function to
627;; MAKE-RECORD-TYPE (after the list of field symbols). This function
628;; will be called like
629;;
630;; (<printer> object port)
631;;
632;; It should print OBJECT to PORT.
633
cf8f1a90 634(define (inherit-print-state old-port new-port)
8a30733e
MD
635 (if (get-print-state old-port)
636 (port-with-print-state new-port (get-print-state old-port))
cf8f1a90
MV
637 new-port))
638
e31f22eb 639;; 0: type-name, 1: fields, 2: constructor
20edfbbd 640(define record-type-vtable
e31f22eb
AW
641 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
642 ;; that we need to expose the bare vtable-vtable to Scheme.
643 (make-vtable-vtable "prprpw" 0
9b5a0d84
AW
644 (lambda (s p)
645 (cond ((eq? s record-type-vtable)
646 (display "#<record-type-vtable>" p))
647 (else
648 (display "#<record-type " p)
649 (display (record-type-name s) p)
650 (display ">" p))))))
0f2d19dd
JB
651
652(define (record-type? obj)
653 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
654
b2669c41 655(define* (make-record-type type-name fields #:optional printer)
31ac29b6 656 ;; Pre-generate constructors for nfields < 20.
e31f22eb
AW
657 (define-syntax make-constructor
658 (lambda (x)
659 (define *max-static-argument-count* 20)
660 (define (make-formals n)
661 (let lp ((i 0))
662 (if (< i n)
663 (cons (datum->syntax
664 x
665 (string->symbol
666 (string (integer->char (+ (char->integer #\a) i)))))
667 (lp (1+ i)))
668 '())))
669 (syntax-case x ()
670 ((_ rtd exp) (not (identifier? #'exp))
671 #'(let ((n exp))
672 (make-constructor rtd n)))
673 ((_ rtd nfields)
674 #`(case nfields
675 #,@(let lp ((n 0))
676 (if (< n *max-static-argument-count*)
677 (cons (with-syntax (((formal ...) (make-formals n))
678 (n n))
679 #'((n)
680 (lambda (formal ...)
681 (make-struct rtd 0 formal ...))))
682 (lp (1+ n)))
683 '()))
684 (else
685 (lambda args
686 (if (= (length args) nfields)
687 (apply make-struct rtd 0 args)
688 (scm-error 'wrong-number-of-args
689 (format #f "make-~a" type-name)
690 "Wrong number of arguments" '() #f)))))))))
691
51797cec
AW
692 (define (default-record-printer s p)
693 (display "#<" p)
694 (display (record-type-name (record-type-descriptor s)) p)
695 (let loop ((fields (record-type-fields (record-type-descriptor s)))
696 (off 0))
697 (cond
698 ((not (null? fields))
699 (display " " p)
700 (display (car fields) p)
701 (display ": " p)
702 (display (struct-ref s off) p)
703 (loop (cdr fields) (+ 1 off)))))
704 (display ">" p))
705
e31f22eb
AW
706 (let ((rtd (make-struct record-type-vtable 0
707 (make-struct-layout
708 (apply string-append
709 (map (lambda (f) "pw") fields)))
b2669c41 710 (or printer default-record-printer)
e31f22eb
AW
711 type-name
712 (copy-tree fields))))
713 (struct-set! rtd (+ vtable-offset-user 2)
714 (make-constructor rtd (length fields)))
51797cec
AW
715 ;; Temporary solution: Associate a name to the record type descriptor
716 ;; so that the object system can create a wrapper class for it.
e31f22eb
AW
717 (set-struct-vtable-name! rtd (if (symbol? type-name)
718 type-name
719 (string->symbol type-name)))
720 rtd))
0f2d19dd
JB
721
722(define (record-type-name obj)
723 (if (record-type? obj)
9f9aa47b 724 (struct-ref obj vtable-offset-user)
0f2d19dd
JB
725 (error 'not-a-record-type obj)))
726
727(define (record-type-fields obj)
728 (if (record-type? obj)
9f9aa47b 729 (struct-ref obj (+ 1 vtable-offset-user))
0f2d19dd
JB
730 (error 'not-a-record-type obj)))
731
d44a0d12
AW
732(define* (record-constructor rtd #:optional field-names)
733 (if (not field-names)
e31f22eb 734 (struct-ref rtd (+ 2 vtable-offset-user))
d44a0d12
AW
735 (primitive-eval
736 `(lambda ,field-names
737 (make-struct ',rtd 0 ,@(map (lambda (f)
738 (if (memq f field-names)
739 f
740 #f))
741 (record-type-fields rtd)))))))
3bf27608 742
0f2d19dd
JB
743(define (record-predicate rtd)
744 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
745
3ba9acb1 746(define (%record-type-error rtd obj) ;; private helper
afc4ccd4
KR
747 (or (eq? rtd (record-type-descriptor obj))
748 (scm-error 'wrong-type-arg "%record-type-check"
9b5a0d84
AW
749 "Wrong type record (want `~S'): ~S"
750 (list (record-type-name rtd) obj)
751 #f)))
afc4ccd4 752
0f2d19dd 753(define (record-accessor rtd field-name)
3bf27608 754 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 755 (if (not pos)
9b5a0d84 756 (error 'no-such-field field-name))
3bf27608
AW
757 (lambda (obj)
758 (if (eq? (struct-vtable obj) rtd)
759 (struct-ref obj pos)
760 (%record-type-error rtd obj)))))
0f2d19dd
JB
761
762(define (record-modifier rtd field-name)
3bf27608 763 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 764 (if (not pos)
9b5a0d84 765 (error 'no-such-field field-name))
3bf27608
AW
766 (lambda (obj val)
767 (if (eq? (struct-vtable obj) rtd)
768 (struct-set! obj pos val)
769 (%record-type-error rtd obj)))))
0f2d19dd
JB
770
771(define (record? obj)
772 (and (struct? obj) (record-type? (struct-vtable obj))))
773
774(define (record-type-descriptor obj)
775 (if (struct? obj)
776 (struct-vtable obj)
777 (error 'not-a-record obj)))
778
21ed9efe
MD
779(provide 'record)
780
0f2d19dd 781\f
3d2ada2f 782
0f2d19dd
JB
783;;; {Booleans}
784;;;
785
786(define (->bool x) (not (not x)))
787
788\f
3d2ada2f 789
0f2d19dd
JB
790;;; {Symbols}
791;;;
792
793(define (symbol-append . args)
06f0414c 794 (string->symbol (apply string-append (map symbol->string args))))
0f2d19dd
JB
795
796(define (list->symbol . args)
797 (string->symbol (apply list->string args)))
798
799(define (symbol . args)
800 (string->symbol (apply string args)))
801
0f2d19dd 802\f
3d2ada2f 803
0f2d19dd
JB
804;;; {Lists}
805;;;
806
807(define (list-index l k)
808 (let loop ((n 0)
9b5a0d84 809 (l l))
0f2d19dd 810 (and (not (null? l))
9b5a0d84
AW
811 (if (eq? (car l) k)
812 n
813 (loop (+ n 1) (cdr l))))))
0f2d19dd 814
1729d8ff 815\f
3d2ada2f 816
52cfc69b 817(if (provided? 'posix)
1e6ebf54 818 (primitive-load-path "ice-9/posix"))
6fa8995c 819
52cfc69b 820(if (provided? 'socket)
1e6ebf54 821 (primitive-load-path "ice-9/networking"))
3afb28ce 822
f3197274 823;; For reference, Emacs file-exists-p uses stat in this same way.
6fa8995c 824(define file-exists?
52cfc69b 825 (if (provided? 'posix)
6fa8995c 826 (lambda (str)
9b5a0d84 827 (->bool (stat str #f)))
6fa8995c 828 (lambda (str)
9b5a0d84
AW
829 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
830 (lambda args #f))))
831 (if port (begin (close-port port) #t)
832 #f)))))
6fa8995c
GH
833
834(define file-is-directory?
52cfc69b 835 (if (provided? 'posix)
6fa8995c 836 (lambda (str)
9b5a0d84 837 (eq? (stat:type (stat str)) 'directory))
6fa8995c 838 (lambda (str)
9b5a0d84
AW
839 (let ((port (catch 'system-error
840 (lambda () (open-file (string-append str "/.")
841 OPEN_READ))
842 (lambda args #f))))
843 (if port (begin (close-port port) #t)
844 #f)))))
0f2d19dd 845
019ac1c9
MV
846(define (system-error-errno args)
847 (if (eq? (car args) 'system-error)
848 (car (list-ref args 4))
849 #f))
850
0f2d19dd 851\f
3d2ada2f 852
0f2d19dd
JB
853;;; {Error Handling}
854;;;
855
4eeaf67c
AW
856(define error
857 (case-lambda
858 (()
4eeaf67c
AW
859 (scm-error 'misc-error #f "?" #f #f))
860 ((message . args)
4eeaf67c
AW
861 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
862 (scm-error 'misc-error #f msg (cons message args) #f)))))
be2d2c70 863
0f2d19dd 864\f
bce074ee 865
b38507c1
AW
866;;; {Time Structures}
867;;;
868
708bf0f3
GH
869(define (tm:sec obj) (vector-ref obj 0))
870(define (tm:min obj) (vector-ref obj 1))
871(define (tm:hour obj) (vector-ref obj 2))
872(define (tm:mday obj) (vector-ref obj 3))
873(define (tm:mon obj) (vector-ref obj 4))
874(define (tm:year obj) (vector-ref obj 5))
875(define (tm:wday obj) (vector-ref obj 6))
876(define (tm:yday obj) (vector-ref obj 7))
877(define (tm:isdst obj) (vector-ref obj 8))
878(define (tm:gmtoff obj) (vector-ref obj 9))
879(define (tm:zone obj) (vector-ref obj 10))
880
881(define (set-tm:sec obj val) (vector-set! obj 0 val))
882(define (set-tm:min obj val) (vector-set! obj 1 val))
883(define (set-tm:hour obj val) (vector-set! obj 2 val))
884(define (set-tm:mday obj val) (vector-set! obj 3 val))
885(define (set-tm:mon obj val) (vector-set! obj 4 val))
886(define (set-tm:year obj val) (vector-set! obj 5 val))
887(define (set-tm:wday obj val) (vector-set! obj 6 val))
888(define (set-tm:yday obj val) (vector-set! obj 7 val))
889(define (set-tm:isdst obj val) (vector-set! obj 8 val))
890(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
891(define (set-tm:zone obj val) (vector-set! obj 10 val))
892
6afcd3b2
GH
893(define (tms:clock obj) (vector-ref obj 0))
894(define (tms:utime obj) (vector-ref obj 1))
895(define (tms:stime obj) (vector-ref obj 2))
896(define (tms:cutime obj) (vector-ref obj 3))
897(define (tms:cstime obj) (vector-ref obj 4))
898
b38507c1
AW
899\f
900
901;;; {File Descriptors and Ports}
902;;;
903
1334c61a 904(define file-position ftell)
52c9a338
AW
905(define* (file-set-position port offset #:optional (whence SEEK_SET))
906 (seek port offset whence))
8b13c6b3 907
e38303a2
GH
908(define (move->fdes fd/port fd)
909 (cond ((integer? fd/port)
9b5a0d84
AW
910 (dup->fdes fd/port fd)
911 (close fd/port)
912 fd)
913 (else
914 (primitive-move->fdes fd/port fd)
915 (set-port-revealed! fd/port 1)
916 fd/port)))
8b13c6b3
GH
917
918(define (release-port-handle port)
919 (let ((revealed (port-revealed port)))
920 (if (> revealed 0)
9b5a0d84 921 (set-port-revealed! port (- revealed 1)))))
0f2d19dd 922
02851b26
AW
923(define dup->port
924 (case-lambda
925 ((port/fd mode)
926 (fdopen (dup->fdes port/fd) mode))
927 ((port/fd mode new-fd)
928 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
929 (set-port-revealed! port 1)
930 port))))
931
932(define dup->inport
933 (case-lambda
934 ((port/fd)
935 (dup->port port/fd "r"))
936 ((port/fd new-fd)
937 (dup->port port/fd "r" new-fd))))
938
939(define dup->outport
940 (case-lambda
941 ((port/fd)
942 (dup->port port/fd "w"))
943 ((port/fd new-fd)
944 (dup->port port/fd "w" new-fd))))
945
946(define dup
947 (case-lambda
948 ((port/fd)
949 (if (integer? port/fd)
950 (dup->fdes port/fd)
951 (dup->port port/fd (port-mode port/fd))))
952 ((port/fd new-fd)
953 (if (integer? port/fd)
954 (dup->fdes port/fd new-fd)
955 (dup->port port/fd (port-mode port/fd) new-fd)))))
e38303a2
GH
956
957(define (duplicate-port port modes)
958 (dup->port port modes))
959
960(define (fdes->inport fdes)
961 (let loop ((rest-ports (fdes->ports fdes)))
962 (cond ((null? rest-ports)
9b5a0d84
AW
963 (let ((result (fdopen fdes "r")))
964 (set-port-revealed! result 1)
965 result))
966 ((input-port? (car rest-ports))
967 (set-port-revealed! (car rest-ports)
968 (+ (port-revealed (car rest-ports)) 1))
969 (car rest-ports))
970 (else
971 (loop (cdr rest-ports))))))
e38303a2
GH
972
973(define (fdes->outport fdes)
974 (let loop ((rest-ports (fdes->ports fdes)))
975 (cond ((null? rest-ports)
9b5a0d84
AW
976 (let ((result (fdopen fdes "w")))
977 (set-port-revealed! result 1)
978 result))
979 ((output-port? (car rest-ports))
980 (set-port-revealed! (car rest-ports)
981 (+ (port-revealed (car rest-ports)) 1))
982 (car rest-ports))
983 (else
984 (loop (cdr rest-ports))))))
e38303a2
GH
985
986(define (port->fdes port)
987 (set-port-revealed! port (+ (port-revealed port) 1))
988 (fileno port))
989
956055a9
GH
990(define (setenv name value)
991 (if value
992 (putenv (string-append name "=" value))
993 (putenv name)))
994
5c1254da
MV
995(define (unsetenv name)
996 "Remove the entry for NAME from the environment."
997 (putenv name))
998
0f2d19dd 999\f
3d2ada2f 1000
0f2d19dd
JB
1001;;; {Load Paths}
1002;;;
1003
3cab8392
JB
1004(define (in-vicinity vicinity file)
1005 (let ((tail (let ((len (string-length vicinity)))
9b5a0d84
AW
1006 (if (zero? len)
1007 #f
1008 (string-ref vicinity (- len 1))))))
3cab8392 1009 (string-append vicinity
9b5a0d84
AW
1010 (if (or (not tail)
1011 (eq? tail #\/))
1012 ""
1013 "/")
1014 file)))
02ceadb8 1015
0f2d19dd 1016\f
3d2ada2f 1017
ef00e7f4 1018;;; {Help for scm_shell}
3d2ada2f 1019;;;
ef00e7f4
JB
1020;;; The argument-processing code used by Guile-based shells generates
1021;;; Scheme code based on the argument list. This page contains help
1022;;; functions for the code it generates.
3d2ada2f 1023;;;
ef00e7f4 1024
ef00e7f4
JB
1025(define (command-line) (program-arguments))
1026
5aa7fe69
JB
1027;; This is mostly for the internal use of the code generated by
1028;; scm_compile_shell_switches.
eef6519b
MV
1029
1030(define (turn-on-debugging)
1031 (debug-enable 'debug)
1032 (debug-enable 'backtrace)
1033 (read-enable 'positions))
4eecfeb7 1034
ef00e7f4 1035(define (load-user-init)
1f08acd9 1036 (let* ((home (or (getenv "HOME")
9b5a0d84
AW
1037 (false-if-exception (passwd:dir (getpwuid (getuid))))
1038 "/")) ;; fallback for cygwin etc.
1039 (init-file (in-vicinity home ".guile")))
1f08acd9 1040 (if (file-exists? init-file)
9b5a0d84 1041 (primitive-load init-file))))
ef00e7f4
JB
1042
1043\f
3d2ada2f 1044
107139ea
AW
1045;;; {The interpreter stack}
1046;;;
1047
06dcb9df 1048;; %stacks defined in stacks.c
a6cd3555 1049(define (%start-stack tag thunk)
8fc43b12
AW
1050 (let ((prompt-tag (make-prompt-tag "start-stack")))
1051 (call-with-prompt
1052 prompt-tag
1053 (lambda ()
1054 (with-fluids ((%stacks (acons tag prompt-tag
1055 (or (fluid-ref %stacks) '()))))
1056 (thunk)))
1057 (lambda (k . args)
a6cd3555
AW
1058 (%start-stack tag (lambda () (apply k args)))))))
1059(define-syntax start-stack
1060 (syntax-rules ()
1061 ((_ tag exp)
1062 (%start-stack tag (lambda () exp)))))
107139ea
AW
1063
1064\f
1065
a06181a2 1066;;; {Loading by paths}
3d2ada2f 1067;;;
a06181a2
JB
1068
1069;;; Load a Scheme source file named NAME, searching for it in the
1070;;; directories listed in %load-path, and applying each of the file
1071;;; name extensions listed in %load-extensions.
1072(define (load-from-path name)
1073 (start-stack 'load-stack
9b5a0d84 1074 (primitive-load-path name)))
0f2d19dd 1075
85e95b47
AW
1076(define %load-verbosely #f)
1077(define (assert-load-verbosity v) (set! %load-verbosely v))
1078
1079(define (%load-announce file)
1080 (if %load-verbosely
1081 (with-output-to-port (current-error-port)
9b5a0d84
AW
1082 (lambda ()
1083 (display ";;; ")
1084 (display "loading ")
1085 (display file)
1086 (newline)
1087 (force-output)))))
85e95b47
AW
1088
1089(set! %load-hook %load-announce)
1090
d6e70467 1091(define* (load name #:optional reader)
1ab3976e
AW
1092 ;; Returns the .go file corresponding to `name'. Does not search load
1093 ;; paths, only the fallback path. If the .go file is missing or out of
1094 ;; date, and autocompilation is enabled, will try autocompilation, just
1095 ;; as primitive-load-path does internally. primitive-load is
1096 ;; unaffected. Returns #f if autocompilation failed or was disabled.
04af4c4c
AW
1097 ;;
1098 ;; NB: Unless we need to compile the file, this function should not cause
1099 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1100 ;; partially duplicates functionality from (system base compile).
1101 (define (compiled-file-name canon-path)
1102 (and %compile-fallback-path
1103 (string-append
1104 %compile-fallback-path
1105 ;; no need for '/' separator here, canon-path is absolute
1106 canon-path
1107 (cond ((or (null? %load-compiled-extensions)
1108 (string-null? (car %load-compiled-extensions)))
1109 (warn "invalid %load-compiled-extensions"
1110 %load-compiled-extensions)
1111 ".go")
1112 (else (car %load-compiled-extensions))))))
1113 (define (fresh-compiled-file-name go-path)
1ab3976e
AW
1114 (catch #t
1115 (lambda ()
04af4c4c
AW
1116 (let* ((scmstat (stat name))
1117 (gostat (stat go-path #f)))
1ab3976e 1118 (if (and gostat (= (stat:mtime gostat) (stat:mtime 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;;
0f2d19dd
JB
1463(define make-module
1464 (lambda args
0f2d19dd 1465
8b718458 1466 (define (parse-arg index default)
9b5a0d84
AW
1467 (if (> (length args) index)
1468 (list-ref args index)
1469 default))
8b718458 1470
608860a5
LC
1471 (define %default-import-size
1472 ;; Typical number of imported bindings actually used by a module.
1473 600)
1474
8b718458 1475 (if (> (length args) 3)
9b5a0d84 1476 (error "Too many args to make-module." args))
0f2d19dd 1477
231a4ea8 1478 (let ((size (parse-arg 0 31))
9b5a0d84
AW
1479 (uses (parse-arg 1 '()))
1480 (binder (parse-arg 2 #f)))
1481
1482 (if (not (integer? size))
1483 (error "Illegal size to make-module." size))
1484 (if (not (and (list? uses)
1485 (and-map module? uses)))
1486 (error "Incorrect use list." uses))
1487 (if (and binder (not (procedure? binder)))
1488 (error
1489 "Lazy-binder expected to be a procedure or #f." binder))
1490
1491 (let ((module (module-constructor (make-hash-table size)
4f692ace 1492 uses binder #f macroexpand
13182603 1493 #f #f #f
9b5a0d84
AW
1494 (make-hash-table %default-import-size)
1495 '()
f905381d 1496 (make-weak-key-hash-table 31) #f
78f79f18 1497 (make-hash-table 7) #f #f #f)))
8b718458 1498
9b5a0d84
AW
1499 ;; We can't pass this as an argument to module-constructor,
1500 ;; because we need it to close over a pointer to the module
1501 ;; itself.
1502 (set-module-eval-closure! module (standard-eval-closure module))
8b718458 1503
9b5a0d84 1504 module))))
0f2d19dd 1505
8b718458 1506
0f2d19dd 1507\f
3d2ada2f 1508
1777c18b
MD
1509;;; {Observer protocol}
1510;;;
1511
1512(define (module-observe module proc)
1513 (set-module-observers! module (cons proc (module-observers module)))
1514 (cons module proc))
1515
723ae5b3 1516(define* (module-observe-weak module observer-id #:optional (proc observer-id))
608860a5
LC
1517 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1518 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1519 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1520 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1521 ;; for instance).
1522
1523 ;; The two-argument version is kept for backward compatibility: when called
1524 ;; with two arguments, the observer gets unregistered when closure PROC
1525 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
723ae5b3 1526 (hashq-set! (module-weak-observers module) observer-id proc))
1777c18b
MD
1527
1528(define (module-unobserve token)
1529 (let ((module (car token))
9b5a0d84 1530 (id (cdr token)))
1777c18b 1531 (if (integer? id)
9b5a0d84
AW
1532 (hash-remove! (module-weak-observers module) id)
1533 (set-module-observers! module (delq1! id (module-observers module)))))
1777c18b
MD
1534 *unspecified*)
1535
d57da08b 1536(define module-defer-observers #f)
03d6cddc 1537(define module-defer-observers-mutex (make-mutex 'recursive))
d57da08b
MD
1538(define module-defer-observers-table (make-hash-table))
1539
1a961d7e 1540(define (module-modified m)
d57da08b
MD
1541 (if module-defer-observers
1542 (hash-set! module-defer-observers-table m #t)
1543 (module-call-observers m)))
1544
1545;;; This function can be used to delay calls to observers so that they
1546;;; can be called once only in the face of massive updating of modules.
1547;;;
1548(define (call-with-deferred-observers thunk)
1549 (dynamic-wind
1550 (lambda ()
9b5a0d84
AW
1551 (lock-mutex module-defer-observers-mutex)
1552 (set! module-defer-observers #t))
d57da08b
MD
1553 thunk
1554 (lambda ()
9b5a0d84
AW
1555 (set! module-defer-observers #f)
1556 (hash-for-each (lambda (m dummy)
1557 (module-call-observers m))
1558 module-defer-observers-table)
1559 (hash-clear! module-defer-observers-table)
1560 (unlock-mutex module-defer-observers-mutex))))
d57da08b
MD
1561
1562(define (module-call-observers m)
1777c18b 1563 (for-each (lambda (proc) (proc m)) (module-observers m))
608860a5
LC
1564
1565 ;; We assume that weak observers don't (un)register themselves as they are
1566 ;; called since this would preclude proper iteration over the hash table
1567 ;; elements.
1568 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1777c18b
MD
1569
1570\f
3d2ada2f 1571
0f2d19dd
JB
1572;;; {Module Searching in General}
1573;;;
1574;;; We sometimes want to look for properties of a symbol
1575;;; just within the obarray of one module. If the property
1576;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1577;;; DISPLAY is locally rebound in the module `safe-guile'.''
1578;;;
1579;;;
1580;;; Other times, we want to test for a symbol property in the obarray
1581;;; of M and, if it is not found there, try each of the modules in the
1582;;; uses list of M. This is the normal way of testing for some
1583;;; property, so we state these properties without qualification as
1584;;; in: ``The symbol 'fnord is interned in module M because it is
1585;;; interned locally in module M2 which is a member of the uses list
1586;;; of M.''
1587;;;
1588
1589;; module-search fn m
20edfbbd 1590;;
0f2d19dd
JB
1591;; return the first non-#f result of FN applied to M and then to
1592;; the modules in the uses of m, and so on recursively. If all applications
1593;; return #f, then so does this function.
1594;;
1595(define (module-search fn m v)
1596 (define (loop pos)
1597 (and (pair? pos)
9b5a0d84
AW
1598 (or (module-search fn (car pos) v)
1599 (loop (cdr pos)))))
0f2d19dd
JB
1600 (or (fn m v)
1601 (loop (module-uses m))))
1602
1603
1604;;; {Is a symbol bound in a module?}
1605;;;
1606;;; Symbol S in Module M is bound if S is interned in M and if the binding
1607;;; of S in M has been set to some well-defined value.
1608;;;
1609
1610;; module-locally-bound? module symbol
1611;;
1612;; Is a symbol bound (interned and defined) locally in a given module?
1613;;
1614(define (module-locally-bound? m v)
1615 (let ((var (module-local-variable m v)))
1616 (and var
9b5a0d84 1617 (variable-bound? var))))
0f2d19dd
JB
1618
1619;; module-bound? module symbol
1620;;
1621;; Is a symbol bound (interned and defined) anywhere in a given module
1622;; or its uses?
1623;;
1624(define (module-bound? m v)
f176c584
AW
1625 (let ((var (module-variable m v)))
1626 (and var
9b5a0d84 1627 (variable-bound? var))))
0f2d19dd
JB
1628
1629;;; {Is a symbol interned in a module?}
1630;;;
20edfbbd 1631;;; Symbol S in Module M is interned if S occurs in
0f2d19dd
JB
1632;;; of S in M has been set to some well-defined value.
1633;;;
1634;;; It is possible to intern a symbol in a module without providing
1635;;; an initial binding for the corresponding variable. This is done
1636;;; with:
1637;;; (module-add! module symbol (make-undefined-variable))
1638;;;
1639;;; In that case, the symbol is interned in the module, but not
1640;;; bound there. The unbound symbol shadows any binding for that
1641;;; symbol that might otherwise be inherited from a member of the uses list.
1642;;;
1643
1644(define (module-obarray-get-handle ob key)
1645 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1646
1647(define (module-obarray-ref ob key)
1648 ((if (symbol? key) hashq-ref hash-ref) ob key))
1649
1650(define (module-obarray-set! ob key val)
1651 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1652
1653(define (module-obarray-remove! ob key)
1654 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1655
1656;; module-symbol-locally-interned? module symbol
20edfbbd 1657;;
0f2d19dd
JB
1658;; is a symbol interned (not neccessarily defined) locally in a given module
1659;; or its uses? Interned symbols shadow inherited bindings even if
1660;; they are not themselves bound to a defined value.
1661;;
1662(define (module-symbol-locally-interned? m v)
1663 (not (not (module-obarray-get-handle (module-obarray m) v))))
1664
1665;; module-symbol-interned? module symbol
20edfbbd 1666;;
0f2d19dd
JB
1667;; is a symbol interned (not neccessarily defined) anywhere in a given module
1668;; or its uses? Interned symbols shadow inherited bindings even if
1669;; they are not themselves bound to a defined value.
1670;;
1671(define (module-symbol-interned? m v)
1672 (module-search module-symbol-locally-interned? m v))
1673
1674
1675;;; {Mapping modules x symbols --> variables}
1676;;;
1677
1678;; module-local-variable module symbol
1679;; return the local variable associated with a MODULE and SYMBOL.
1680;;
1681;;; This function is very important. It is the only function that can
1682;;; return a variable from a module other than the mutators that store
1683;;; new variables in modules. Therefore, this function is the location
1684;;; of the "lazy binder" hack.
1685;;;
1686;;; If symbol is defined in MODULE, and if the definition binds symbol
1687;;; to a variable, return that variable object.
1688;;;
1689;;; If the symbols is not found at first, but the module has a lazy binder,
1690;;; then try the binder.
1691;;;
1692;;; If the symbol is not found at all, return #f.
1693;;;
608860a5
LC
1694;;; (This is now written in C, see `modules.c'.)
1695;;;
0f2d19dd
JB
1696
1697;;; {Mapping modules x symbols --> bindings}
1698;;;
1699;;; These are similar to the mapping to variables, except that the
1700;;; variable is dereferenced.
1701;;;
1702
1703;; module-symbol-binding module symbol opt-value
20edfbbd 1704;;
0f2d19dd
JB
1705;; return the binding of a variable specified by name within
1706;; a given module, signalling an error if the variable is unbound.
1707;; If the OPT-VALUE is passed, then instead of signalling an error,
1708;; return OPT-VALUE.
1709;;
1710(define (module-symbol-local-binding m v . opt-val)
1711 (let ((var (module-local-variable m v)))
7b07e5ef 1712 (if (and var (variable-bound? var))
9b5a0d84
AW
1713 (variable-ref var)
1714 (if (not (null? opt-val))
1715 (car opt-val)
1716 (error "Locally unbound variable." v)))))
0f2d19dd
JB
1717
1718;; module-symbol-binding module symbol opt-value
20edfbbd 1719;;
0f2d19dd
JB
1720;; return the binding of a variable specified by name within
1721;; a given module, signalling an error if the variable is unbound.
1722;; If the OPT-VALUE is passed, then instead of signalling an error,
1723;; return OPT-VALUE.
1724;;
1725(define (module-symbol-binding m v . opt-val)
1726 (let ((var (module-variable m v)))
7b07e5ef 1727 (if (and var (variable-bound? var))
9b5a0d84
AW
1728 (variable-ref var)
1729 (if (not (null? opt-val))
1730 (car opt-val)
1731 (error "Unbound variable." v)))))
0f2d19dd
JB
1732
1733
1734\f
3d2ada2f 1735
0f2d19dd
JB
1736;;; {Adding Variables to Modules}
1737;;;
0f2d19dd
JB
1738
1739;; module-make-local-var! module symbol
20edfbbd 1740;;
0f2d19dd
JB
1741;; ensure a variable for V in the local namespace of M.
1742;; If no variable was already there, then create a new and uninitialzied
1743;; variable.
1744;;
d57da08b
MD
1745;; This function is used in modules.c.
1746;;
0f2d19dd
JB
1747(define (module-make-local-var! m v)
1748 (or (let ((b (module-obarray-ref (module-obarray m) v)))
9b5a0d84
AW
1749 (and (variable? b)
1750 (begin
1751 ;; Mark as modified since this function is called when
1752 ;; the standard eval closure defines a binding
1753 (module-modified m)
1754 b)))
0c5f718b 1755
608860a5
LC
1756 ;; Create a new local variable.
1757 (let ((local-var (make-undefined-variable)))
1758 (module-add! m v local-var)
1759 local-var)))
0f2d19dd 1760
89d06712 1761;; module-ensure-local-variable! module symbol
9540368e 1762;;
89d06712
MV
1763;; Ensure that there is a local variable in MODULE for SYMBOL. If
1764;; there is no binding for SYMBOL, create a new uninitialized
1765;; variable. Return the local variable.
9540368e 1766;;
89d06712
MV
1767(define (module-ensure-local-variable! module symbol)
1768 (or (module-local-variable module symbol)
9540368e 1769 (let ((var (make-undefined-variable)))
9b5a0d84
AW
1770 (module-add! module symbol var)
1771 var)))
9540368e 1772
0f2d19dd 1773;; module-add! module symbol var
20edfbbd 1774;;
0f2d19dd
JB
1775;; ensure a particular variable for V in the local namespace of M.
1776;;
1777(define (module-add! m v var)
1778 (if (not (variable? var))
1779 (error "Bad variable to module-add!" var))
1777c18b 1780 (module-obarray-set! (module-obarray m) v var)
1a961d7e 1781 (module-modified m))
0f2d19dd 1782
20edfbbd
TTN
1783;; module-remove!
1784;;
0f2d19dd
JB
1785;; make sure that a symbol is undefined in the local namespace of M.
1786;;
1787(define (module-remove! m v)
c35738c1 1788 (module-obarray-remove! (module-obarray m) v)
1a961d7e 1789 (module-modified m))
0f2d19dd
JB
1790
1791(define (module-clear! m)
c35738c1 1792 (hash-clear! (module-obarray m))
1a961d7e 1793 (module-modified m))
0f2d19dd
JB
1794
1795;; MODULE-FOR-EACH -- exported
20edfbbd 1796;;
0f2d19dd
JB
1797;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1798;;
1799(define (module-for-each proc module)
c35738c1 1800 (hash-for-each proc (module-obarray module)))
0f2d19dd
JB
1801
1802(define (module-map proc module)
711a9fd7 1803 (hash-map->list proc (module-obarray module)))
c35738c1 1804
0f27ab8a
AW
1805;; Submodules
1806;;
1807;; Modules exist in a separate namespace from values, because you generally do
1808;; not want the name of a submodule, which you might not even use, to collide
1809;; with local variables that happen to be named the same as the submodule.
1810;;
1811(define (module-ref-submodule module name)
81fc66cf
AW
1812 (or (hashq-ref (module-submodules module) name)
1813 (and (module-submodule-binder module)
1814 ((module-submodule-binder module) module name))))
0f27ab8a
AW
1815
1816(define (module-define-submodule! module name submodule)
f6a5308b 1817 (hashq-set! (module-submodules module) name submodule))
0f27ab8a 1818
0f2d19dd
JB
1819\f
1820
1821;;; {Low Level Bootstrapping}
1822;;;
1823
20edfbbd 1824;; make-root-module
0f2d19dd 1825
296ff5e7
MV
1826;; A root module uses the pre-modules-obarray as its obarray. This
1827;; special obarray accumulates all bindings that have been established
1828;; before the module system is fully booted.
0f2d19dd 1829;;
296ff5e7
MV
1830;; (The obarray continues to be used by code that has been closed over
1831;; before the module system has been booted.)
0f2d19dd
JB
1832
1833(define (make-root-module)
296ff5e7
MV
1834 (let ((m (make-module 0)))
1835 (set-module-obarray! m (%get-pre-modules-obarray))
1836 m))
0f2d19dd 1837
b622dec7 1838;; make-scm-module
0f2d19dd 1839
296ff5e7
MV
1840;; The root interface is a module that uses the same obarray as the
1841;; root module. It does not allow new definitions, tho.
0f2d19dd 1842
6906bd0d 1843(define (make-scm-module)
296ff5e7
MV
1844 (let ((m (make-module 0)))
1845 (set-module-obarray! m (%get-pre-modules-obarray))
1846 (set-module-eval-closure! m (standard-interface-eval-closure m))
1847 m))
0f2d19dd
JB
1848
1849
0f2d19dd 1850\f
3d2ada2f 1851
0f2d19dd
JB
1852;;; {Module-based Loading}
1853;;;
1854
1855(define (save-module-excursion thunk)
1856 (let ((inner-module (current-module))
9b5a0d84 1857 (outer-module #f))
0f2d19dd 1858 (dynamic-wind (lambda ()
9b5a0d84
AW
1859 (set! outer-module (current-module))
1860 (set-current-module inner-module)
1861 (set! inner-module #f))
1862 thunk
1863 (lambda ()
1864 (set! inner-module (current-module))
1865 (set-current-module outer-module)
1866 (set! outer-module #f)))))
0f2d19dd 1867
0f2d19dd
JB
1868(define basic-load load)
1869
5a662124 1870(define* (load-module filename #:optional reader)
c6775c40
MD
1871 (save-module-excursion
1872 (lambda ()
1873 (let ((oldname (and (current-load-port)
9b5a0d84 1874 (port-filename (current-load-port)))))
5a662124
AW
1875 (basic-load (if (and oldname
1876 (> (string-length filename) 0)
1877 (not (char=? (string-ref filename 0) #\/))
1878 (not (string=? (dirname oldname) ".")))
1879 (string-append (dirname oldname) "/" filename)
1880 filename)
1881 reader)))))
0f2d19dd
JB
1882
1883
1884\f
3d2ada2f 1885
44cf1f0f 1886;;; {MODULE-REF -- exported}
3d2ada2f
DH
1887;;;
1888
0f2d19dd
JB
1889;; Returns the value of a variable called NAME in MODULE or any of its
1890;; used modules. If there is no such variable, then if the optional third
1891;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
20edfbbd 1892;;
0f2d19dd
JB
1893(define (module-ref module name . rest)
1894 (let ((variable (module-variable module name)))
1895 (if (and variable (variable-bound? variable))
9b5a0d84
AW
1896 (variable-ref variable)
1897 (if (null? rest)
1898 (error "No variable named" name 'in module)
1899 (car rest) ; default value
1900 ))))
0f2d19dd
JB
1901
1902;; MODULE-SET! -- exported
1903;;
1904;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1905;; to VALUE; if there is no such variable, an error is signaled.
20edfbbd 1906;;
0f2d19dd
JB
1907(define (module-set! module name value)
1908 (let ((variable (module-variable module name)))
1909 (if variable
9b5a0d84
AW
1910 (variable-set! variable value)
1911 (error "No variable named" name 'in module))))
0f2d19dd
JB
1912
1913;; MODULE-DEFINE! -- exported
1914;;
1915;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1916;; variable, it is added first.
20edfbbd 1917;;
0f2d19dd
JB
1918(define (module-define! module name value)
1919 (let ((variable (module-local-variable module name)))
1920 (if variable
9b5a0d84
AW
1921 (begin
1922 (variable-set! variable value)
1923 (module-modified module))
1924 (let ((variable (make-variable value)))
1925 (module-add! module name variable)))))
0f2d19dd 1926
ed218d98
MV
1927;; MODULE-DEFINED? -- exported
1928;;
1929;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1930;; uses)
1931;;
1932(define (module-defined? module name)
1933 (let ((variable (module-variable module name)))
1934 (and variable (variable-bound? variable))))
1935
0f2d19dd
JB
1936;; MODULE-USE! module interface
1937;;
1938;; Add INTERFACE to the list of interfaces used by MODULE.
20edfbbd 1939;;
0f2d19dd 1940(define (module-use! module interface)
b1907902
AW
1941 (if (not (or (eq? module interface)
1942 (memq interface (module-uses module))))
608860a5
LC
1943 (begin
1944 ;; Newly used modules must be appended rather than consed, so that
1945 ;; `module-variable' traverses the use list starting from the first
1946 ;; used module.
1947 (set-module-uses! module
1948 (append (filter (lambda (m)
1949 (not
1950 (equal? (module-name m)
1951 (module-name interface))))
1952 (module-uses module))
1953 (list interface)))
8f44138a 1954 (hash-clear! (module-import-obarray module))
608860a5 1955 (module-modified module))))
0f2d19dd 1956
7b07e5ef
MD
1957;; MODULE-USE-INTERFACES! module interfaces
1958;;
1959;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1960;;
1961(define (module-use-interfaces! module interfaces)
608860a5
LC
1962 (set-module-uses! module
1963 (append (module-uses module) interfaces))
8f44138a 1964 (hash-clear! (module-import-obarray module))
608860a5 1965 (module-modified module))
7b07e5ef 1966
0f2d19dd 1967\f
3d2ada2f 1968
0f2d19dd
JB
1969;;; {Recursive Namespaces}
1970;;;
0f2d19dd 1971;;; A hierarchical namespace emerges if we consider some module to be
b910c4ac 1972;;; root, and submodules of that module to be nested namespaces.
0f2d19dd 1973;;;
b910c4ac 1974;;; The routines here manage variable names in hierarchical namespace.
0f2d19dd
JB
1975;;; Each variable name is a list of elements, looked up in successively nested
1976;;; modules.
1977;;;
9b5a0d84 1978;;; (nested-ref some-root-module '(foo bar baz))
b910c4ac
AW
1979;;; => <value of a variable named baz in the submodule bar of
1980;;; the submodule foo of some-root-module>
0f2d19dd
JB
1981;;;
1982;;;
1983;;; There are:
1984;;;
9b5a0d84
AW
1985;;; ;; a-root is a module
1986;;; ;; name is a list of symbols
0f2d19dd 1987;;;
9b5a0d84
AW
1988;;; nested-ref a-root name
1989;;; nested-set! a-root name val
1990;;; nested-define! a-root name val
1991;;; nested-remove! a-root name
0f2d19dd 1992;;;
b910c4ac
AW
1993;;; These functions manipulate values in namespaces. For referencing the
1994;;; namespaces themselves, use the following:
0f2d19dd 1995;;;
b910c4ac
AW
1996;;; nested-ref-module a-root name
1997;;; nested-define-module! a-root name mod
1998;;;
1999;;; (current-module) is a natural choice for a root so for convenience there are
0f2d19dd
JB
2000;;; also:
2001;;;
b910c4ac
AW
2002;;; local-ref name == nested-ref (current-module) name
2003;;; local-set! name val == nested-set! (current-module) name val
2004;;; local-define name val == nested-define! (current-module) name val
2005;;; local-remove name == nested-remove! (current-module) name
2006;;; local-ref-module name == nested-ref-module (current-module) name
2007;;; local-define-module! name m == nested-define-module! (current-module) name m
0f2d19dd
JB
2008;;;
2009
2010
0dd5491c 2011(define (nested-ref root names)
b910c4ac
AW
2012 (if (null? names)
2013 root
2014 (let loop ((cur root)
2015 (head (car names))
2016 (tail (cdr names)))
2017 (if (null? tail)
2018 (module-ref cur head #f)
2019 (let ((cur (module-ref-submodule cur head)))
2020 (and cur
2021 (loop cur (car tail) (cdr tail))))))))
0f2d19dd 2022
0dd5491c 2023(define (nested-set! root names val)
0f2d19dd 2024 (let loop ((cur root)
b910c4ac
AW
2025 (head (car names))
2026 (tail (cdr names)))
2027 (if (null? tail)
2028 (module-set! cur head val)
2029 (let ((cur (module-ref-submodule cur head)))
2030 (if (not cur)
2031 (error "failed to resolve module" names)
2032 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2033
0dd5491c 2034(define (nested-define! root names val)
0f2d19dd 2035 (let loop ((cur root)
b910c4ac
AW
2036 (head (car names))
2037 (tail (cdr names)))
2038 (if (null? tail)
2039 (module-define! cur head val)
2040 (let ((cur (module-ref-submodule cur head)))
2041 (if (not cur)
2042 (error "failed to resolve module" names)
2043 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2044
0dd5491c 2045(define (nested-remove! root names)
0f2d19dd 2046 (let loop ((cur root)
b910c4ac
AW
2047 (head (car names))
2048 (tail (cdr names)))
2049 (if (null? tail)
2050 (module-remove! cur head)
2051 (let ((cur (module-ref-submodule cur head)))
2052 (if (not cur)
2053 (error "failed to resolve module" names)
2054 (loop cur (car tail) (cdr tail)))))))
2055
2056
2057(define (nested-ref-module root names)
2058 (let loop ((cur root)
2059 (names names))
2060 (if (null? names)
2061 cur
2062 (let ((cur (module-ref-submodule cur (car names))))
2063 (and cur
2064 (loop cur (cdr names)))))))
2065
2066(define (nested-define-module! root names module)
2067 (if (null? names)
2068 (error "can't redefine root module" root module)
2069 (let loop ((cur root)
2070 (head (car names))
2071 (tail (cdr names)))
2072 (if (null? tail)
2073 (module-define-submodule! cur head module)
2074 (let ((cur (or (module-ref-submodule cur head)
2075 (let ((m (make-module 31)))
2076 (set-module-kind! m 'directory)
2077 (set-module-name! m (append (module-name cur)
2078 (list head)))
2079 (module-define-submodule! cur head m)
2080 m))))
2081 (loop cur (car tail) (cdr tail)))))))
2082
0f2d19dd 2083
0dd5491c
MD
2084(define (local-ref names) (nested-ref (current-module) names))
2085(define (local-set! names val) (nested-set! (current-module) names val))
2086(define (local-define names val) (nested-define! (current-module) names val))
2087(define (local-remove names) (nested-remove! (current-module) names))
b910c4ac
AW
2088(define (local-ref-module names) (nested-ref-module (current-module) names))
2089(define (local-define-module names mod) (nested-define-module! (current-module) names mod))
2090
0f2d19dd
JB
2091
2092
2093\f
3d2ada2f 2094
cb67c838 2095;;; {The (guile) module}
0f2d19dd 2096;;;
cb67c838
AW
2097;;; The standard module, which has the core Guile bindings. Also called the
2098;;; "root module", as it is imported by many other modules, but it is not
2099;;; necessarily the root of anything; and indeed, the module named '() might be
2100;;; better thought of as a root.
0f2d19dd 2101;;;
bbd1d133 2102
edc185c7
MD
2103(define (set-system-module! m s)
2104 (set-procedure-property! (module-eval-closure m) 'system-module s))
0f2d19dd
JB
2105(define the-root-module (make-root-module))
2106(define the-scm-module (make-scm-module))
2107(set-module-public-interface! the-root-module the-scm-module)
d5504515
MD
2108(set-module-name! the-root-module '(guile))
2109(set-module-name! the-scm-module '(guile))
2110(set-module-kind! the-scm-module 'interface)
25d8cd3a
AW
2111(set-system-module! the-root-module #t)
2112(set-system-module! the-scm-module #t)
0f2d19dd 2113
bbd1d133
AW
2114
2115\f
2116
2117;; Now that we have a root module, even though modules aren't fully booted,
2118;; expand the definition of resolve-module.
2119;;
2120(define (resolve-module name . args)
2121 (if (equal? name '(guile))
2122 the-root-module
2123 (error "unexpected module to resolve during module boot" name)))
2124
2125;; Cheat. These bindings are needed by modules.c, but we don't want
2126;; to move their real definition here because that would be unnatural.
2127;;
2128(define process-define-module #f)
2129(define process-use-modules #f)
2130(define module-export! #f)
2131(define default-duplicate-binding-procedures #f)
2132
2133;; This boots the module system. All bindings needed by modules.c
2134;; must have been defined by now.
296ff5e7 2135;;
bbd1d133
AW
2136(set-current-module the-root-module)
2137
2138
2139\f
2140
2141;; Now that modules are booted, give module-name its final definition.
2142;;
2143(define module-name
2144 (let ((accessor (record-accessor module-type 'name)))
2145 (lambda (mod)
2146 (or (accessor mod)
2147 (let ((name (list (gensym))))
cb67c838
AW
2148 ;; Name MOD and bind it in the module root so that it's visible to
2149 ;; `resolve-module'. This is important as `psyntax' stores module
2150 ;; names and relies on being able to `resolve-module' them.
bbd1d133 2151 (set-module-name! mod name)
9e0bfdba 2152 (nested-define-module! (resolve-module '() #f) name mod)
bbd1d133
AW
2153 (accessor mod))))))
2154
296ff5e7 2155(define (make-modules-in module name)
9e0bfdba
AW
2156 (or (nested-ref-module module name)
2157 (let ((m (make-module 31)))
2158 (set-module-kind! m 'directory)
2159 (set-module-name! m (append (module-name module) name))
2160 (nested-define-module! module name m)
2161 m)))
0f2d19dd 2162
296ff5e7
MV
2163(define (beautify-user-module! module)
2164 (let ((interface (module-public-interface module)))
2165 (if (or (not interface)
9b5a0d84
AW
2166 (eq? interface module))
2167 (let ((interface (make-module 31)))
2168 (set-module-name! interface (module-name module))
dca14012 2169 (set-module-version! interface (module-version module))
9b5a0d84
AW
2170 (set-module-kind! interface 'interface)
2171 (set-module-public-interface! module interface))))
296ff5e7 2172 (if (and (not (memq the-scm-module (module-uses module)))
9b5a0d84 2173 (not (eq? module the-root-module)))
608860a5
LC
2174 ;; Import the default set of bindings (from the SCM module) in MODULE.
2175 (module-use! module the-scm-module)))
432558b9 2176
dca14012 2177(define (version-matches? version-ref target)
dca14012
JG
2178 (define (sub-versions-match? v-refs t)
2179 (define (sub-version-matches? v-ref t)
befd1df9
AW
2180 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2181 (cond
2182 ((number? v-ref) (eqv? v-ref t))
2183 ((list? v-ref)
2184 (case (car v-ref)
2185 ((>=) (>= t (cadr v-ref)))
2186 ((<=) (<= t (cadr v-ref)))
2187 ((and) (and-map matches? (cdr v-ref)))
2188 ((or) (or-map matches? (cdr v-ref)))
2189 ((not) (not (matches? (cadr v-ref))))
2190 (else (error "Invalid sub-version reference" v-ref))))
2191 (else (error "Invalid sub-version reference" v-ref)))))
dca14012
JG
2192 (or (null? v-refs)
2193 (and (not (null? t))
2194 (sub-version-matches? (car v-refs) (car t))
2195 (sub-versions-match? (cdr v-refs) (cdr t)))))
befd1df9
AW
2196
2197 (let ((matches? (lambda (v) (version-matches? v target))))
2198 (or (null? version-ref)
2199 (case (car version-ref)
2200 ((and) (and-map matches? (cdr version-ref)))
2201 ((or) (or-map matches? (cdr version-ref)))
2202 ((not) (not (matches? (cadr version-ref))))
2203 (else (sub-versions-match? version-ref target))))))
dca14012 2204
f95f82f8
AW
2205(define (make-fresh-user-module)
2206 (let ((m (make-module)))
2207 (beautify-user-module! m)
2208 m))
2209
1f60d9d2
MD
2210;; NOTE: This binding is used in libguile/modules.c.
2211;;
53f84bc8 2212(define resolve-module
cb67c838
AW
2213 (let ((root (make-module)))
2214 (set-module-name! root '())
2215 ;; Define the-root-module as '(guile).
d58ccc66 2216 (module-define-submodule! root 'guile the-root-module)
cb67c838 2217
7e314766 2218 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
6b7d701e 2219 (let ((already (nested-ref-module root name)))
cb67c838 2220 (cond
d58ccc66 2221 ((and already
cb67c838
AW
2222 (or (not autoload) (module-public-interface already)))
2223 ;; A hit, a palpable hit.
e44d2e4d 2224 (if (and version
cb67c838
AW
2225 (not (version-matches? version (module-version already))))
2226 (error "incompatible module version already loaded" name))
2227 already)
2228 (autoload
2229 ;; Try to autoload the module, and recurse.
2230 (try-load-module name version)
7e314766 2231 (resolve-module name #f #:ensure ensure))
cb67c838 2232 (else
51b22dbb 2233 ;; No module found (or if one was, it had no public interface), and
7e314766
AW
2234 ;; we're not autoloading. Make an empty module if #:ensure is true.
2235 (or already
2236 (and ensure
2237 (make-modules-in root name)))))))))
cb67c838 2238
296ff5e7 2239
dca14012
JG
2240(define (try-load-module name version)
2241 (try-module-autoload name version))
0f2d19dd 2242
90847923
MD
2243(define (purify-module! module)
2244 "Removes bindings in MODULE which are inherited from the (guile) module."
2245 (let ((use-list (module-uses module)))
2246 (if (and (pair? use-list)
9b5a0d84
AW
2247 (eq? (car (last-pair use-list)) the-scm-module))
2248 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
90847923 2249
4eecfeb7 2250;; Return a module that is an interface to the module designated by
532cf805
MV
2251;; NAME.
2252;;
c614a00b 2253;; `resolve-interface' takes four keyword arguments:
532cf805
MV
2254;;
2255;; #:select SELECTION
2256;;
2257;; SELECTION is a list of binding-specs to be imported; A binding-spec
2258;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2259;; is the name in the used module and SEEN is the name in the using
2260;; module. Note that SEEN is also passed through RENAMER, below. The
2261;; default is to select all bindings. If you specify no selection but
4eecfeb7 2262;; a renamer, only the bindings that already exist in the used module
532cf805
MV
2263;; are made available in the interface. Bindings that are added later
2264;; are not picked up.
2265;;
c614a00b 2266;; #:hide BINDINGS
532cf805 2267;;
c614a00b 2268;; BINDINGS is a list of bindings which should not be imported.
f595ccfe
MD
2269;;
2270;; #:prefix PREFIX
2271;;
2272;; PREFIX is a symbol that will be appended to each exported name.
2273;; The default is to not perform any renaming.
532cf805 2274;;
c614a00b
MD
2275;; #:renamer RENAMER
2276;;
2277;; RENAMER is a procedure that takes a symbol and returns its new
2278;; name. The default is not perform any renaming.
2279;;
532cf805
MV
2280;; Signal "no code for module" error if module name is not resolvable
2281;; or its public interface is not available. Signal "no binding"
2282;; error if selected binding does not exist in the used module.
2283;;
36d58fc3
AW
2284(define* (resolve-interface name #:key
2285 (select #f)
2286 (hide '())
2287 (prefix #f)
2288 (renamer (if prefix
2289 (symbol-prefix-proc prefix)
2290 identity))
2291 version)
47aabe86 2292 (let* ((module (resolve-module name #t version #:ensure #f))
b622dec7
TTN
2293 (public-i (and module (module-public-interface module))))
2294 (and (or (not module) (not public-i))
2295 (error "no code for module" name))
c614a00b 2296 (if (and (not select) (null? hide) (eq? renamer identity))
b622dec7 2297 public-i
532cf805 2298 (let ((selection (or select (module-map (lambda (sym var) sym)
9b5a0d84 2299 public-i)))
b622dec7 2300 (custom-i (make-module 31)))
c614a00b 2301 (set-module-kind! custom-i 'custom-interface)
9b5a0d84
AW
2302 (set-module-name! custom-i name)
2303 ;; XXX - should use a lazy binder so that changes to the
2304 ;; used module are picked up automatically.
2305 (for-each (lambda (bspec)
2306 (let* ((direct? (symbol? bspec))
2307 (orig (if direct? bspec (car bspec)))
2308 (seen (if direct? bspec (cdr bspec)))
2309 (var (or (module-local-variable public-i orig)
2310 (module-local-variable module orig)
2311 (error
2312 ;; fixme: format manually for now
2313 (simple-format
2314 #f "no binding `~A' in module ~A"
2315 orig name)))))
2316 (if (memq orig hide)
2317 (set! hide (delq! orig hide))
2318 (module-add! custom-i
2319 (renamer seen)
2320 var))))
2321 selection)
2322 ;; Check that we are not hiding bindings which don't exist
2323 (for-each (lambda (binding)
2324 (if (not (module-local-variable public-i binding))
2325 (error
2326 (simple-format
2327 #f "no binding `~A' to hide in module ~A"
2328 binding name))))
2329 hide)
b622dec7 2330 custom-i))))
fb1b76f4
TTN
2331
2332(define (symbol-prefix-proc prefix)
2333 (lambda (symbol)
2334 (symbol-append prefix symbol)))
0f2d19dd 2335
482a28f9
MV
2336;; This function is called from "modules.c". If you change it, be
2337;; sure to update "modules.c" as well.
2338
0f2d19dd 2339(define (process-define-module args)
f8a502cb
TTN
2340 (let* ((module-id (car args))
2341 (module (resolve-module module-id #f))
2342 (kws (cdr args))
2343 (unrecognized (lambda (arg)
2344 (error "unrecognized define-module argument" arg))))
0f2d19dd 2345 (beautify-user-module! module)
0209ca9a 2346 (let loop ((kws kws)
1b92d94c
AW
2347 (reversed-interfaces '())
2348 (exports '())
2349 (re-exports '())
2350 (replacements '())
608860a5 2351 (autoloads '()))
e4da0740 2352
0209ca9a 2353 (if (null? kws)
1b92d94c
AW
2354 (call-with-deferred-observers
2355 (lambda ()
2356 (module-use-interfaces! module (reverse reversed-interfaces))
2357 (module-export! module exports)
2358 (module-replace! module replacements)
2359 (module-re-export! module re-exports)
608860a5
LC
2360 (if (not (null? autoloads))
2361 (apply module-autoload! module autoloads))))
1b92d94c
AW
2362 (case (car kws)
2363 ((#:use-module #:use-syntax)
2364 (or (pair? (cdr kws))
2365 (unrecognized kws))
13182603
AW
2366 (cond
2367 ((equal? (caadr kws) '(ice-9 syncase))
2368 (issue-deprecation-warning
2369 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
1b92d94c 2370 (loop (cddr kws)
13182603 2371 reversed-interfaces
1b92d94c
AW
2372 exports
2373 re-exports
2374 replacements
13182603
AW
2375 autoloads))
2376 (else
2377 (let* ((interface-args (cadr kws))
2378 (interface (apply resolve-interface interface-args)))
2379 (and (eq? (car kws) #:use-syntax)
2380 (or (symbol? (caar interface-args))
2381 (error "invalid module name for use-syntax"
2382 (car interface-args)))
2383 (set-module-transformer!
2384 module
2385 (module-ref interface
2386 (car (last-pair (car interface-args)))
2387 #f)))
2388 (loop (cddr kws)
2389 (cons interface reversed-interfaces)
2390 exports
2391 re-exports
2392 replacements
2393 autoloads)))))
1b92d94c
AW
2394 ((#:autoload)
2395 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2396 (unrecognized kws))
2397 (loop (cdddr kws)
608860a5 2398 reversed-interfaces
1b92d94c
AW
2399 exports
2400 re-exports
2401 replacements
608860a5
LC
2402 (let ((name (cadr kws))
2403 (bindings (caddr kws)))
2404 (cons* name bindings autoloads))))
1b92d94c
AW
2405 ((#:no-backtrace)
2406 (set-system-module! module #t)
2407 (loop (cdr kws) reversed-interfaces exports re-exports
608860a5 2408 replacements autoloads))
1b92d94c
AW
2409 ((#:pure)
2410 (purify-module! module)
2411 (loop (cdr kws) reversed-interfaces exports re-exports
608860a5 2412 replacements autoloads))
dca14012
JG
2413 ((#:version)
2414 (or (pair? (cdr kws))
2415 (unrecognized kws))
2416 (let ((version (cadr kws)))
2417 (set-module-version! module version)
2418 (set-module-version! (module-public-interface module) version))
2419 (loop (cddr kws) reversed-interfaces exports re-exports
2420 replacements autoloads))
1b92d94c
AW
2421 ((#:duplicates)
2422 (if (not (pair? (cdr kws)))
2423 (unrecognized kws))
2424 (set-module-duplicates-handlers!
2425 module
2426 (lookup-duplicates-handlers (cadr kws)))
2427 (loop (cddr kws) reversed-interfaces exports re-exports
608860a5 2428 replacements autoloads))
1b92d94c
AW
2429 ((#:export #:export-syntax)
2430 (or (pair? (cdr kws))
2431 (unrecognized kws))
2432 (loop (cddr kws)
2433 reversed-interfaces
2434 (append (cadr kws) exports)
2435 re-exports
2436 replacements
608860a5 2437 autoloads))
1b92d94c
AW
2438 ((#:re-export #:re-export-syntax)
2439 (or (pair? (cdr kws))
2440 (unrecognized kws))
2441 (loop (cddr kws)
2442 reversed-interfaces
2443 exports
2444 (append (cadr kws) re-exports)
2445 replacements
608860a5 2446 autoloads))
1b92d94c
AW
2447 ((#:replace #:replace-syntax)
2448 (or (pair? (cdr kws))
2449 (unrecognized kws))
2450 (loop (cddr kws)
2451 reversed-interfaces
2452 exports
2453 re-exports
2454 (append (cadr kws) replacements)
608860a5 2455 autoloads))
78f79f18
AW
2456 ((#:filename)
2457 (or (pair? (cdr kws))
2458 (unrecognized kws))
2459 (set-module-filename! module (cadr kws))
2460 (loop (cddr kws)
2461 reversed-interfaces
2462 exports
2463 re-exports
2464 replacements
2465 autoloads))
1b92d94c
AW
2466 (else
2467 (unrecognized kws)))))
db853761 2468 (run-hook module-defined-hook module)
0f2d19dd 2469 module))
71225060 2470
db853761
NJ
2471;; `module-defined-hook' is a hook that is run whenever a new module
2472;; is defined. Its members are called with one argument, the new
2473;; module.
2474(define module-defined-hook (make-hook 1))
2475
3d2ada2f
DH
2476\f
2477
71225060 2478;;; {Autoload}
3d2ada2f 2479;;;
71225060
MD
2480
2481(define (make-autoload-interface module name bindings)
2482 (let ((b (lambda (a sym definep)
9b5a0d84
AW
2483 (and (memq sym bindings)
2484 (let ((i (module-public-interface (resolve-module name))))
2485 (if (not i)
2486 (error "missing interface for module" name))
2487 (let ((autoload (memq a (module-uses module))))
2488 ;; Replace autoload-interface with actual interface if
2489 ;; that has not happened yet.
2490 (if (pair? autoload)
2491 (set-car! autoload i)))
2492 (module-local-variable i sym))))))
608860a5 2493 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
f905381d 2494 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
78f79f18 2495 (make-hash-table 0) #f #f #f)))
608860a5
LC
2496
2497(define (module-autoload! module . args)
2498 "Have @var{module} automatically load the module named @var{name} when one
2499of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2500list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2501module '(ice-9 q) '(make-q q-length))}."
2502 (let loop ((args args))
2503 (cond ((null? args)
2504 #t)
2505 ((null? (cdr args))
2506 (error "invalid name+binding autoload list" args))
2507 (else
2508 (let ((name (car args))
2509 (bindings (cadr args)))
2510 (module-use! module (make-autoload-interface module
2511 name bindings))
2512 (loop (cddr args)))))))
2513
71225060 2514
0f2d19dd 2515\f
3d2ada2f 2516
44cf1f0f 2517;;; {Autoloading modules}
3d2ada2f 2518;;;
0f2d19dd
JB
2519
2520(define autoloads-in-progress '())
2521
482a28f9
MV
2522;; This function is called from "modules.c". If you change it, be
2523;; sure to update "modules.c" as well.
2524
d9113d47 2525(define* (try-module-autoload module-name #:optional version)
0f2d19dd 2526 (let* ((reverse-name (reverse module-name))
9b5a0d84
AW
2527 (name (symbol->string (car reverse-name)))
2528 (dir-hint-module-name (reverse (cdr reverse-name)))
2529 (dir-hint (apply string-append
2530 (map (lambda (elt)
2531 (string-append (symbol->string elt) "/"))
2532 dir-hint-module-name))))
0209ca9a 2533 (resolve-module dir-hint-module-name #f)
0f2d19dd 2534 (and (not (autoload-done-or-in-progress? dir-hint name))
9b5a0d84
AW
2535 (let ((didit #f))
2536 (dynamic-wind
2537 (lambda () (autoload-in-progress! dir-hint name))
2538 (lambda ()
eddd16d7
AW
2539 (with-fluids ((current-reader #f))
2540 (save-module-excursion
2541 (lambda ()
39392995
AW
2542 ;; The initial environment when loading a module is a fresh
2543 ;; user module.
2544 (set-current-module (make-fresh-user-module))
e44d2e4d
AW
2545 ;; Here we could allow some other search strategy (other than
2546 ;; primitive-load-path), for example using versions encoded
2547 ;; into the file system -- but then we would have to figure
2548 ;; out how to locate the compiled file, do autocompilation,
2549 ;; etc. Punt for now, and don't use versions when locating
2550 ;; the file.
2551 (primitive-load-path (in-vicinity dir-hint name) #f)
eddd16d7 2552 (set! didit #t)))))
9b5a0d84
AW
2553 (lambda () (set-autoloaded! dir-hint name didit)))
2554 didit))))
0f2d19dd 2555
71225060 2556\f
3d2ada2f
DH
2557
2558;;; {Dynamic linking of modules}
2559;;;
d0cbd20c 2560
0f2d19dd
JB
2561(define autoloads-done '((guile . guile)))
2562
2563(define (autoload-done-or-in-progress? p m)
2564 (let ((n (cons p m)))
2565 (->bool (or (member n autoloads-done)
9b5a0d84 2566 (member n autoloads-in-progress)))))
0f2d19dd
JB
2567
2568(define (autoload-done! p m)
2569 (let ((n (cons p m)))
2570 (set! autoloads-in-progress
9b5a0d84 2571 (delete! n autoloads-in-progress))
0f2d19dd 2572 (or (member n autoloads-done)
9b5a0d84 2573 (set! autoloads-done (cons n autoloads-done)))))
0f2d19dd
JB
2574
2575(define (autoload-in-progress! p m)
2576 (let ((n (cons p m)))
2577 (set! autoloads-done
9b5a0d84 2578 (delete! n autoloads-done))
0f2d19dd
JB
2579 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2580
2581(define (set-autoloaded! p m done?)
2582 (if done?
2583 (autoload-done! p m)
2584 (let ((n (cons p m)))
9b5a0d84
AW
2585 (set! autoloads-done (delete! n autoloads-done))
2586 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
0f2d19dd 2587
0f2d19dd
JB
2588\f
2589
83b38198 2590;;; {Run-time options}
3d2ada2f 2591;;;
83b38198 2592
122f296d
AW
2593(define-syntax define-option-interface
2594 (syntax-rules ()
2595 ((_ (interface (options enable disable) (option-set!)))
2596 (begin
2597 (define options
2598 (case-lambda
2599 (() (interface))
2600 ((arg)
2601 (if (list? arg)
2602 (begin (interface arg) (interface))
2603 (for-each
2604 (lambda (option)
2605 (apply (lambda (name value documentation)
2606 (display name)
2607 (if (< (string-length (symbol->string name)) 8)
2608 (display #\tab))
2609 (display #\tab)
2610 (display value)
2611 (display #\tab)
2612 (display documentation)
2613 (newline))
2614 option))
2615 (interface #t))))))
2616 (define (enable . flags)
2617 (interface (append flags (interface)))
2618 (interface))
2619 (define (disable . flags)
2620 (let ((options (interface)))
2621 (for-each (lambda (flag) (set! options (delq! flag options)))
2622 flags)
2623 (interface options)
2624 (interface)))
2625 (define-syntax option-set!
2626 (syntax-rules ()
2627 ((_ opt val)
2628 (options (append (options) (list 'opt val))))))))))
e9bab9df
DH
2629
2630(define-option-interface
2631 (eval-options-interface
2632 (eval-options eval-enable eval-disable)
2633 (eval-set!)))
2634
2635(define-option-interface
2636 (debug-options-interface
2637 (debug-options debug-enable debug-disable)
2638 (debug-set!)))
2639
2640(define-option-interface
2641 (evaluator-traps-interface
2642 (traps trap-enable trap-disable)
2643 (trap-set!)))
2644
2645(define-option-interface
2646 (read-options-interface
2647 (read-options read-enable read-disable)
2648 (read-set!)))
2649
2650(define-option-interface
2651 (print-options-interface
2652 (print-options print-enable print-disable)
2653 (print-set!)))
83b38198
MD
2654
2655\f
2656
410e83c0
AW
2657;;; {The Unspecified Value}
2658;;;
2659;;; Currently Guile represents unspecified values via one particular value,
2660;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2661;;; future if we could replace this with a return of 0 values, though.
9346b857 2662;;;
410e83c0
AW
2663
2664(define-syntax *unspecified*
2665 (identifier-syntax (if #f #f)))
2666
2667(define (unspecified? v) (eq? v *unspecified*))
2668
2669
2670\f
2671
0f2d19dd
JB
2672;;; {Running Repls}
2673;;;
2674
9346b857
AW
2675;; Programs can call `batch-mode?' to see if they are running as part of a
2676;; script or if they are running interactively. REPL implementations ensure that
2677;; `batch-mode?' returns #f during their extent.
2678;;
2679;; Programs can re-enter batch mode, for example after a fork, by calling
0feb833d
AW
2680;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
2681;; to abort to the outermost prompt, and call a thunk there.
9346b857
AW
2682(define *repl-level* (make-fluid))
2683(define (batch-mode?)
2684 (negative? (or (fluid-ref *repl-level*) -1)))
2685(define (ensure-batch-mode!)
0feb833d 2686 (fluid-set! *repl-level* #f))
4bbbcd5c 2687
0f2d19dd
JB
2688(define (quit . args)
2689 (apply throw 'quit args))
2690
7950df7c
GH
2691(define exit quit)
2692
0f2d19dd
JB
2693(define (gc-run-time)
2694 (cdr (assq 'gc-time-taken (gc-stats))))
2695
8942e7a1
AW
2696(define abort-hook (make-hook))
2697(define before-error-hook (make-hook))
2698(define after-error-hook (make-hook))
2699(define before-backtrace-hook (make-hook))
2700(define after-backtrace-hook (make-hook))
2701
3e3cec45
MD
2702(define before-read-hook (make-hook))
2703(define after-read-hook (make-hook))
870777d7
KN
2704(define before-eval-hook (make-hook 1))
2705(define after-eval-hook (make-hook 1))
2706(define before-print-hook (make-hook 1))
2707(define after-print-hook (make-hook 1))
1c6cd8e8 2708
dc5c2038
MD
2709;;; The default repl-reader function. We may override this if we've
2710;;; the readline library.
2711(define repl-reader
17ee350c 2712 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
0becb8f3
AW
2713 (if (not (char-ready?))
2714 (display (if (string? prompt) prompt (prompt))))
dc5c2038 2715 (force-output)
04efd24d 2716 (run-hook before-read-hook)
17ee350c 2717 ((or reader read) (current-input-port))))
dc5c2038 2718
0f2d19dd 2719
0f2d19dd 2720\f
3d2ada2f 2721
44cf1f0f 2722;;; {IOTA functions: generating lists of numbers}
3d2ada2f 2723;;;
0f2d19dd 2724
e69cd299
MD
2725(define (iota n)
2726 (let loop ((count (1- n)) (result '()))
2727 (if (< count 0) result
2728 (loop (1- count) (cons count result)))))
0f2d19dd
JB
2729
2730\f
3d2ada2f 2731
773abfbb
KR
2732;;; {While}
2733;;;
2734;;; with `continue' and `break'.
2735;;;
2736
10e69149
AW
2737;; The inliner will remove the prompts at compile-time if it finds that
2738;; `continue' or `break' are not used.
2739;;
2740(define-syntax while
2741 (lambda (x)
2742 (syntax-case x ()
2743 ((while cond body ...)
2744 #`(let ((break-tag (make-prompt-tag "break"))
2745 (continue-tag (make-prompt-tag "continue")))
2746 (call-with-prompt
2747 break-tag
2748 (lambda ()
2749 (define-syntax #,(datum->syntax #'while 'break)
2750 (lambda (x)
2751 (syntax-case x ()
2752 ((_)
2753 #'(abort-to-prompt break-tag))
2754 ((_ . args)
2755 (syntax-violation 'break "too many arguments" x))
2756 (_
2757 #'(lambda ()
2758 (abort-to-prompt break-tag))))))
2759 (let lp ()
2760 (call-with-prompt
2761 continue-tag
2762 (lambda ()
2763 (define-syntax #,(datum->syntax #'while 'continue)
2764 (lambda (x)
2765 (syntax-case x ()
2766 ((_)
2767 #'(abort-to-prompt continue-tag))
2768 ((_ . args)
2769 (syntax-violation 'continue "too many arguments" x))
2770 (_
2771 #'(lambda args
2772 (apply abort-to-prompt continue-tag args))))))
2773 (do () ((not cond)) body ...))
2774 (lambda (k) (lp)))))
2775 (lambda (k)
2776 #t)))))))
5578a53f 2777
773abfbb 2778
0f2d19dd 2779\f
3d2ada2f 2780
0f2d19dd
JB
2781;;; {Module System Macros}
2782;;;
2783
532cf805
MV
2784;; Return a list of expressions that evaluate to the appropriate
2785;; arguments for resolve-interface according to SPEC.
2786
b15dea68 2787(eval-when
25d8cd3a
AW
2788 (compile)
2789 (if (memq 'prefix (read-options))
2790 (error "boot-9 must be compiled with #:kw, not :kw")))
1a1a10d3 2791
532cf805
MV
2792(define (keyword-like-symbol->keyword sym)
2793 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2794
074e036e
AW
2795;; FIXME: we really need to clean up the guts of the module system.
2796;; We can compile to something better than process-define-module.
2797(define-syntax define-module
2798 (lambda (x)
2799 (define (keyword-like? stx)
2800 (let ((dat (syntax->datum stx)))
2801 (and (symbol? dat)
2802 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2803 (define (->keyword sym)
2804 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2805
2806 (define (quotify-iface args)
2807 (let loop ((in args) (out '()))
2808 (syntax-case in ()
2809 (() (reverse! out))
2810 ;; The user wanted #:foo, but wrote :foo. Fix it.
2811 ((sym . in) (keyword-like? #'sym)
2812 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2813 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2814 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2815 ((#:renamer renamer . in)
2816 (loop #'in (cons* #'renamer #:renamer out)))
2817 ((kw val . in)
2818 (loop #'in (cons* #''val #'kw out))))))
2819
2820 (define (quotify args)
2821 ;; Just quote everything except #:use-module and #:use-syntax. We
2822 ;; need to know about all arguments regardless since we want to turn
2823 ;; symbols that look like keywords into real keywords, and the
2824 ;; keyword args in a define-module form are not regular
2825 ;; (i.e. no-backtrace doesn't take a value).
2826 (let loop ((in args) (out '()))
2827 (syntax-case in ()
2828 (() (reverse! out))
2829 ;; The user wanted #:foo, but wrote :foo. Fix it.
2830 ((sym . in) (keyword-like? #'sym)
2831 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2832 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2833 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2834 ((#:no-backtrace . in)
2835 (loop #'in (cons #:no-backtrace out)))
2836 ((#:pure . in)
2837 (loop #'in (cons #:pure out)))
2838 ((kw)
2839 (syntax-violation 'define-module "keyword arg without value" x #'kw))
2840 ((use-module (name name* ...) . in)
2841 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2842 (and-map symbol? (syntax->datum #'(name name* ...))))
2843 (loop #'in
2844 (cons* #''((name name* ...))
2845 #'use-module
2846 out)))
2847 ((use-module ((name name* ...) arg ...) . in)
2848 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2849 (and-map symbol? (syntax->datum #'(name name* ...))))
2850 (loop #'in
2851 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
2852 #'use-module
2853 out)))
2854 ((#:autoload name bindings . in)
2855 (loop #'in (cons* #''bindings #''name #:autoload out)))
2856 ((kw val . in)
2857 (loop #'in (cons* #''val #'kw out))))))
2858
2859 (syntax-case x ()
2860 ((_ (name name* ...) arg ...)
2861 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
d9b1c71a 2862 #'(eval-when (eval load compile expand)
074e036e 2863 (let ((m (process-define-module
78f79f18
AW
2864 (list '(name name* ...)
2865 #:filename (assq-ref
2866 (or (current-source-location) '())
2867 'filename)
2868 quoted-arg ...))))
074e036e
AW
2869 (set-current-module m)
2870 m)))))))
0f2d19dd 2871
532cf805
MV
2872;; The guts of the use-modules macro. Add the interfaces of the named
2873;; modules to the use-list of the current module, in order.
2874
482a28f9
MV
2875;; This function is called by "modules.c". If you change it, be sure
2876;; to change scm_c_use_module as well.
2877
532cf805 2878(define (process-use-modules module-interface-args)
d57da08b 2879 (let ((interfaces (map (lambda (mif-args)
9b5a0d84
AW
2880 (or (apply resolve-interface mif-args)
2881 (error "no such module" mif-args)))
2882 module-interface-args)))
d57da08b
MD
2883 (call-with-deferred-observers
2884 (lambda ()
2885 (module-use-interfaces! (current-module) interfaces)))))
89da9036 2886
4e3328ce
AW
2887(define-syntax use-modules
2888 (lambda (x)
2889 (define (keyword-like? stx)
2890 (let ((dat (syntax->datum stx)))
2891 (and (symbol? dat)
2892 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2893 (define (->keyword sym)
2894 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2895
2896 (define (quotify-iface args)
2897 (let loop ((in args) (out '()))
2898 (syntax-case in ()
2899 (() (reverse! out))
2900 ;; The user wanted #:foo, but wrote :foo. Fix it.
2901 ((sym . in) (keyword-like? #'sym)
2902 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2903 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2904 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2905 ((#:renamer renamer . in)
2906 (loop #'in (cons* #'renamer #:renamer out)))
2907 ((kw val . in)
2908 (loop #'in (cons* #''val #'kw out))))))
2909
2910 (define (quotify specs)
2911 (let lp ((in specs) (out '()))
2912 (syntax-case in ()
2913 (() (reverse out))
2914 (((name name* ...) . in)
2915 (and-map symbol? (syntax->datum #'(name name* ...)))
2916 (lp #'in (cons #''((name name* ...)) out)))
2917 ((((name name* ...) arg ...) . in)
2918 (and-map symbol? (syntax->datum #'(name name* ...)))
2919 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
2920 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
2921 out)))))))
2922
2923 (syntax-case x ()
2924 ((_ spec ...)
2925 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
520caaeb 2926 #'(eval-when (eval load compile expand)
4e3328ce
AW
2927 (process-use-modules (list quoted-args ...))
2928 *unspecified*))))))
2929
2930(define-syntax use-syntax
2931 (syntax-rules ()
2932 ((_ spec ...)
2933 (begin
520caaeb 2934 (eval-when (eval load compile expand)
4e3328ce
AW
2935 (issue-deprecation-warning
2936 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
2937 (use-modules spec ...)))))
0f2d19dd 2938
b1e4c7cc
JG
2939(include-from-path "ice-9/r6rs-libraries")
2940
13182603
AW
2941(define-syntax define-private
2942 (syntax-rules ()
2943 ((_ foo bar)
2944 (define foo bar))))
2945
2946(define-syntax define-public
2947 (syntax-rules ()
2948 ((_ (name . args) . body)
2949 (define-public name (lambda args . body)))
2950 ((_ name val)
2951 (begin
2952 (define name val)
2953 (export name)))))
2954
2955(define-syntax defmacro-public
2956 (syntax-rules ()
2957 ((_ name args . body)
2958 (begin
2959 (defmacro name args . body)
2960 (export-syntax name)))))
0f2d19dd 2961
87e00370
LC
2962;; And now for the most important macro.
2963(define-syntax λ
2964 (syntax-rules ()
2965 ((_ formals body ...)
2966 (lambda formals body ...))))
2967
2968\f
89d06712 2969;; Export a local variable
482a28f9
MV
2970
2971;; This function is called from "modules.c". If you change it, be
2972;; sure to update "modules.c" as well.
2973
90847923
MD
2974(define (module-export! m names)
2975 (let ((public-i (module-public-interface m)))
2976 (for-each (lambda (name)
78c22f5e
JG
2977 (let* ((internal-name (if (pair? name) (car name) name))
2978 (external-name (if (pair? name) (cdr name) name))
2979 (var (module-ensure-local-variable! m internal-name)))
2980 (module-add! public-i external-name var)))
9b5a0d84 2981 names)))
89d06712 2982
f595ccfe
MD
2983(define (module-replace! 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)))
9b5a0d84 2989 (set-object-property! var 'replace #t)
78c22f5e 2990 (module-add! public-i external-name var)))
9b5a0d84 2991 names)))
f595ccfe 2992
d2b7b761
AW
2993;; Export all local variables from a module
2994;;
2995(define (module-export-all! mod)
2996 (define (fresh-interface!)
2997 (let ((iface (make-module)))
2998 (set-module-name! iface (module-name mod))
e5602ce7 2999 (set-module-version! iface (module-version mod))
d2b7b761
AW
3000 (set-module-kind! iface 'interface)
3001 (set-module-public-interface! mod iface)
3002 iface))
3003 (let ((iface (or (module-public-interface mod)
3004 (fresh-interface!))))
3005 (set-module-obarray! iface (module-obarray mod))))
3006
89d06712
MV
3007;; Re-export a imported variable
3008;;
3009(define (module-re-export! m names)
3010 (let ((public-i (module-public-interface m)))
3011 (for-each (lambda (name)
78c22f5e
JG
3012 (let* ((internal-name (if (pair? name) (car name) name))
3013 (external-name (if (pair? name) (cdr name) name))
3014 (var (module-variable m internal-name)))
9b5a0d84 3015 (cond ((not var)
78c22f5e
JG
3016 (error "Undefined variable:" internal-name))
3017 ((eq? var (module-local-variable m internal-name))
3018 (error "re-exporting local variable:" internal-name))
9b5a0d84 3019 (else
78c22f5e 3020 (module-add! public-i external-name var)))))
9b5a0d84 3021 names)))
90847923 3022
d6151723
AW
3023(define-syntax export
3024 (syntax-rules ()
3025 ((_ name ...)
520caaeb 3026 (eval-when (eval load compile expand)
d6151723
AW
3027 (call-with-deferred-observers
3028 (lambda ()
3029 (module-export! (current-module) '(name ...))))))))
a0cc0a01 3030
d6151723
AW
3031(define-syntax re-export
3032 (syntax-rules ()
3033 ((_ name ...)
520caaeb 3034 (eval-when (eval load compile expand)
d6151723
AW
3035 (call-with-deferred-observers
3036 (lambda ()
3037 (module-re-export! (current-module) '(name ...))))))))
89d06712 3038
d6151723
AW
3039(define-syntax export-syntax
3040 (syntax-rules ()
3041 ((_ name ...)
3042 (export name ...))))
a0cc0a01 3043
d6151723
AW
3044(define-syntax re-export-syntax
3045 (syntax-rules ()
3046 ((_ name ...)
3047 (re-export name ...))))
a0cc0a01 3048
0f2d19dd
JB
3049(define load load-module)
3050
3de80ed5
AW
3051\f
3052
f595ccfe
MD
3053;;; {Parameters}
3054;;;
3055
3056(define make-mutable-parameter
3057 (let ((make (lambda (fluid converter)
9b5a0d84
AW
3058 (lambda args
3059 (if (null? args)
3060 (fluid-ref fluid)
3061 (fluid-set! fluid (converter (car args))))))))
7df2621d
AW
3062 (lambda* (init #:optional (converter identity))
3063 (let ((fluid (make-fluid)))
9b5a0d84
AW
3064 (fluid-set! fluid (converter init))
3065 (make fluid converter)))))
f595ccfe
MD
3066
3067\f
3d2ada2f 3068
7b07e5ef
MD
3069;;; {Handling of duplicate imported bindings}
3070;;;
3071
3072;; Duplicate handlers take the following arguments:
3073;;
3074;; module importing module
9b5a0d84
AW
3075;; name conflicting name
3076;; int1 old interface where name occurs
3077;; val1 value of binding in old interface
3078;; int2 new interface where name occurs
3079;; val2 value of binding in new interface
3080;; var previous resolution or #f
3081;; val value of previous resolution
7b07e5ef
MD
3082;;
3083;; A duplicate handler can take three alternative actions:
3084;;
3085;; 1. return #f => leave responsibility to next handler
3086;; 2. exit with an error
3087;; 3. return a variable resolving the conflict
3088;;
3089
3090(define duplicate-handlers
3091 (let ((m (make-module 7)))
f595ccfe
MD
3092
3093 (define (check module name int1 val1 int2 val2 var val)
3094 (scm-error 'misc-error
9b5a0d84
AW
3095 #f
3096 "~A: `~A' imported from both ~A and ~A"
3097 (list (module-name module)
3098 name
3099 (module-name int1)
3100 (module-name int2))
3101 #f))
f595ccfe 3102
65bed4aa 3103 (define (warn module name int1 val1 int2 val2 var val)
d7c0c26d 3104 (format (current-error-port)
9b5a0d84
AW
3105 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3106 (module-name module)
3107 name
3108 (module-name int1)
3109 (module-name int2))
65bed4aa 3110 #f)
f595ccfe
MD
3111
3112 (define (replace module name int1 val1 int2 val2 var val)
3113 (let ((old (or (and var (object-property var 'replace) var)
9b5a0d84
AW
3114 (module-variable int1 name)))
3115 (new (module-variable int2 name)))
3116 (if (object-property old 'replace)
3117 (and (or (eq? old new)
3118 (not (object-property new 'replace)))
3119 old)
3120 (and (object-property new 'replace)
3121 new))))
f595ccfe 3122
65bed4aa
MD
3123 (define (warn-override-core module name int1 val1 int2 val2 var val)
3124 (and (eq? int1 the-scm-module)
9b5a0d84
AW
3125 (begin
3126 (format (current-error-port)
3127 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3128 (module-name module)
3129 (module-name int2)
3130 name)
3131 (module-local-variable int2 name))))
f595ccfe 3132
65bed4aa
MD
3133 (define (first module name int1 val1 int2 val2 var val)
3134 (or var (module-local-variable int1 name)))
f595ccfe 3135
65bed4aa
MD
3136 (define (last module name int1 val1 int2 val2 var val)
3137 (module-local-variable int2 name))
f595ccfe 3138
65bed4aa
MD
3139 (define (noop module name int1 val1 int2 val2 var val)
3140 #f)
3141
7b07e5ef
MD
3142 (set-module-name! m 'duplicate-handlers)
3143 (set-module-kind! m 'interface)
f595ccfe
MD
3144 (module-define! m 'check check)
3145 (module-define! m 'warn warn)
3146 (module-define! m 'replace replace)
3147 (module-define! m 'warn-override-core warn-override-core)
3148 (module-define! m 'first first)
3149 (module-define! m 'last last)
65bed4aa
MD
3150 (module-define! m 'merge-generics noop)
3151 (module-define! m 'merge-accessors noop)
7b07e5ef
MD
3152 m))
3153
f595ccfe 3154(define (lookup-duplicates-handlers handler-names)
109c2c9f
MD
3155 (and handler-names
3156 (map (lambda (handler-name)
9b5a0d84
AW
3157 (or (module-symbol-local-binding
3158 duplicate-handlers handler-name #f)
3159 (error "invalid duplicate handler name:"
3160 handler-name)))
3161 (if (list? handler-names)
3162 handler-names
3163 (list handler-names)))))
f595ccfe 3164
70a459e3
MD
3165(define default-duplicate-binding-procedures
3166 (make-mutable-parameter #f))
3167
3168(define default-duplicate-binding-handler
6496a663 3169 (make-mutable-parameter '(replace warn-override-core warn last)
9b5a0d84
AW
3170 (lambda (handler-names)
3171 (default-duplicate-binding-procedures
3172 (lookup-duplicates-handlers handler-names))
3173 handler-names)))
f595ccfe 3174
7b07e5ef 3175\f
7f24bc58
MG
3176
3177;;; {`cond-expand' for SRFI-0 support.}
3178;;;
3179;;; This syntactic form expands into different commands or
3180;;; definitions, depending on the features provided by the Scheme
3181;;; implementation.
3182;;;
3183;;; Syntax:
3184;;;
3185;;; <cond-expand>
3186;;; --> (cond-expand <cond-expand-clause>+)
3187;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3188;;; <cond-expand-clause>
3189;;; --> (<feature-requirement> <command-or-definition>*)
3190;;; <feature-requirement>
3191;;; --> <feature-identifier>
3192;;; | (and <feature-requirement>*)
3193;;; | (or <feature-requirement>*)
3194;;; | (not <feature-requirement>)
3195;;; <feature-identifier>
3196;;; --> <a symbol which is the name or alias of a SRFI>
3197;;;
3198;;; Additionally, this implementation provides the
3199;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3200;;; determine the implementation type and the supported standard.
3201;;;
3202;;; Currently, the following feature identifiers are supported:
3203;;;
08b609aa 3204;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
7f24bc58
MG
3205;;;
3206;;; Remember to update the features list when adding more SRFIs.
3d2ada2f 3207;;;
7f24bc58 3208
b9b8f9da 3209(define %cond-expand-features
f41be016 3210 ;; Adjust the above comment when changing this.
018733ff 3211 '(guile
60c8ad9e 3212 guile-2
018733ff
KR
3213 r5rs
3214 srfi-0 ;; cond-expand itself
85acb35f 3215 srfi-4 ;; homogenous numeric vectors
018733ff 3216 srfi-6 ;; open-input-string etc, in the guile core
4a276c08
MV
3217 srfi-13 ;; string library
3218 srfi-14 ;; character sets
344d68d5 3219 srfi-55 ;; require-extension
08b609aa 3220 srfi-61 ;; general cond clause
018733ff 3221 ))
1d00af09 3222
b9b8f9da
MG
3223;; This table maps module public interfaces to the list of features.
3224;;
3225(define %cond-expand-table (make-hash-table 31))
3226
3227;; Add one or more features to the `cond-expand' feature list of the
3228;; module `module'.
3229;;
3230(define (cond-expand-provide module features)
3231 (let ((mod (module-public-interface module)))
3232 (and mod
9b5a0d84
AW
3233 (hashq-set! %cond-expand-table mod
3234 (append (hashq-ref %cond-expand-table mod '())
3235 features)))))
b9b8f9da 3236
f4bf64b4
LC
3237(define-macro (cond-expand . clauses)
3238 (let ((syntax-error (lambda (cl)
3239 (error "invalid clause in `cond-expand'" cl))))
3240 (letrec
3241 ((test-clause
3242 (lambda (clause)
3243 (cond
3244 ((symbol? clause)
3245 (or (memq clause %cond-expand-features)
3246 (let lp ((uses (module-uses (current-module))))
3247 (if (pair? uses)
3248 (or (memq clause
3249 (hashq-ref %cond-expand-table
3250 (car uses) '()))
3251 (lp (cdr uses)))
3252 #f))))
3253 ((pair? clause)
3254 (cond
3255 ((eq? 'and (car clause))
3256 (let lp ((l (cdr clause)))
3257 (cond ((null? l)
3258 #t)
3259 ((pair? l)
3260 (and (test-clause (car l)) (lp (cdr l))))
3261 (else
3262 (syntax-error clause)))))
3263 ((eq? 'or (car clause))
3264 (let lp ((l (cdr clause)))
3265 (cond ((null? l)
3266 #f)
3267 ((pair? l)
3268 (or (test-clause (car l)) (lp (cdr l))))
3269 (else
3270 (syntax-error clause)))))
3271 ((eq? 'not (car clause))
3272 (cond ((not (pair? (cdr clause)))
3273 (syntax-error clause))
3274 ((pair? (cddr clause))
3275 ((syntax-error clause))))
3276 (not (test-clause (cadr clause))))
3277 (else
3278 (syntax-error clause))))
3279 (else
3280 (syntax-error clause))))))
3281 (let lp ((c clauses))
3282 (cond
3283 ((null? c)
3284 (error "Unfulfilled `cond-expand'"))
3285 ((not (pair? c))
3286 (syntax-error c))
3287 ((not (pair? (car c)))
3288 (syntax-error (car c)))
3289 ((test-clause (caar c))
3290 `(begin ,@(cdar c)))
3291 ((eq? (caar c) 'else)
3292 (if (pair? (cdr c))
3293 (syntax-error c))
3294 `(begin ,@(cdar c)))
3295 (else
3296 (lp (cdr c))))))))
0f2d19dd 3297
f41be016
MG
3298;; This procedure gets called from the startup code with a list of
3299;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3300;;
3301(define (use-srfis srfis)
9a18d8d4
KR
3302 (process-use-modules
3303 (map (lambda (num)
9b5a0d84
AW
3304 (list (list 'srfi (string->symbol
3305 (string-append "srfi-" (number->string num))))))
3306 srfis)))
f8a502cb 3307
0f2d19dd 3308\f
9d774814 3309
344d68d5
RB
3310;;; srfi-55: require-extension
3311;;;
3312
3313(define-macro (require-extension extension-spec)
3314 ;; This macro only handles the srfi extension, which, at present, is
3315 ;; the only one defined by the standard.
3316 (if (not (pair? extension-spec))
3317 (scm-error 'wrong-type-arg "require-extension"
3318 "Not an extension: ~S" (list extension-spec) #f))
3319 (let ((extension (car extension-spec))
3320 (extension-args (cdr extension-spec)))
3321 (case extension
3322 ((srfi)
3323 (let ((use-list '()))
3324 (for-each
3325 (lambda (i)
3326 (if (not (integer? i))
3327 (scm-error 'wrong-type-arg "require-extension"
3328 "Invalid srfi name: ~S" (list i) #f))
3329 (let ((srfi-sym (string->symbol
3330 (string-append "srfi-" (number->string i)))))
3331 (if (not (memq srfi-sym %cond-expand-features))
3332 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3333 use-list)))))
3334 extension-args)
3335 (if (pair? use-list)
3336 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3337 `(begin ,@(reverse! use-list)))))
3338 (else
3339 (scm-error
3340 'wrong-type-arg "require-extension"
3341 "Not a recognized extension type: ~S" (list extension) #f)))))
3342
3343\f
3344
9aca88c3 3345;;; {Load emacs interface support if emacs option is given.}
3d2ada2f 3346;;;
9aca88c3 3347
645e38d9 3348(define (named-module-use! user usee)
89d06712 3349 (module-use! (resolve-module user) (resolve-interface usee)))
645e38d9 3350
9aca88c3 3351(define (load-emacs-interface)
fb1b76f4
TTN
3352 (and (provided? 'debug-extensions)
3353 (debug-enable 'backtrace))
645e38d9 3354 (named-module-use! '(guile-user) '(ice-9 emacs)))
9aca88c3
JB
3355
3356\f
0f2d19dd 3357
755457ec
MD
3358(define using-readline?
3359 (let ((using-readline? (make-fluid)))
3360 (make-procedure-with-setter
3361 (lambda () (fluid-ref using-readline?))
3362 (lambda (v) (fluid-set! using-readline? v)))))
3363
20edfbbd 3364(define (top-repl)
615bfe72
MV
3365 (let ((guile-user-module (resolve-module '(guile-user))))
3366
3367 ;; Load emacs interface support if emacs option is given.
454b82f4 3368 (if (and (module-defined? guile-user-module 'use-emacs-interface)
9b5a0d84
AW
3369 (module-ref guile-user-module 'use-emacs-interface))
3370 (load-emacs-interface))
615bfe72
MV
3371
3372 ;; Use some convenient modules (in reverse order)
bbf5a913 3373
9a18d8d4
KR
3374 (set-current-module guile-user-module)
3375 (process-use-modules
3376 (append
3377 '(((ice-9 r5rs))
9b5a0d84
AW
3378 ((ice-9 session))
3379 ((ice-9 debug)))
9a18d8d4 3380 (if (provided? 'regex)
9b5a0d84
AW
3381 '(((ice-9 regex)))
3382 '())
9a18d8d4 3383 (if (provided? 'threads)
9b5a0d84
AW
3384 '(((ice-9 threads)))
3385 '())))
615bfe72 3386 ;; load debugger on demand
42ee0d00 3387 (module-autoload! guile-user-module '(system vm debug) '(debug))
615bfe72 3388
9a18d8d4
KR
3389 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3390 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3391 ;; no effect.
615bfe72 3392 (let ((old-handlers #f)
02fcbf78
AW
3393 ;; We can't use @ here, as modules have been booted, but in Guile's
3394 ;; build the srfi-1 helper lib hasn't been built yet, which will
3395 ;; result in an error when (system repl repl) is loaded at compile
3396 ;; time (to see if it is a macro or not).
3397 (start-repl (module-ref (resolve-module '(system repl repl))
3398 'start-repl))
9b5a0d84
AW
3399 (signals (if (provided? 'posix)
3400 `((,SIGINT . "User interrupt")
3401 (,SIGFPE . "Arithmetic error")
3402 (,SIGSEGV
3403 . "Bad memory access (Segmentation violation)"))
3404 '())))
9a18d8d4
KR
3405 ;; no SIGBUS on mingw
3406 (if (defined? 'SIGBUS)
9b5a0d84
AW
3407 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3408 signals)))
615bfe72
MV
3409
3410 (dynamic-wind
3411
9b5a0d84
AW
3412 ;; call at entry
3413 (lambda ()
3414 (let ((make-handler (lambda (msg)
3415 (lambda (sig)
9b5a0d84
AW
3416 (scm-error 'signal
3417 #f
3418 msg
3419 #f
3420 (list sig))))))
3421 (set! old-handlers
3422 (map (lambda (sig-msg)
3423 (sigaction (car sig-msg)
3424 (make-handler (cdr sig-msg))))
3425 signals))))
3426
3427 ;; the protected thunk.
3428 (lambda ()
6a01fabf 3429 (let ((status (start-repl 'scheme)))
9b5a0d84
AW
3430 (run-hook exit-hook)
3431 status))
3432
3433 ;; call at exit.
3434 (lambda ()
3435 (map (lambda (sig-msg old-handler)
3436 (if (not (car old-handler))
3437 ;; restore original C handler.
3438 (sigaction (car sig-msg) #f)
3439 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3440 (sigaction (car sig-msg)
3441 (car old-handler)
3442 (cdr old-handler))))
3443 signals old-handlers))))))
0f2d19dd 3444
2055a1bc
MD
3445;;; This hook is run at the very end of an interactive session.
3446;;;
3e3cec45 3447(define exit-hook (make-hook))
2055a1bc 3448
4d31f0da 3449\f
3d2ada2f
DH
3450
3451;;; {Deprecated stuff}
3452;;;
3453
3d2ada2f 3454(begin-deprecated
0ea72faa 3455 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3d2ada2f
DH
3456
3457\f
3458
3459;;; Place the user in the guile-user module.
3460;;;
6eb396fe 3461
a2689737
AW
3462;; FIXME:
3463(module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3464
68623e8e
AW
3465(define-module (guile-user)
3466 #:autoload (system base compile) (compile))
6d36532c 3467
7385dc12
LC
3468;; Remain in the `(guile)' module at compilation-time so that the
3469;; `-Wunused-toplevel' warning works as expected.
3470(eval-when (compile) (set-current-module the-root-module))
3471
20edfbbd 3472;;; boot-9.scm ends here