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