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