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