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