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