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