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