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