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