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