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