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