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