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