brown-paper-bag to uninstalled-env
[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)))))))
dc232ed0 2349 (not (numlist-less (car pair2) (car pair1))))
dca14012
JG
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)
dc232ed0 2357 (string-append (cdr pair) name ext))
dca14012
JG
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
dc232ed0 2368 (let* ((subdir (string-append (cdr root-pair) entry))
dca14012 2369 (num (string->number entry))
dc232ed0
JG
2370 (num (and num (exact? num) (append (car root-pair)
2371 (list num)))))
dca14012 2372 (if (and num (eq? (stat:type (stat subdir)) 'directory))
dc232ed0
JG
2373 (filter-subdir
2374 root-pair dstrm (cons (cons num (string-append subdir "/"))
2375 subdir-pairs))
dca14012
JG
2376 (filter-subdir root-pair dstrm subdir-pairs))))))
2377
2378 (or (and (null? root-pairs) ret)
2379 (let* ((rp (car root-pairs))
2380 (dstrm (false-if-exception (opendir (cdr rp)))))
2381 (if dstrm
2382 (let ((subdir-pairs (filter-subdir rp dstrm '())))
2383 (closedir dstrm)
2384 (filter-subdirs (cdr root-pairs)
2385 (or (and (null? subdir-pairs) ret)
2386 (append ret subdir-pairs))))
2387 (filter-subdirs (cdr root-pairs) ret)))))
2388
2389 (or (and (null? root-pairs) leaf-pairs)
2390 (let ((matching-subdir-pairs (filter-subdirs root-pairs '())))
2391 (match-version-recursive
2392 matching-subdir-pairs
2393 (append leaf-pairs (filter pair? (map match-version-and-file
2394 matching-subdir-pairs)))))))
2395 (define (make-root-pair root)
2396 (cons '() (string-append root "/" dir-hint)))
2397
2398 (let* ((root-pairs (map make-root-pair roots))
2399 (matches (if (null? version-ref)
2400 (filter pair? (map match-version-and-file root-pairs))
2401 '()))
2402 (matches (append matches (match-version-recursive root-pairs '()))))
2403 (and (null? matches) (error "No matching modules found."))
2404 (cdar (sort matches subdir-pair-less))))
2405
f95f82f8
AW
2406(define (make-fresh-user-module)
2407 (let ((m (make-module)))
2408 (beautify-user-module! m)
2409 m))
2410
1f60d9d2
MD
2411;; NOTE: This binding is used in libguile/modules.c.
2412;;
53f84bc8 2413(define resolve-module
cb67c838
AW
2414 (let ((root (make-module)))
2415 (set-module-name! root '())
2416 ;; Define the-root-module as '(guile).
d58ccc66 2417 (module-define-submodule! root 'guile the-root-module)
cb67c838 2418
6b7d701e
AW
2419 (lambda* (name #:optional (autoload #t) (version #f))
2420 (let ((already (nested-ref-module root name)))
cb67c838 2421 (cond
d58ccc66 2422 ((and already
cb67c838
AW
2423 (or (not autoload) (module-public-interface already)))
2424 ;; A hit, a palpable hit.
2425 (if (and version
2426 (not (version-matches? version (module-version already))))
2427 (error "incompatible module version already loaded" name))
2428 already)
2429 (autoload
2430 ;; Try to autoload the module, and recurse.
2431 (try-load-module name version)
2432 (resolve-module name #f))
2433 (else
51b22dbb
AW
2434 ;; No module found (or if one was, it had no public interface), and
2435 ;; we're not autoloading. Here's the weird semantics: we ensure
2436 ;; there's an empty module.
2437 (or already (make-modules-in root name))))))))
cb67c838 2438
296ff5e7 2439
dca14012
JG
2440(define (try-load-module name version)
2441 (try-module-autoload name version))
0f2d19dd 2442
90847923
MD
2443(define (purify-module! module)
2444 "Removes bindings in MODULE which are inherited from the (guile) module."
2445 (let ((use-list (module-uses module)))
2446 (if (and (pair? use-list)
9b5a0d84
AW
2447 (eq? (car (last-pair use-list)) the-scm-module))
2448 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
90847923 2449
4eecfeb7 2450;; Return a module that is an interface to the module designated by
532cf805
MV
2451;; NAME.
2452;;
c614a00b 2453;; `resolve-interface' takes four keyword arguments:
532cf805
MV
2454;;
2455;; #:select SELECTION
2456;;
2457;; SELECTION is a list of binding-specs to be imported; A binding-spec
2458;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2459;; is the name in the used module and SEEN is the name in the using
2460;; module. Note that SEEN is also passed through RENAMER, below. The
2461;; default is to select all bindings. If you specify no selection but
4eecfeb7 2462;; a renamer, only the bindings that already exist in the used module
532cf805
MV
2463;; are made available in the interface. Bindings that are added later
2464;; are not picked up.
2465;;
c614a00b 2466;; #:hide BINDINGS
532cf805 2467;;
c614a00b 2468;; BINDINGS is a list of bindings which should not be imported.
f595ccfe
MD
2469;;
2470;; #:prefix PREFIX
2471;;
2472;; PREFIX is a symbol that will be appended to each exported name.
2473;; The default is to not perform any renaming.
532cf805 2474;;
c614a00b
MD
2475;; #:renamer RENAMER
2476;;
2477;; RENAMER is a procedure that takes a symbol and returns its new
2478;; name. The default is not perform any renaming.
2479;;
532cf805
MV
2480;; Signal "no code for module" error if module name is not resolvable
2481;; or its public interface is not available. Signal "no binding"
2482;; error if selected binding does not exist in the used module.
2483;;
36d58fc3
AW
2484(define* (resolve-interface name #:key
2485 (select #f)
2486 (hide '())
2487 (prefix #f)
2488 (renamer (if prefix
2489 (symbol-prefix-proc prefix)
2490 identity))
2491 version)
2492 (let* ((module (resolve-module name #t version))
b622dec7
TTN
2493 (public-i (and module (module-public-interface module))))
2494 (and (or (not module) (not public-i))
2495 (error "no code for module" name))
c614a00b 2496 (if (and (not select) (null? hide) (eq? renamer identity))
b622dec7 2497 public-i
532cf805 2498 (let ((selection (or select (module-map (lambda (sym var) sym)
9b5a0d84 2499 public-i)))
b622dec7 2500 (custom-i (make-module 31)))
c614a00b 2501 (set-module-kind! custom-i 'custom-interface)
9b5a0d84
AW
2502 (set-module-name! custom-i name)
2503 ;; XXX - should use a lazy binder so that changes to the
2504 ;; used module are picked up automatically.
2505 (for-each (lambda (bspec)
2506 (let* ((direct? (symbol? bspec))
2507 (orig (if direct? bspec (car bspec)))
2508 (seen (if direct? bspec (cdr bspec)))
2509 (var (or (module-local-variable public-i orig)
2510 (module-local-variable module orig)
2511 (error
2512 ;; fixme: format manually for now
2513 (simple-format
2514 #f "no binding `~A' in module ~A"
2515 orig name)))))
2516 (if (memq orig hide)
2517 (set! hide (delq! orig hide))
2518 (module-add! custom-i
2519 (renamer seen)
2520 var))))
2521 selection)
2522 ;; Check that we are not hiding bindings which don't exist
2523 (for-each (lambda (binding)
2524 (if (not (module-local-variable public-i binding))
2525 (error
2526 (simple-format
2527 #f "no binding `~A' to hide in module ~A"
2528 binding name))))
2529 hide)
b622dec7 2530 custom-i))))
fb1b76f4
TTN
2531
2532(define (symbol-prefix-proc prefix)
2533 (lambda (symbol)
2534 (symbol-append prefix symbol)))
0f2d19dd 2535
482a28f9
MV
2536;; This function is called from "modules.c". If you change it, be
2537;; sure to update "modules.c" as well.
2538
0f2d19dd 2539(define (process-define-module args)
f8a502cb
TTN
2540 (let* ((module-id (car args))
2541 (module (resolve-module module-id #f))
2542 (kws (cdr args))
2543 (unrecognized (lambda (arg)
2544 (error "unrecognized define-module argument" arg))))
0f2d19dd 2545 (beautify-user-module! module)
0209ca9a 2546 (let loop ((kws kws)
1b92d94c
AW
2547 (reversed-interfaces '())
2548 (exports '())
2549 (re-exports '())
2550 (replacements '())
608860a5 2551 (autoloads '()))
e4da0740 2552
0209ca9a 2553 (if (null? kws)
1b92d94c
AW
2554 (call-with-deferred-observers
2555 (lambda ()
2556 (module-use-interfaces! module (reverse reversed-interfaces))
2557 (module-export! module exports)
2558 (module-replace! module replacements)
2559 (module-re-export! module re-exports)
608860a5
LC
2560 (if (not (null? autoloads))
2561 (apply module-autoload! module autoloads))))
1b92d94c
AW
2562 (case (car kws)
2563 ((#:use-module #:use-syntax)
2564 (or (pair? (cdr kws))
2565 (unrecognized kws))
13182603
AW
2566 (cond
2567 ((equal? (caadr kws) '(ice-9 syncase))
2568 (issue-deprecation-warning
2569 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
1b92d94c 2570 (loop (cddr kws)
13182603 2571 reversed-interfaces
1b92d94c
AW
2572 exports
2573 re-exports
2574 replacements
13182603
AW
2575 autoloads))
2576 (else
2577 (let* ((interface-args (cadr kws))
2578 (interface (apply resolve-interface interface-args)))
2579 (and (eq? (car kws) #:use-syntax)
2580 (or (symbol? (caar interface-args))
2581 (error "invalid module name for use-syntax"
2582 (car interface-args)))
2583 (set-module-transformer!
2584 module
2585 (module-ref interface
2586 (car (last-pair (car interface-args)))
2587 #f)))
2588 (loop (cddr kws)
2589 (cons interface reversed-interfaces)
2590 exports
2591 re-exports
2592 replacements
2593 autoloads)))))
1b92d94c
AW
2594 ((#:autoload)
2595 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2596 (unrecognized kws))
2597 (loop (cdddr kws)
608860a5 2598 reversed-interfaces
1b92d94c
AW
2599 exports
2600 re-exports
2601 replacements
608860a5
LC
2602 (let ((name (cadr kws))
2603 (bindings (caddr kws)))
2604 (cons* name bindings autoloads))))
1b92d94c
AW
2605 ((#:no-backtrace)
2606 (set-system-module! module #t)
2607 (loop (cdr kws) reversed-interfaces exports re-exports
608860a5 2608 replacements autoloads))
1b92d94c
AW
2609 ((#:pure)
2610 (purify-module! module)
2611 (loop (cdr kws) reversed-interfaces exports re-exports
608860a5 2612 replacements autoloads))
dca14012
JG
2613 ((#:version)
2614 (or (pair? (cdr kws))
2615 (unrecognized kws))
2616 (let ((version (cadr kws)))
2617 (set-module-version! module version)
2618 (set-module-version! (module-public-interface module) version))
2619 (loop (cddr kws) reversed-interfaces exports re-exports
2620 replacements autoloads))
1b92d94c
AW
2621 ((#:duplicates)
2622 (if (not (pair? (cdr kws)))
2623 (unrecognized kws))
2624 (set-module-duplicates-handlers!
2625 module
2626 (lookup-duplicates-handlers (cadr kws)))
2627 (loop (cddr kws) reversed-interfaces exports re-exports
608860a5 2628 replacements autoloads))
1b92d94c
AW
2629 ((#:export #:export-syntax)
2630 (or (pair? (cdr kws))
2631 (unrecognized kws))
2632 (loop (cddr kws)
2633 reversed-interfaces
2634 (append (cadr kws) exports)
2635 re-exports
2636 replacements
608860a5 2637 autoloads))
1b92d94c
AW
2638 ((#:re-export #:re-export-syntax)
2639 (or (pair? (cdr kws))
2640 (unrecognized kws))
2641 (loop (cddr kws)
2642 reversed-interfaces
2643 exports
2644 (append (cadr kws) re-exports)
2645 replacements
608860a5 2646 autoloads))
1b92d94c
AW
2647 ((#:replace #:replace-syntax)
2648 (or (pair? (cdr kws))
2649 (unrecognized kws))
2650 (loop (cddr kws)
2651 reversed-interfaces
2652 exports
2653 re-exports
2654 (append (cadr kws) replacements)
608860a5 2655 autoloads))
78f79f18
AW
2656 ((#:filename)
2657 (or (pair? (cdr kws))
2658 (unrecognized kws))
2659 (set-module-filename! module (cadr kws))
2660 (loop (cddr kws)
2661 reversed-interfaces
2662 exports
2663 re-exports
2664 replacements
2665 autoloads))
1b92d94c
AW
2666 (else
2667 (unrecognized kws)))))
db853761 2668 (run-hook module-defined-hook module)
0f2d19dd 2669 module))
71225060 2670
db853761
NJ
2671;; `module-defined-hook' is a hook that is run whenever a new module
2672;; is defined. Its members are called with one argument, the new
2673;; module.
2674(define module-defined-hook (make-hook 1))
2675
3d2ada2f
DH
2676\f
2677
71225060 2678;;; {Autoload}
3d2ada2f 2679;;;
71225060
MD
2680
2681(define (make-autoload-interface module name bindings)
2682 (let ((b (lambda (a sym definep)
9b5a0d84
AW
2683 (and (memq sym bindings)
2684 (let ((i (module-public-interface (resolve-module name))))
2685 (if (not i)
2686 (error "missing interface for module" name))
2687 (let ((autoload (memq a (module-uses module))))
2688 ;; Replace autoload-interface with actual interface if
2689 ;; that has not happened yet.
2690 (if (pair? autoload)
2691 (set-car! autoload i)))
2692 (module-local-variable i sym))))))
608860a5 2693 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
f905381d 2694 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
78f79f18 2695 (make-hash-table 0) #f #f #f)))
608860a5
LC
2696
2697(define (module-autoload! module . args)
2698 "Have @var{module} automatically load the module named @var{name} when one
2699of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2700list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2701module '(ice-9 q) '(make-q q-length))}."
2702 (let loop ((args args))
2703 (cond ((null? args)
2704 #t)
2705 ((null? (cdr args))
2706 (error "invalid name+binding autoload list" args))
2707 (else
2708 (let ((name (car args))
2709 (bindings (cadr args)))
2710 (module-use! module (make-autoload-interface module
2711 name bindings))
2712 (loop (cddr args)))))))
2713
71225060 2714
0f2d19dd 2715\f
3d2ada2f 2716
44cf1f0f 2717;;; {Autoloading modules}
3d2ada2f 2718;;;
0f2d19dd
JB
2719
2720(define autoloads-in-progress '())
2721
482a28f9
MV
2722;; This function is called from "modules.c". If you change it, be
2723;; sure to update "modules.c" as well.
2724
d9113d47 2725(define* (try-module-autoload module-name #:optional version)
0f2d19dd 2726 (let* ((reverse-name (reverse module-name))
9b5a0d84
AW
2727 (name (symbol->string (car reverse-name)))
2728 (dir-hint-module-name (reverse (cdr reverse-name)))
2729 (dir-hint (apply string-append
2730 (map (lambda (elt)
2731 (string-append (symbol->string elt) "/"))
2732 dir-hint-module-name))))
0209ca9a 2733 (resolve-module dir-hint-module-name #f)
0f2d19dd 2734 (and (not (autoload-done-or-in-progress? dir-hint name))
9b5a0d84
AW
2735 (let ((didit #f))
2736 (dynamic-wind
2737 (lambda () (autoload-in-progress! dir-hint name))
2738 (lambda ()
eddd16d7
AW
2739 (with-fluids ((current-reader #f))
2740 (save-module-excursion
2741 (lambda ()
2742 (if version
2743 (load (find-versioned-module
2744 dir-hint name version %load-path))
2745 (primitive-load-path (in-vicinity dir-hint name) #f))
2746 (set! didit #t)))))
9b5a0d84
AW
2747 (lambda () (set-autoloaded! dir-hint name didit)))
2748 didit))))
0f2d19dd 2749
71225060 2750\f
3d2ada2f
DH
2751
2752;;; {Dynamic linking of modules}
2753;;;
d0cbd20c 2754
0f2d19dd
JB
2755(define autoloads-done '((guile . guile)))
2756
2757(define (autoload-done-or-in-progress? p m)
2758 (let ((n (cons p m)))
2759 (->bool (or (member n autoloads-done)
9b5a0d84 2760 (member n autoloads-in-progress)))))
0f2d19dd
JB
2761
2762(define (autoload-done! p m)
2763 (let ((n (cons p m)))
2764 (set! autoloads-in-progress
9b5a0d84 2765 (delete! n autoloads-in-progress))
0f2d19dd 2766 (or (member n autoloads-done)
9b5a0d84 2767 (set! autoloads-done (cons n autoloads-done)))))
0f2d19dd
JB
2768
2769(define (autoload-in-progress! p m)
2770 (let ((n (cons p m)))
2771 (set! autoloads-done
9b5a0d84 2772 (delete! n autoloads-done))
0f2d19dd
JB
2773 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2774
2775(define (set-autoloaded! p m done?)
2776 (if done?
2777 (autoload-done! p m)
2778 (let ((n (cons p m)))
9b5a0d84
AW
2779 (set! autoloads-done (delete! n autoloads-done))
2780 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
0f2d19dd 2781
0f2d19dd
JB
2782\f
2783
83b38198 2784;;; {Run-time options}
3d2ada2f 2785;;;
83b38198 2786
27af6bc2 2787(defmacro define-option-interface (option-group)
9ea12179 2788 (let* ((option-name 'car)
9b5a0d84
AW
2789 (option-value 'cadr)
2790 (option-documentation 'caddr)
e9bab9df 2791
9b5a0d84 2792 ;; Below follow the macros defining the run-time option interfaces.
e9bab9df 2793
9b5a0d84
AW
2794 (make-options (lambda (interface)
2795 `(lambda args
2796 (cond ((null? args) (,interface))
2797 ((list? (car args))
2798 (,interface (car args)) (,interface))
2799 (else (for-each
27af6bc2 2800 (lambda (option)
9ea12179 2801 (display (,option-name option))
27af6bc2 2802 (if (< (string-length
9ea12179 2803 (symbol->string (,option-name option)))
27af6bc2
AW
2804 8)
2805 (display #\tab))
2806 (display #\tab)
9ea12179 2807 (display (,option-value option))
27af6bc2 2808 (display #\tab)
9ea12179 2809 (display (,option-documentation option))
27af6bc2
AW
2810 (newline))
2811 (,interface #t)))))))
e9bab9df 2812
9b5a0d84
AW
2813 (make-enable (lambda (interface)
2814 `(lambda flags
2815 (,interface (append flags (,interface)))
2816 (,interface))))
2817
2818 (make-disable (lambda (interface)
2819 `(lambda flags
2820 (let ((options (,interface)))
2821 (for-each (lambda (flag)
2822 (set! options (delq! flag options)))
2823 flags)
2824 (,interface options)
2825 (,interface))))))
27af6bc2
AW
2826 (let* ((interface (car option-group))
2827 (options/enable/disable (cadr option-group)))
2828 `(begin
2829 (define ,(car options/enable/disable)
2830 ,(make-options interface))
2831 (define ,(cadr options/enable/disable)
2832 ,(make-enable interface))
2833 (define ,(caddr options/enable/disable)
2834 ,(make-disable interface))
2835 (defmacro ,(caaddr option-group) (opt val)
2836 `(,',(car options/enable/disable)
2837 (append (,',(car options/enable/disable))
2838 (list ',opt ,val))))))))
e9bab9df
DH
2839
2840(define-option-interface
2841 (eval-options-interface
2842 (eval-options eval-enable eval-disable)
2843 (eval-set!)))
2844
2845(define-option-interface
2846 (debug-options-interface
2847 (debug-options debug-enable debug-disable)
2848 (debug-set!)))
2849
2850(define-option-interface
2851 (evaluator-traps-interface
2852 (traps trap-enable trap-disable)
2853 (trap-set!)))
2854
2855(define-option-interface
2856 (read-options-interface
2857 (read-options read-enable read-disable)
2858 (read-set!)))
2859
2860(define-option-interface
2861 (print-options-interface
2862 (print-options print-enable print-disable)
2863 (print-set!)))
83b38198
MD
2864
2865\f
2866
0f2d19dd
JB
2867;;; {Running Repls}
2868;;;
2869
2870(define (repl read evaler print)
75a97b92 2871 (let loop ((source (read (current-input-port))))
0f2d19dd 2872 (print (evaler source))
75a97b92 2873 (loop (read (current-input-port)))))
0f2d19dd
JB
2874
2875;; A provisional repl that acts like the SCM repl:
2876;;
2877(define scm-repl-silent #f)
2878(define (assert-repl-silence v) (set! scm-repl-silent v))
2879
21ed9efe
MD
2880(define *unspecified* (if #f #f))
2881(define (unspecified? v) (eq? v *unspecified*))
2882
2883(define scm-repl-print-unspecified #f)
2884(define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2885
79451588 2886(define scm-repl-verbose #f)
0f2d19dd
JB
2887(define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2888
e6875011 2889(define scm-repl-prompt "guile> ")
0f2d19dd 2890
e6875011
MD
2891(define (set-repl-prompt! v) (set! scm-repl-prompt v))
2892
9f0e9918 2893(define (default-pre-unwind-handler key . args)
06dcb9df
AW
2894 ;; Narrow by two more frames: this one, and the throw handler.
2895 (save-stack 2)
d5d34fa1
MD
2896 (apply throw key args))
2897
1351c2db
AW
2898(begin-deprecated
2899 (define (pre-unwind-handler-dispatch key . args)
2900 (apply default-pre-unwind-handler key args)))
0f2d19dd 2901
3e3cec45 2902(define abort-hook (make-hook))
59e1116d 2903
28d8ab3c
GH
2904;; these definitions are used if running a script.
2905;; otherwise redefined in error-catching-loop.
2906(define (set-batch-mode?! arg) #t)
2907(define (batch-mode?) #t)
4bbbcd5c 2908
8bb7f646 2909;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
8087b6be 2910(define before-signal-stack (make-fluid))
06dcb9df 2911;; FIXME: stack-saved? is broken in the presence of threads.
21ed9efe
MD
2912(define stack-saved? #f)
2913
2914(define (save-stack . narrowing)
06dcb9df
AW
2915 (if (not stack-saved?)
2916 (begin
2917 (let ((stacks (fluid-ref %stacks)))
2918 (fluid-set! the-last-stack
2919 ;; (make-stack obj inner outer inner outer ...)
2920 ;;
2921 ;; In this case, cut away the make-stack frame, the
2922 ;; save-stack frame, and then narrow as specified by the
2923 ;; user, delimited by the nearest start-stack invocation,
2924 ;; if any.
2925 (apply make-stack #t
2926 2
2927 (if (pair? stacks) (cdar stacks) 0)
2928 narrowing)))
2929 (set! stack-saved? #t))))
1c6cd8e8 2930
3e3cec45
MD
2931(define before-error-hook (make-hook))
2932(define after-error-hook (make-hook))
2933(define before-backtrace-hook (make-hook))
2934(define after-backtrace-hook (make-hook))
1c6cd8e8 2935
21ed9efe
MD
2936(define has-shown-debugger-hint? #f)
2937
35c5db87
GH
2938(define (handle-system-error key . args)
2939 (let ((cep (current-error-port)))
8bb7f646 2940 (cond ((not (stack? (fluid-ref the-last-stack))))
9b5a0d84
AW
2941 ((memq 'backtrace (debug-options-interface))
2942 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2943 (eq? key 'out-of-range))
2944 (list-ref args 3)
2945 '())))
2946 (run-hook before-backtrace-hook)
2947 (newline cep)
2948 (display "Backtrace:\n")
2949 (display-backtrace (fluid-ref the-last-stack) cep
2950 #f #f highlights)
2951 (newline cep)
2952 (run-hook after-backtrace-hook))))
04efd24d 2953 (run-hook before-error-hook)
8bb7f646 2954 (apply display-error (fluid-ref the-last-stack) cep args)
04efd24d 2955 (run-hook after-error-hook)
35c5db87
GH
2956 (force-output cep)
2957 (throw 'abort key)))
21ed9efe 2958
0f2d19dd
JB
2959(define (quit . args)
2960 (apply throw 'quit args))
2961
7950df7c
GH
2962(define exit quit)
2963
0f2d19dd
JB
2964(define (gc-run-time)
2965 (cdr (assq 'gc-time-taken (gc-stats))))
2966
3e3cec45
MD
2967(define before-read-hook (make-hook))
2968(define after-read-hook (make-hook))
870777d7
KN
2969(define before-eval-hook (make-hook 1))
2970(define after-eval-hook (make-hook 1))
2971(define before-print-hook (make-hook 1))
2972(define after-print-hook (make-hook 1))
1c6cd8e8 2973
dc5c2038
MD
2974;;; The default repl-reader function. We may override this if we've
2975;;; the readline library.
2976(define repl-reader
17ee350c 2977 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
0becb8f3
AW
2978 (if (not (char-ready?))
2979 (display (if (string? prompt) prompt (prompt))))
dc5c2038 2980 (force-output)
04efd24d 2981 (run-hook before-read-hook)
17ee350c 2982 ((or reader read) (current-input-port))))
dc5c2038 2983
0f2d19dd 2984
0f2d19dd 2985\f
3d2ada2f 2986
44cf1f0f 2987;;; {IOTA functions: generating lists of numbers}
3d2ada2f 2988;;;
0f2d19dd 2989
e69cd299
MD
2990(define (iota n)
2991 (let loop ((count (1- n)) (result '()))
2992 (if (< count 0) result
2993 (loop (1- count) (cons count result)))))
0f2d19dd
JB
2994
2995\f
3d2ada2f 2996
7398c2c2
MD
2997;;; {collect}
2998;;;
2999;;; Similar to `begin' but returns a list of the results of all constituent
3000;;; forms instead of the result of the last form.
3001;;; (The definition relies on the current left-to-right
3002;;; order of evaluation of operands in applications.)
3d2ada2f 3003;;;
7398c2c2
MD
3004
3005(defmacro collect forms
3006 (cons 'list forms))
0f2d19dd 3007
3d2ada2f
DH
3008\f
3009
773abfbb
KR
3010;;; {While}
3011;;;
3012;;; with `continue' and `break'.
3013;;;
3014
3015;; The inner `do' loop avoids re-establishing a catch every iteration,
5578a53f
KR
3016;; that's only necessary if continue is actually used. A new key is
3017;; generated every time, so break and continue apply to their originating
972c33e5 3018;; `while' even when recursing.
c8fc38b1 3019;;
972c33e5
AW
3020;; FIXME: This macro is unintentionally unhygienic with respect to let,
3021;; make-symbol, do, throw, catch, lambda, and not.
c8fc38b1 3022;;
773abfbb 3023(define-macro (while cond . body)
972c33e5
AW
3024 (let ((keyvar (make-symbol "while-keyvar")))
3025 `(let ((,keyvar (make-symbol "while-key")))
3026 (do ()
3027 ((catch ,keyvar
3028 (lambda ()
3029 (let ((break (lambda () (throw ,keyvar #t)))
3030 (continue (lambda () (throw ,keyvar #f))))
3031 (do ()
3032 ((not ,cond))
3033 ,@body)
3034 #t))
3035 (lambda (key arg)
3036 arg)))))))
5578a53f 3037
773abfbb 3038
0f2d19dd 3039\f
3d2ada2f 3040
0f2d19dd
JB
3041;;; {Module System Macros}
3042;;;
3043
532cf805
MV
3044;; Return a list of expressions that evaluate to the appropriate
3045;; arguments for resolve-interface according to SPEC.
3046
b15dea68 3047(eval-when
25d8cd3a
AW
3048 (compile)
3049 (if (memq 'prefix (read-options))
3050 (error "boot-9 must be compiled with #:kw, not :kw")))
1a1a10d3 3051
532cf805
MV
3052(define (keyword-like-symbol->keyword sym)
3053 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3054
074e036e
AW
3055;; FIXME: we really need to clean up the guts of the module system.
3056;; We can compile to something better than process-define-module.
3057(define-syntax define-module
3058 (lambda (x)
3059 (define (keyword-like? stx)
3060 (let ((dat (syntax->datum stx)))
3061 (and (symbol? dat)
3062 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3063 (define (->keyword sym)
3064 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3065
3066 (define (quotify-iface args)
3067 (let loop ((in args) (out '()))
3068 (syntax-case in ()
3069 (() (reverse! out))
3070 ;; The user wanted #:foo, but wrote :foo. Fix it.
3071 ((sym . in) (keyword-like? #'sym)
3072 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3073 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3074 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3075 ((#:renamer renamer . in)
3076 (loop #'in (cons* #'renamer #:renamer out)))
3077 ((kw val . in)
3078 (loop #'in (cons* #''val #'kw out))))))
3079
3080 (define (quotify args)
3081 ;; Just quote everything except #:use-module and #:use-syntax. We
3082 ;; need to know about all arguments regardless since we want to turn
3083 ;; symbols that look like keywords into real keywords, and the
3084 ;; keyword args in a define-module form are not regular
3085 ;; (i.e. no-backtrace doesn't take a value).
3086 (let loop ((in args) (out '()))
3087 (syntax-case in ()
3088 (() (reverse! out))
3089 ;; The user wanted #:foo, but wrote :foo. Fix it.
3090 ((sym . in) (keyword-like? #'sym)
3091 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3092 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3093 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3094 ((#:no-backtrace . in)
3095 (loop #'in (cons #:no-backtrace out)))
3096 ((#:pure . in)
3097 (loop #'in (cons #:pure out)))
3098 ((kw)
3099 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3100 ((use-module (name name* ...) . in)
3101 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3102 (and-map symbol? (syntax->datum #'(name name* ...))))
3103 (loop #'in
3104 (cons* #''((name name* ...))
3105 #'use-module
3106 out)))
3107 ((use-module ((name name* ...) arg ...) . in)
3108 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3109 (and-map symbol? (syntax->datum #'(name name* ...))))
3110 (loop #'in
3111 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
3112 #'use-module
3113 out)))
3114 ((#:autoload name bindings . in)
3115 (loop #'in (cons* #''bindings #''name #:autoload out)))
3116 ((kw val . in)
3117 (loop #'in (cons* #''val #'kw out))))))
3118
3119 (syntax-case x ()
3120 ((_ (name name* ...) arg ...)
3121 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
d9b1c71a 3122 #'(eval-when (eval load compile expand)
074e036e 3123 (let ((m (process-define-module
78f79f18
AW
3124 (list '(name name* ...)
3125 #:filename (assq-ref
3126 (or (current-source-location) '())
3127 'filename)
3128 quoted-arg ...))))
074e036e
AW
3129 (set-current-module m)
3130 m)))))))
0f2d19dd 3131
532cf805
MV
3132;; The guts of the use-modules macro. Add the interfaces of the named
3133;; modules to the use-list of the current module, in order.
3134
482a28f9
MV
3135;; This function is called by "modules.c". If you change it, be sure
3136;; to change scm_c_use_module as well.
3137
532cf805 3138(define (process-use-modules module-interface-args)
d57da08b 3139 (let ((interfaces (map (lambda (mif-args)
9b5a0d84
AW
3140 (or (apply resolve-interface mif-args)
3141 (error "no such module" mif-args)))
3142 module-interface-args)))
d57da08b
MD
3143 (call-with-deferred-observers
3144 (lambda ()
3145 (module-use-interfaces! (current-module) interfaces)))))
89da9036 3146
4e3328ce
AW
3147(define-syntax use-modules
3148 (lambda (x)
3149 (define (keyword-like? stx)
3150 (let ((dat (syntax->datum stx)))
3151 (and (symbol? dat)
3152 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3153 (define (->keyword sym)
3154 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3155
3156 (define (quotify-iface args)
3157 (let loop ((in args) (out '()))
3158 (syntax-case in ()
3159 (() (reverse! out))
3160 ;; The user wanted #:foo, but wrote :foo. Fix it.
3161 ((sym . in) (keyword-like? #'sym)
3162 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3163 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3164 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3165 ((#:renamer renamer . in)
3166 (loop #'in (cons* #'renamer #:renamer out)))
3167 ((kw val . in)
3168 (loop #'in (cons* #''val #'kw out))))))
3169
3170 (define (quotify specs)
3171 (let lp ((in specs) (out '()))
3172 (syntax-case in ()
3173 (() (reverse out))
3174 (((name name* ...) . in)
3175 (and-map symbol? (syntax->datum #'(name name* ...)))
3176 (lp #'in (cons #''((name name* ...)) out)))
3177 ((((name name* ...) arg ...) . in)
3178 (and-map symbol? (syntax->datum #'(name name* ...)))
3179 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3180 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3181 out)))))))
3182
3183 (syntax-case x ()
3184 ((_ spec ...)
3185 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
520caaeb 3186 #'(eval-when (eval load compile expand)
4e3328ce
AW
3187 (process-use-modules (list quoted-args ...))
3188 *unspecified*))))))
3189
3190(define-syntax use-syntax
3191 (syntax-rules ()
3192 ((_ spec ...)
3193 (begin
520caaeb 3194 (eval-when (eval load compile expand)
4e3328ce
AW
3195 (issue-deprecation-warning
3196 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3197 (use-modules spec ...)))))
0f2d19dd 3198
b1e4c7cc
JG
3199(include-from-path "ice-9/r6rs-libraries")
3200
13182603
AW
3201(define-syntax define-private
3202 (syntax-rules ()
3203 ((_ foo bar)
3204 (define foo bar))))
3205
3206(define-syntax define-public
3207 (syntax-rules ()
3208 ((_ (name . args) . body)
3209 (define-public name (lambda args . body)))
3210 ((_ name val)
3211 (begin
3212 (define name val)
3213 (export name)))))
3214
3215(define-syntax defmacro-public
3216 (syntax-rules ()
3217 ((_ name args . body)
3218 (begin
3219 (defmacro name args . body)
3220 (export-syntax name)))))
0f2d19dd 3221
87e00370
LC
3222;; And now for the most important macro.
3223(define-syntax λ
3224 (syntax-rules ()
3225 ((_ formals body ...)
3226 (lambda formals body ...))))
3227
3228\f
89d06712 3229;; Export a local variable
482a28f9
MV
3230
3231;; This function is called from "modules.c". If you change it, be
3232;; sure to update "modules.c" as well.
3233
90847923
MD
3234(define (module-export! m names)
3235 (let ((public-i (module-public-interface m)))
3236 (for-each (lambda (name)
78c22f5e
JG
3237 (let* ((internal-name (if (pair? name) (car name) name))
3238 (external-name (if (pair? name) (cdr name) name))
3239 (var (module-ensure-local-variable! m internal-name)))
3240 (module-add! public-i external-name var)))
9b5a0d84 3241 names)))
89d06712 3242
f595ccfe
MD
3243(define (module-replace! m names)
3244 (let ((public-i (module-public-interface m)))
3245 (for-each (lambda (name)
78c22f5e
JG
3246 (let* ((internal-name (if (pair? name) (car name) name))
3247 (external-name (if (pair? name) (cdr name) name))
3248 (var (module-ensure-local-variable! m internal-name)))
9b5a0d84 3249 (set-object-property! var 'replace #t)
78c22f5e 3250 (module-add! public-i external-name var)))
9b5a0d84 3251 names)))
f595ccfe 3252
d2b7b761
AW
3253;; Export all local variables from a module
3254;;
3255(define (module-export-all! mod)
3256 (define (fresh-interface!)
3257 (let ((iface (make-module)))
3258 (set-module-name! iface (module-name mod))
3259 ;; for guile 2: (set-module-version! iface (module-version mod))
3260 (set-module-kind! iface 'interface)
3261 (set-module-public-interface! mod iface)
3262 iface))
3263 (let ((iface (or (module-public-interface mod)
3264 (fresh-interface!))))
3265 (set-module-obarray! iface (module-obarray mod))))
3266
89d06712
MV
3267;; Re-export a imported variable
3268;;
3269(define (module-re-export! m names)
3270 (let ((public-i (module-public-interface m)))
3271 (for-each (lambda (name)
78c22f5e
JG
3272 (let* ((internal-name (if (pair? name) (car name) name))
3273 (external-name (if (pair? name) (cdr name) name))
3274 (var (module-variable m internal-name)))
9b5a0d84 3275 (cond ((not var)
78c22f5e
JG
3276 (error "Undefined variable:" internal-name))
3277 ((eq? var (module-local-variable m internal-name))
3278 (error "re-exporting local variable:" internal-name))
9b5a0d84 3279 (else
78c22f5e 3280 (module-add! public-i external-name var)))))
9b5a0d84 3281 names)))
90847923 3282
d6151723
AW
3283(define-syntax export
3284 (syntax-rules ()
3285 ((_ name ...)
520caaeb 3286 (eval-when (eval load compile expand)
d6151723
AW
3287 (call-with-deferred-observers
3288 (lambda ()
3289 (module-export! (current-module) '(name ...))))))))
a0cc0a01 3290
d6151723
AW
3291(define-syntax re-export
3292 (syntax-rules ()
3293 ((_ name ...)
520caaeb 3294 (eval-when (eval load compile expand)
d6151723
AW
3295 (call-with-deferred-observers
3296 (lambda ()
3297 (module-re-export! (current-module) '(name ...))))))))
89d06712 3298
d6151723
AW
3299(define-syntax export-syntax
3300 (syntax-rules ()
3301 ((_ name ...)
3302 (export name ...))))
a0cc0a01 3303
d6151723
AW
3304(define-syntax re-export-syntax
3305 (syntax-rules ()
3306 ((_ name ...)
3307 (re-export name ...))))
a0cc0a01 3308
0f2d19dd
JB
3309(define load load-module)
3310
3de80ed5
AW
3311\f
3312
f595ccfe
MD
3313;;; {Parameters}
3314;;;
3315
3316(define make-mutable-parameter
3317 (let ((make (lambda (fluid converter)
9b5a0d84
AW
3318 (lambda args
3319 (if (null? args)
3320 (fluid-ref fluid)
3321 (fluid-set! fluid (converter (car args))))))))
7df2621d
AW
3322 (lambda* (init #:optional (converter identity))
3323 (let ((fluid (make-fluid)))
9b5a0d84
AW
3324 (fluid-set! fluid (converter init))
3325 (make fluid converter)))))
f595ccfe
MD
3326
3327\f
3d2ada2f 3328
7b07e5ef
MD
3329;;; {Handling of duplicate imported bindings}
3330;;;
3331
3332;; Duplicate handlers take the following arguments:
3333;;
3334;; module importing module
9b5a0d84
AW
3335;; name conflicting name
3336;; int1 old interface where name occurs
3337;; val1 value of binding in old interface
3338;; int2 new interface where name occurs
3339;; val2 value of binding in new interface
3340;; var previous resolution or #f
3341;; val value of previous resolution
7b07e5ef
MD
3342;;
3343;; A duplicate handler can take three alternative actions:
3344;;
3345;; 1. return #f => leave responsibility to next handler
3346;; 2. exit with an error
3347;; 3. return a variable resolving the conflict
3348;;
3349
3350(define duplicate-handlers
3351 (let ((m (make-module 7)))
f595ccfe
MD
3352
3353 (define (check module name int1 val1 int2 val2 var val)
3354 (scm-error 'misc-error
9b5a0d84
AW
3355 #f
3356 "~A: `~A' imported from both ~A and ~A"
3357 (list (module-name module)
3358 name
3359 (module-name int1)
3360 (module-name int2))
3361 #f))
f595ccfe 3362
65bed4aa 3363 (define (warn module name int1 val1 int2 val2 var val)
d7c0c26d 3364 (format (current-error-port)
9b5a0d84
AW
3365 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3366 (module-name module)
3367 name
3368 (module-name int1)
3369 (module-name int2))
65bed4aa 3370 #f)
f595ccfe
MD
3371
3372 (define (replace module name int1 val1 int2 val2 var val)
3373 (let ((old (or (and var (object-property var 'replace) var)
9b5a0d84
AW
3374 (module-variable int1 name)))
3375 (new (module-variable int2 name)))
3376 (if (object-property old 'replace)
3377 (and (or (eq? old new)
3378 (not (object-property new 'replace)))
3379 old)
3380 (and (object-property new 'replace)
3381 new))))
f595ccfe 3382
65bed4aa
MD
3383 (define (warn-override-core module name int1 val1 int2 val2 var val)
3384 (and (eq? int1 the-scm-module)
9b5a0d84
AW
3385 (begin
3386 (format (current-error-port)
3387 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3388 (module-name module)
3389 (module-name int2)
3390 name)
3391 (module-local-variable int2 name))))
f595ccfe 3392
65bed4aa
MD
3393 (define (first module name int1 val1 int2 val2 var val)
3394 (or var (module-local-variable int1 name)))
f595ccfe 3395
65bed4aa
MD
3396 (define (last module name int1 val1 int2 val2 var val)
3397 (module-local-variable int2 name))
f595ccfe 3398
65bed4aa
MD
3399 (define (noop module name int1 val1 int2 val2 var val)
3400 #f)
3401
7b07e5ef
MD
3402 (set-module-name! m 'duplicate-handlers)
3403 (set-module-kind! m 'interface)
f595ccfe
MD
3404 (module-define! m 'check check)
3405 (module-define! m 'warn warn)
3406 (module-define! m 'replace replace)
3407 (module-define! m 'warn-override-core warn-override-core)
3408 (module-define! m 'first first)
3409 (module-define! m 'last last)
65bed4aa
MD
3410 (module-define! m 'merge-generics noop)
3411 (module-define! m 'merge-accessors noop)
7b07e5ef
MD
3412 m))
3413
f595ccfe 3414(define (lookup-duplicates-handlers handler-names)
109c2c9f
MD
3415 (and handler-names
3416 (map (lambda (handler-name)
9b5a0d84
AW
3417 (or (module-symbol-local-binding
3418 duplicate-handlers handler-name #f)
3419 (error "invalid duplicate handler name:"
3420 handler-name)))
3421 (if (list? handler-names)
3422 handler-names
3423 (list handler-names)))))
f595ccfe 3424
70a459e3
MD
3425(define default-duplicate-binding-procedures
3426 (make-mutable-parameter #f))
3427
3428(define default-duplicate-binding-handler
6496a663 3429 (make-mutable-parameter '(replace warn-override-core warn last)
9b5a0d84
AW
3430 (lambda (handler-names)
3431 (default-duplicate-binding-procedures
3432 (lookup-duplicates-handlers handler-names))
3433 handler-names)))
f595ccfe 3434
7b07e5ef 3435\f
7f24bc58
MG
3436
3437;;; {`cond-expand' for SRFI-0 support.}
3438;;;
3439;;; This syntactic form expands into different commands or
3440;;; definitions, depending on the features provided by the Scheme
3441;;; implementation.
3442;;;
3443;;; Syntax:
3444;;;
3445;;; <cond-expand>
3446;;; --> (cond-expand <cond-expand-clause>+)
3447;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3448;;; <cond-expand-clause>
3449;;; --> (<feature-requirement> <command-or-definition>*)
3450;;; <feature-requirement>
3451;;; --> <feature-identifier>
3452;;; | (and <feature-requirement>*)
3453;;; | (or <feature-requirement>*)
3454;;; | (not <feature-requirement>)
3455;;; <feature-identifier>
3456;;; --> <a symbol which is the name or alias of a SRFI>
3457;;;
3458;;; Additionally, this implementation provides the
3459;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3460;;; determine the implementation type and the supported standard.
3461;;;
3462;;; Currently, the following feature identifiers are supported:
3463;;;
08b609aa 3464;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
7f24bc58
MG
3465;;;
3466;;; Remember to update the features list when adding more SRFIs.
3d2ada2f 3467;;;
7f24bc58 3468
b9b8f9da 3469(define %cond-expand-features
f41be016 3470 ;; Adjust the above comment when changing this.
018733ff 3471 '(guile
60c8ad9e 3472 guile-2
018733ff
KR
3473 r5rs
3474 srfi-0 ;; cond-expand itself
85acb35f 3475 srfi-4 ;; homogenous numeric vectors
018733ff 3476 srfi-6 ;; open-input-string etc, in the guile core
4a276c08
MV
3477 srfi-13 ;; string library
3478 srfi-14 ;; character sets
344d68d5 3479 srfi-55 ;; require-extension
08b609aa 3480 srfi-61 ;; general cond clause
018733ff 3481 ))
1d00af09 3482
b9b8f9da
MG
3483;; This table maps module public interfaces to the list of features.
3484;;
3485(define %cond-expand-table (make-hash-table 31))
3486
3487;; Add one or more features to the `cond-expand' feature list of the
3488;; module `module'.
3489;;
3490(define (cond-expand-provide module features)
3491 (let ((mod (module-public-interface module)))
3492 (and mod
9b5a0d84
AW
3493 (hashq-set! %cond-expand-table mod
3494 (append (hashq-ref %cond-expand-table mod '())
3495 features)))))
b9b8f9da 3496
f4bf64b4
LC
3497(define-macro (cond-expand . clauses)
3498 (let ((syntax-error (lambda (cl)
3499 (error "invalid clause in `cond-expand'" cl))))
3500 (letrec
3501 ((test-clause
3502 (lambda (clause)
3503 (cond
3504 ((symbol? clause)
3505 (or (memq clause %cond-expand-features)
3506 (let lp ((uses (module-uses (current-module))))
3507 (if (pair? uses)
3508 (or (memq clause
3509 (hashq-ref %cond-expand-table
3510 (car uses) '()))
3511 (lp (cdr uses)))
3512 #f))))
3513 ((pair? clause)
3514 (cond
3515 ((eq? 'and (car clause))
3516 (let lp ((l (cdr clause)))
3517 (cond ((null? l)
3518 #t)
3519 ((pair? l)
3520 (and (test-clause (car l)) (lp (cdr l))))
3521 (else
3522 (syntax-error clause)))))
3523 ((eq? 'or (car clause))
3524 (let lp ((l (cdr clause)))
3525 (cond ((null? l)
3526 #f)
3527 ((pair? l)
3528 (or (test-clause (car l)) (lp (cdr l))))
3529 (else
3530 (syntax-error clause)))))
3531 ((eq? 'not (car clause))
3532 (cond ((not (pair? (cdr clause)))
3533 (syntax-error clause))
3534 ((pair? (cddr clause))
3535 ((syntax-error clause))))
3536 (not (test-clause (cadr clause))))
3537 (else
3538 (syntax-error clause))))
3539 (else
3540 (syntax-error clause))))))
3541 (let lp ((c clauses))
3542 (cond
3543 ((null? c)
3544 (error "Unfulfilled `cond-expand'"))
3545 ((not (pair? c))
3546 (syntax-error c))
3547 ((not (pair? (car c)))
3548 (syntax-error (car c)))
3549 ((test-clause (caar c))
3550 `(begin ,@(cdar c)))
3551 ((eq? (caar c) 'else)
3552 (if (pair? (cdr c))
3553 (syntax-error c))
3554 `(begin ,@(cdar c)))
3555 (else
3556 (lp (cdr c))))))))
0f2d19dd 3557
f41be016
MG
3558;; This procedure gets called from the startup code with a list of
3559;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3560;;
3561(define (use-srfis srfis)
9a18d8d4
KR
3562 (process-use-modules
3563 (map (lambda (num)
9b5a0d84
AW
3564 (list (list 'srfi (string->symbol
3565 (string-append "srfi-" (number->string num))))))
3566 srfis)))
f8a502cb 3567
0f2d19dd 3568\f
9d774814 3569
344d68d5
RB
3570;;; srfi-55: require-extension
3571;;;
3572
3573(define-macro (require-extension extension-spec)
3574 ;; This macro only handles the srfi extension, which, at present, is
3575 ;; the only one defined by the standard.
3576 (if (not (pair? extension-spec))
3577 (scm-error 'wrong-type-arg "require-extension"
3578 "Not an extension: ~S" (list extension-spec) #f))
3579 (let ((extension (car extension-spec))
3580 (extension-args (cdr extension-spec)))
3581 (case extension
3582 ((srfi)
3583 (let ((use-list '()))
3584 (for-each
3585 (lambda (i)
3586 (if (not (integer? i))
3587 (scm-error 'wrong-type-arg "require-extension"
3588 "Invalid srfi name: ~S" (list i) #f))
3589 (let ((srfi-sym (string->symbol
3590 (string-append "srfi-" (number->string i)))))
3591 (if (not (memq srfi-sym %cond-expand-features))
3592 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3593 use-list)))))
3594 extension-args)
3595 (if (pair? use-list)
3596 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3597 `(begin ,@(reverse! use-list)))))
3598 (else
3599 (scm-error
3600 'wrong-type-arg "require-extension"
3601 "Not a recognized extension type: ~S" (list extension) #f)))))
3602
3603\f
3604
9aca88c3 3605;;; {Load emacs interface support if emacs option is given.}
3d2ada2f 3606;;;
9aca88c3 3607
645e38d9 3608(define (named-module-use! user usee)
89d06712 3609 (module-use! (resolve-module user) (resolve-interface usee)))
645e38d9 3610
9aca88c3 3611(define (load-emacs-interface)
fb1b76f4
TTN
3612 (and (provided? 'debug-extensions)
3613 (debug-enable 'backtrace))
645e38d9 3614 (named-module-use! '(guile-user) '(ice-9 emacs)))
9aca88c3
JB
3615
3616\f
0f2d19dd 3617
755457ec
MD
3618(define using-readline?
3619 (let ((using-readline? (make-fluid)))
3620 (make-procedure-with-setter
3621 (lambda () (fluid-ref using-readline?))
3622 (lambda (v) (fluid-set! using-readline? v)))))
3623
20edfbbd 3624(define (top-repl)
615bfe72
MV
3625 (let ((guile-user-module (resolve-module '(guile-user))))
3626
3627 ;; Load emacs interface support if emacs option is given.
454b82f4 3628 (if (and (module-defined? guile-user-module 'use-emacs-interface)
9b5a0d84
AW
3629 (module-ref guile-user-module 'use-emacs-interface))
3630 (load-emacs-interface))
615bfe72
MV
3631
3632 ;; Use some convenient modules (in reverse order)
bbf5a913 3633
9a18d8d4
KR
3634 (set-current-module guile-user-module)
3635 (process-use-modules
3636 (append
3637 '(((ice-9 r5rs))
9b5a0d84
AW
3638 ((ice-9 session))
3639 ((ice-9 debug)))
9a18d8d4 3640 (if (provided? 'regex)
9b5a0d84
AW
3641 '(((ice-9 regex)))
3642 '())
9a18d8d4 3643 (if (provided? 'threads)
9b5a0d84
AW
3644 '(((ice-9 threads)))
3645 '())))
615bfe72 3646 ;; load debugger on demand
42ee0d00 3647 (module-autoload! guile-user-module '(system vm debug) '(debug))
615bfe72 3648
9a18d8d4
KR
3649 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3650 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3651 ;; no effect.
615bfe72 3652 (let ((old-handlers #f)
3ece779a 3653 (start-repl (@ (system repl repl) start-repl))
9b5a0d84
AW
3654 (signals (if (provided? 'posix)
3655 `((,SIGINT . "User interrupt")
3656 (,SIGFPE . "Arithmetic error")
3657 (,SIGSEGV
3658 . "Bad memory access (Segmentation violation)"))
3659 '())))
9a18d8d4
KR
3660 ;; no SIGBUS on mingw
3661 (if (defined? 'SIGBUS)
9b5a0d84
AW
3662 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3663 signals)))
615bfe72
MV
3664
3665 (dynamic-wind
3666
9b5a0d84
AW
3667 ;; call at entry
3668 (lambda ()
3669 (let ((make-handler (lambda (msg)
3670 (lambda (sig)
3671 ;; Make a backup copy of the stack
3672 (fluid-set! before-signal-stack
3673 (fluid-ref the-last-stack))
3674 (save-stack 2)
3675 (scm-error 'signal
3676 #f
3677 msg
3678 #f
3679 (list sig))))))
3680 (set! old-handlers
3681 (map (lambda (sig-msg)
3682 (sigaction (car sig-msg)
3683 (make-handler (cdr sig-msg))))
3684 signals))))
3685
3686 ;; the protected thunk.
3687 (lambda ()
6a01fabf 3688 (let ((status (start-repl 'scheme)))
9b5a0d84
AW
3689 (run-hook exit-hook)
3690 status))
3691
3692 ;; call at exit.
3693 (lambda ()
3694 (map (lambda (sig-msg old-handler)
3695 (if (not (car old-handler))
3696 ;; restore original C handler.
3697 (sigaction (car sig-msg) #f)
3698 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3699 (sigaction (car sig-msg)
3700 (car old-handler)
3701 (cdr old-handler))))
3702 signals old-handlers))))))
0f2d19dd 3703
2055a1bc
MD
3704;;; This hook is run at the very end of an interactive session.
3705;;;
3e3cec45 3706(define exit-hook (make-hook))
2055a1bc 3707
4d31f0da 3708\f
3d2ada2f
DH
3709
3710;;; {Deprecated stuff}
3711;;;
3712
3d2ada2f 3713(begin-deprecated
0ea72faa 3714 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3d2ada2f
DH
3715
3716\f
3717
3718;;; Place the user in the guile-user module.
3719;;;
6eb396fe 3720
a2689737
AW
3721;; FIXME:
3722(module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3723
68623e8e
AW
3724(define-module (guile-user)
3725 #:autoload (system base compile) (compile))
6d36532c 3726
7385dc12
LC
3727;; Remain in the `(guile)' module at compilation-time so that the
3728;; `-Wunused-toplevel' warning works as expected.
3729(eval-when (compile) (set-current-module the-root-module))
3730
20edfbbd 3731;;; boot-9.scm ends here