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