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