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