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