1 ;;; -*- mode: scheme; coding: utf-8; -*-
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.
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.
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.
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
26 ;;; This file is the first thing loaded into Guile. It adds many mundane
27 ;;; definitions and a few that are interesting.
29 ;;; The module system (hence the hierarchical namespace) are defined in this
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.
42 (set-current-module (resolve-module '(guile))))
49 ;; Define delimited continuation operators, and implement catch and throw in
52 (define make-prompt-tag
53 (lambda* (#:optional (stem "prompt"))
54 ;; The only property that prompt tags need have is uniqueness in the
55 ;; sense of eq?. A one-element list will serve nicely.
58 (define default-prompt-tag
59 ;; Redefined later to be a parameter.
60 (let ((%default-prompt-tag (make-prompt-tag)))
62 %default-prompt-tag)))
64 (define (call-with-prompt tag thunk handler)
65 (@prompt tag (thunk) handler))
66 (define (abort-to-prompt tag . args)
70 ;; Define catch and with-throw-handler, using some common helper routines and a
71 ;; shared fluid. Hide the helpers in a lexical contour.
73 (define with-throw-handler #f)
75 (define (default-exception-handler k . args)
79 ((not (pair? args)) 0)
80 ((integer? (car args)) (car args))
84 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
87 (define %running-exception-handlers (make-fluid '()))
88 (define %exception-handler (make-fluid default-exception-handler))
90 (define (default-throw-handler prompt-tag catch-k)
91 (let ((prev (fluid-ref %exception-handler)))
92 (lambda (thrown-k . args)
93 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
94 (apply abort-to-prompt prompt-tag thrown-k args)
95 (apply prev thrown-k args)))))
97 (define (custom-throw-handler prompt-tag catch-k pre)
98 (let ((prev (fluid-ref %exception-handler)))
99 (lambda (thrown-k . args)
100 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
101 (let ((running (fluid-ref %running-exception-handlers)))
102 (with-fluids ((%running-exception-handlers (cons pre running)))
103 (if (not (memq pre running))
104 (apply pre thrown-k args))
107 (apply abort-to-prompt prompt-tag thrown-k args)
108 (apply prev thrown-k args))))
109 (apply prev thrown-k args)))))
112 (lambda* (k thunk handler #:optional pre-unwind-handler)
113 "Invoke @var{thunk} in the dynamic context of @var{handler} for
114 exceptions matching @var{key}. If thunk throws to the symbol
115 @var{key}, then @var{handler} is invoked this way:
117 (handler key args ...)
120 @var{key} is a symbol or @code{#t}.
122 @var{thunk} takes no arguments. If @var{thunk} returns
123 normally, that is the return value of @code{catch}.
125 Handler is invoked outside the scope of its own @code{catch}.
126 If @var{handler} again throws to the same key, a new handler
127 from further up the call chain is invoked.
129 If the key is @code{#t}, then a throw to @emph{any} symbol will
130 match this call to @code{catch}.
132 If a @var{pre-unwind-handler} is given and @var{thunk} throws
133 an exception that matches @var{key}, Guile calls the
134 @var{pre-unwind-handler} before unwinding the dynamic state and
135 invoking the main @var{handler}. @var{pre-unwind-handler} should
136 be a procedure with the same signature as @var{handler}, that
137 is @code{(lambda (key . args))}. It is typically used to save
138 the stack at the point where the exception occurred, but can also
139 query other parts of the dynamic state at that point, such as
142 A @var{pre-unwind-handler} can exit either normally or non-locally.
143 If it exits normally, Guile unwinds the stack and dynamic context
144 and then calls the normal (third argument) handler. If it exits
145 non-locally, that exit determines the continuation."
146 (if (not (or (symbol? k) (eqv? k #t)))
147 (scm-error 'wrong-type-arg "catch"
148 "Wrong type argument in position ~a: ~a"
149 (list 1 k) (list k)))
150 (let ((tag (make-prompt-tag "catch")))
156 (if pre-unwind-handler
157 (custom-throw-handler tag k pre-unwind-handler)
158 (default-throw-handler tag k))))
160 (lambda (cont k . args)
161 (apply handler k args))))))
163 (set! with-throw-handler
164 (lambda (k thunk pre-unwind-handler)
165 "Add @var{handler} to the dynamic context as a throw handler
166 for key @var{k}, then invoke @var{thunk}."
167 (if (not (or (symbol? k) (eqv? k #t)))
168 (scm-error 'wrong-type-arg "with-throw-handler"
169 "Wrong type argument in position ~a: ~a"
170 (list 1 k) (list k)))
171 (with-fluids ((%exception-handler
172 (custom-throw-handler #f k pre-unwind-handler)))
177 "Invoke the catch form matching @var{key}, passing @var{args} to the
180 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
182 If there is no handler at all, Guile prints an error and then exits."
183 (if (not (symbol? key))
184 ((fluid-ref %exception-handler) 'wrong-type-arg "throw"
185 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
186 (apply (fluid-ref %exception-handler) key args)))))
191 ;;; {Language primitives}
194 ;; These are are the procedural wrappers around the primitives of
195 ;; Guile's language: @apply, @call-with-current-continuation, etc.
197 ;; Usually, a call to a primitive is compiled specially. The compiler
198 ;; knows about all these kinds of expressions. But the primitives may
199 ;; be referenced not only as operators, but as values as well. These
200 ;; stub procedures are the "values" of apply, dynamic-wind, and other
203 (define (apply fun . args)
204 (@apply fun (apply:nconc2last args)))
205 (define (call-with-current-continuation proc)
206 (@call-with-current-continuation proc))
207 (define (call-with-values producer consumer)
208 (@call-with-values producer consumer))
209 (define (dynamic-wind in thunk out)
210 "All three arguments must be 0-argument procedures.
211 Guard @var{in} is called, then @var{thunk}, then
214 If, any time during the execution of @var{thunk}, the
215 continuation of the @code{dynamic_wind} expression is escaped
216 non-locally, @var{out} is called. If the continuation of
217 the dynamic-wind is re-entered, @var{in} is called. Thus
218 @var{in} and @var{out} may be called any number of
221 (define x 'normal-binding)
224 (call-with-current-continuation
230 (lambda () (set! x 'special-binding))
234 (lambda () (display x) (newline)
235 (call-with-current-continuation escape)
236 (display x) (newline)
241 (lambda () (set! x old-x)))))))
248 @result{} normal-binding
253 @result{} a-cont ;; the value of the (define a-cont...)
255 @result{} normal-binding
257 @result{} special-binding
259 (@dynamic-wind in (thunk) out))
263 ;;; {Low-Level Port Code}
266 ;; These are used to request the proper mode to open files in.
268 (define OPEN_READ "r")
269 (define OPEN_WRITE "w")
270 (define OPEN_BOTH "r+")
272 (define *null-device* "/dev/null")
274 (define (open-input-file str)
275 "Takes a string naming an existing file and returns an input port
276 capable of delivering characters from the file. If the file
277 cannot be opened, an error is signalled."
278 (open-file str OPEN_READ))
280 (define (open-output-file str)
281 "Takes a string naming an output file to be created and returns an
282 output port capable of writing characters to a new file by that
283 name. If the file cannot be opened, an error is signalled. If a
284 file with the given name already exists, the effect is unspecified."
285 (open-file str OPEN_WRITE))
287 (define (open-io-file str)
288 "Open file with name STR for both input and output."
289 (open-file str OPEN_BOTH))
293 ;;; {Simple Debugging Tools}
296 ;; peek takes any number of arguments, writes them to the
297 ;; current ouput port, and returns the last argument.
298 ;; It is handy to wrap around an expression to look at
299 ;; a value each time is evaluated, e.g.:
301 ;; (+ 10 (troublesome-fn))
302 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
305 (define (peek . stuff)
310 (car (last-pair stuff)))
314 ;; Temporary definition; replaced later.
315 (define current-warning-port current-error-port)
317 (define (warn . stuff)
318 (newline (current-warning-port))
319 (display ";;; WARNING " (current-warning-port))
320 (display stuff (current-warning-port))
321 (newline (current-warning-port))
322 (car (last-pair stuff)))
329 (define (provide sym)
330 (if (not (memq sym *features*))
331 (set! *features* (cons sym *features*))))
333 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
334 ;; provided? also checks to see if the module is available. We should do that
337 (define (provided? feature)
338 (and (memq feature *features*) #t))
345 (define (make-struct/no-tail vtable . args)
346 (apply make-struct vtable 0 args))
350 ;;; Boot versions of `map' and `for-each', enough to get the expander
359 (cons (f (car l)) (map1 (cdr l))))))
361 (let map2 ((l1 l1) (l2 l2))
364 (cons (f (car l1) (car l2))
365 (map2 (cdr l1) (cdr l2))))))
367 (let lp ((l1 l1) (rest rest))
370 (cons (apply f (car l1) (map car rest))
371 (lp (cdr l1) (map cdr rest))))))))
376 (let for-each1 ((l l))
380 (for-each1 (cdr l))))))
382 (let for-each2 ((l1 l1) (l2 l2))
385 (f (car l1) (car l2))
386 (for-each2 (cdr l1) (cdr l2))))))
388 (let lp ((l1 l1) (rest rest))
391 (apply f (car l1) (map car rest))
392 (lp (cdr l1) (map cdr rest))))))))
394 ;;; {and-map and or-map}
396 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
397 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
402 ;; Apply f to successive elements of l until exhaustion or f returns #f.
403 ;; If returning early, return #f. Otherwise, return the last value returned
404 ;; by f. If f has never been called because l is empty, return #t.
406 (define (and-map f lst)
407 (let loop ((result #t)
412 (loop (f (car l)) (cdr l))))))
416 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
417 ;; If returning early, return the return value of f.
419 (define (or-map f lst)
420 (let loop ((result #f)
424 (loop (f (car l)) (cdr l))))))
428 ;; let format alias simple-format until the more complete version is loaded
430 (define format simple-format)
432 ;; this is scheme wrapping the C code so the final pred call is a tail call,
435 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
436 (if (and (procedure? char_pred)
438 (<= end (string-length s))) ;; let c-code handle range error
439 (or (string-any-c-code char_pred s start (1- end))
440 (char_pred (string-ref s (1- end))))
441 (string-any-c-code char_pred s start end))))
443 ;; this is scheme wrapping the C code so the final pred call is a tail call,
446 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
447 (if (and (procedure? char_pred)
449 (<= end (string-length s))) ;; let c-code handle range error
450 (and (string-every-c-code char_pred s start (1- end))
451 (char_pred (string-ref s (1- end))))
452 (string-every-c-code char_pred s start end))))
454 ;; A variant of string-fill! that we keep for compatability
456 (define (substring-fill! str start end fill)
457 (string-fill! str fill start end))
461 ;; Define a minimal stub of the module API for psyntax, before modules
463 (define (module-name x)
465 (define (module-add! module sym var)
466 (hashq-set! (%get-pre-modules-obarray) sym var))
467 (define (module-define! module sym val)
468 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
470 (variable-set! v val)
471 (module-add! (current-module) sym (make-variable val)))))
472 (define (module-ref module sym)
473 (let ((v (module-variable module sym)))
474 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
475 (define (resolve-module . args)
478 ;; API provided by psyntax
479 (define syntax-violation #f)
480 (define datum->syntax #f)
481 (define syntax->datum #f)
482 (define syntax-source #f)
483 (define identifier? #f)
484 (define generate-temporaries #f)
485 (define bound-identifier=? #f)
486 (define free-identifier=? #f)
488 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
489 ;; expanded macros, to dispatch an input against a set of patterns.
490 (define $sc-dispatch #f)
493 (primitive-load-path "ice-9/psyntax-pp")
494 ;; The binding for `macroexpand' has now been overridden, making psyntax the
501 ((_ x y ...) (if x (and y ...) #f))))
507 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
509 (include-from-path "ice-9/quasisyntax")
511 (define-syntax-rule (when test stmt stmt* ...)
512 (if test (begin stmt stmt* ...)))
514 (define-syntax-rule (unless test stmt stmt* ...)
515 (if (not test) (begin stmt stmt* ...)))
519 (define (fold f seed xs)
520 (let loop ((xs xs) (seed seed))
522 (loop (cdr xs) (f (car xs) seed)))))
523 (define (reverse-map f xs)
524 (fold (lambda (x seed) (cons (f x) seed))
526 (syntax-case whole-expr ()
527 ((_ clause clauses ...)
529 #,@(fold (lambda (clause-builder tail)
530 (clause-builder tail))
534 (define* (bad-clause #:optional (msg "invalid clause"))
535 (syntax-violation 'cond msg whole-expr clause))
536 (syntax-case clause (=> else)
541 (bad-clause "else must be the last clause"))))
542 ((else . _) (bad-clause))
549 ((test => receiver ...)
550 (bad-clause "wrong number of receiver expressions"))
551 ((generator guard => receiver)
553 #`((call-with-values (lambda () generator)
555 (if (apply guard vals)
556 (apply receiver vals)
558 ((generator guard => receiver ...)
559 (bad-clause "wrong number of receiver expressions"))
570 #'(clause clauses ...))))))))
574 (define (fold f seed xs)
575 (let loop ((xs xs) (seed seed))
577 (loop (cdr xs) (f (car xs) seed)))))
578 (define (fold2 f a b xs)
579 (let loop ((xs xs) (a a) (b b))
580 (if (null? xs) (values a b)
582 (lambda () (f (car xs) a b))
584 (loop (cdr xs) a b))))))
585 (define (reverse-map-with-seed f seed xs)
586 (fold2 (lambda (x ys seed)
588 (lambda () (f x seed))
590 (values (cons y ys) seed))))
592 (syntax-case whole-expr ()
593 ((_ expr clause clauses ...)
594 (with-syntax ((key #'key))
597 (lambda (clause-builder tail)
598 (clause-builder tail))
600 (reverse-map-with-seed
601 (lambda (clause seen)
602 (define* (bad-clause #:optional (msg "invalid clause"))
603 (syntax-violation 'case msg whole-expr clause))
604 (syntax-case clause ()
608 (syntax-case #'rest (=>)
609 ((=> receiver) #'(receiver key))
612 "wrong number of receiver expressions"))
613 ((e e* ...) #'(begin e e* ...))
615 (syntax-case #'test (else)
620 (define (warn-datum type)
621 ((@ (system base message)
624 (append (source-properties datum)
626 (syntax->datum #'test)))
628 (syntax->datum clause)
629 (syntax->datum whole-expr)))
630 (if (memv datum seen)
631 (warn-datum 'duplicate-case-datum))
632 (if (or (pair? datum)
634 (generalized-vector? datum))
635 (warn-datum 'bad-case-datum))
638 (map syntax->datum #'(datums ...)))))
639 (values (lambda (tail)
640 #`((if (memv key '(datums ...))
644 (else (values (lambda (tail)
648 "else must be the last clause")))
652 '() #'(clause clauses ...)))))))))
656 ((do ((var init step ...) ...)
669 (loop (do "step" var step ...)
677 (define-syntax-rule (delay exp)
678 (make-promise (lambda () exp)))
680 (define-syntax current-source-location
684 (with-syntax ((s (datum->syntax x (syntax-source x))))
687 ;; We provide this accessor out of convenience. current-line and
688 ;; current-column aren't so interesting, because they distort what they
689 ;; are measuring; better to use syntax-source from a macro.
691 (define-syntax current-filename
693 "A macro that expands to the current filename: the filename that
694 the (current-filename) form appears in. Expands to #f if this
695 information is unavailable."
697 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
699 (define-syntax-rule (define-once sym val)
701 (if (module-locally-bound? (current-module) 'sym) sym val)))
703 ;;; The real versions of `map' and `for-each', with cycle detection, and
704 ;;; that use reverse! instead of recursion in the case of `map'.
709 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
712 (if (eq? tortoise hare)
713 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
715 (map1 (cdr hare) (cdr tortoise) #f
716 (cons (f (car hare)) out)))
717 (map1 (cdr hare) tortoise #t
718 (cons (f (car hare)) out)))
721 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
725 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
730 (scm-error 'wrong-type-arg "map"
732 "List of wrong length: ~S"
736 (map2 (cdr h1) (cdr h2) t1 t2 #t
737 (cons (f (car h1) (car h2)) out)))
739 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
742 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
745 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
746 (cons (f (car h1) (car h2)) out)))))
748 ((and (null? h1) (null? h2))
752 (scm-error 'wrong-type-arg "map"
754 "List of wrong length: ~S"
758 (scm-error 'wrong-type-arg "map"
763 (let ((len (length l1)))
764 (let mapn ((rest rest))
766 (if (= (length (car rest)) len)
768 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
769 (list (car rest)) #f)))))
770 (let mapn ((l1 l1) (rest rest) (out '()))
773 (mapn (cdr l1) (map cdr rest)
774 (cons (apply f (car l1) (map car rest)) out)))))))
776 (define map-in-order map)
781 (let for-each1 ((hare l) (tortoise l) (move? #f))
784 (if (eq? tortoise hare)
785 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
789 (for-each1 (cdr hare) (cdr tortoise) #f)))
792 (for-each1 (cdr hare) tortoise #t)))
794 (if (not (null? hare))
795 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
799 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
801 ((and (pair? h1) (pair? h2))
804 (f (car h1) (car h2))
805 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
807 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
810 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
813 (f (car h1) (car h2))
814 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
817 (or (null? h2) (pair? h2))
818 (and (pair? h1) (null? h2)))
822 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
825 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
829 (let ((len (length l1)))
830 (let for-eachn ((rest rest))
832 (if (= (length (car rest)) len)
833 (for-eachn (cdr rest))
834 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
835 (list (car rest)) #f)))))
837 (let for-eachn ((l1 l1) (rest rest))
840 (apply f (car l1) (map car rest))
841 (for-eachn (cdr l1) (map cdr rest))))))))
847 ;;; Extensible exception printing.
850 (define set-exception-printer! #f)
851 ;; There is already a definition of print-exception from backtrace.c
852 ;; that we will override.
854 (let ((exception-printers '()))
855 (define (print-location frame port)
856 (let ((source (and=> frame frame-source)))
857 ;; source := (addr . (filename . (line . column)))
859 (let ((filename (or (cadr source) "<unnamed port>"))
860 (line (caddr source))
861 (col (cdddr source)))
862 (format port "~a:~a:~a: " filename (1+ line) col))
863 (format port "ERROR: "))))
865 (set! set-exception-printer!
867 (set! exception-printers (acons key proc exception-printers))))
869 (set! print-exception
870 (lambda (port frame key args)
871 (define (default-printer)
872 (format port "Throw to key `~a' with args `~s'." key args))
875 (let ((proc (frame-procedure frame)))
876 (print-location frame port)
877 (format port "In procedure ~a:\n"
878 (or (false-if-exception (procedure-name proc))
881 (print-location frame port)
884 (let ((printer (assq-ref exception-printers key)))
886 (printer port key args default-printer)
889 (format port "Error while printing exception.")))
891 (force-output port))))
894 ;;; Printers for those keys thrown by Guile.
897 (define (scm-error-printer port key args default-printer)
898 ;; Abuse case-lambda as a pattern matcher, given that we don't have
899 ;; ice-9 match at this point.
901 ((subr msg args . rest)
903 (format port "In procedure ~a: " subr))
904 (apply format port msg (or args '())))
905 (_ (default-printer)))
908 (define (syntax-error-printer port key args default-printer)
910 ((who what where form subform . extra)
911 (format port "Syntax error:\n")
913 (let ((file (or (assq-ref where 'filename) "unknown file"))
914 (line (and=> (assq-ref where 'line) 1+))
915 (col (assq-ref where 'column)))
916 (format port "~a:~a:~a: " file line col))
917 (format port "unknown location: "))
919 (format port "~a: " who))
920 (format port "~a" what)
922 (format port " in subform ~s of ~s" subform form)
924 (format port " in form ~s" form))))
925 (_ (default-printer)))
928 (define (getaddrinfo-error-printer port key args default-printer)
929 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
931 (set-exception-printer! 'goops-error scm-error-printer)
932 (set-exception-printer! 'host-not-found scm-error-printer)
933 (set-exception-printer! 'keyword-argument-error scm-error-printer)
934 (set-exception-printer! 'misc-error scm-error-printer)
935 (set-exception-printer! 'no-data scm-error-printer)
936 (set-exception-printer! 'no-recovery scm-error-printer)
937 (set-exception-printer! 'null-pointer-error scm-error-printer)
938 (set-exception-printer! 'out-of-range scm-error-printer)
939 (set-exception-printer! 'program-error scm-error-printer)
940 (set-exception-printer! 'read-error scm-error-printer)
941 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
942 (set-exception-printer! 'signal scm-error-printer)
943 (set-exception-printer! 'stack-overflow scm-error-printer)
944 (set-exception-printer! 'system-error scm-error-printer)
945 (set-exception-printer! 'try-again scm-error-printer)
946 (set-exception-printer! 'unbound-variable scm-error-printer)
947 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
948 (set-exception-printer! 'wrong-type-arg scm-error-printer)
950 (set-exception-printer! 'syntax-error syntax-error-printer)
952 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
960 (define-syntax define-macro
964 ((_ (macro . args) doc body1 body ...)
965 (string? (syntax->datum #'doc))
966 #'(define-macro macro doc (lambda args body1 body ...)))
967 ((_ (macro . args) body ...)
968 #'(define-macro macro #f (lambda args body ...)))
969 ((_ macro doc transformer)
970 (or (string? (syntax->datum #'doc))
971 (not (syntax->datum #'doc)))
972 #'(define-syntax macro
975 #((macro-type . defmacro)
976 (defmacro-args args))
979 (let ((v (syntax->datum #'args)))
980 (datum->syntax y (apply transformer v)))))))))))
982 (define-syntax defmacro
984 "Define a defmacro, with the old lispy defun syntax."
986 ((_ macro args doc body1 body ...)
987 (string? (syntax->datum #'doc))
988 #'(define-macro macro doc (lambda args body1 body ...)))
989 ((_ macro args body ...)
990 #'(define-macro macro #f (lambda args body ...))))))
999 (define-syntax begin-deprecated
1003 (if (include-deprecated-features)
1004 #'(begin form form* ...)
1009 ;;; {Trivial Functions}
1012 (define (identity x) x)
1014 (define (compose proc . rest)
1015 "Compose PROC with the procedures in REST, such that the last one in
1016 REST is applied first and PROC last, and return the resulting procedure.
1017 The given procedures must have compatible arity."
1020 (let ((g (apply compose rest)))
1022 (call-with-values (lambda () (apply g args)) proc)))))
1024 (define (negate proc)
1025 "Return a procedure with the same arity as PROC that returns the `not'
1028 (not (apply proc args))))
1030 (define (const value)
1031 "Return a procedure that accepts any number of arguments and returns
1036 (define (and=> value procedure) (and value (procedure value)))
1037 (define call/cc call-with-current-continuation)
1039 (define-syntax-rule (false-if-exception expr)
1042 (lambda (k . args) #f)))
1046 ;;; {General Properties}
1049 ;; Properties are a lispy way to associate random info with random objects.
1050 ;; Traditionally properties are implemented as an alist or a plist actually
1051 ;; pertaining to the object in question.
1053 ;; These "object properties" have the advantage that they can be associated with
1054 ;; any object, even if the object has no plist. Object properties are good when
1055 ;; you are extending pre-existing objects in unexpected ways. They also present
1056 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
1057 ;; type that always has properties, it's often still best to store those
1058 ;; properties within the object itself.
1060 (define (make-object-property)
1061 ;; Weak tables are thread-safe.
1062 (let ((prop (make-weak-key-hash-table)))
1063 (make-procedure-with-setter
1064 (lambda (obj) (hashq-ref prop obj))
1065 (lambda (obj val) (hashq-set! prop obj val)))))
1070 ;;; {Symbol Properties}
1073 ;;; Symbol properties are something you see in old Lisp code. In most current
1074 ;;; Guile code, symbols are not used as a data structure -- they are used as
1075 ;;; keys into other data structures.
1077 (define (symbol-property sym prop)
1078 (let ((pair (assoc prop (symbol-pref sym))))
1079 (and pair (cdr pair))))
1081 (define (set-symbol-property! sym prop val)
1082 (let ((pair (assoc prop (symbol-pref sym))))
1085 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
1087 (define (symbol-property-remove! sym prop)
1088 (let ((pair (assoc prop (symbol-pref sym))))
1090 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
1097 (define (array-shape a)
1098 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1099 (array-dimensions a)))
1106 ;;; It's much better if you can use lambda* / define*, of course.
1108 (define (kw-arg-ref args kw)
1109 (let ((rem (member kw args)))
1110 (and rem (pair? (cdr rem)) (cadr rem))))
1117 (define (struct-layout s)
1118 (struct-ref (struct-vtable s) vtable-index-layout))
1125 ;; Printing records: by default, records are printed as
1127 ;; #<type-name field1: val1 field2: val2 ...>
1129 ;; You can change that by giving a custom printing function to
1130 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1131 ;; will be called like
1133 ;; (<printer> object port)
1135 ;; It should print OBJECT to PORT.
1137 (define (inherit-print-state old-port new-port)
1138 (if (get-print-state old-port)
1139 (port-with-print-state new-port (get-print-state old-port))
1142 ;; 0: type-name, 1: fields, 2: constructor
1143 (define record-type-vtable
1144 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1146 (display "#<record-type " p)
1147 (display (record-type-name s) p)
1149 (set-struct-vtable-name! s 'record-type)
1152 (define (record-type? obj)
1153 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1155 (define* (make-record-type type-name fields #:optional printer)
1156 ;; Pre-generate constructors for nfields < 20.
1157 (define-syntax make-constructor
1159 (define *max-static-argument-count* 20)
1160 (define (make-formals n)
1163 (cons (datum->syntax
1166 (string (integer->char (+ (char->integer #\a) i)))))
1170 ((_ rtd exp) (not (identifier? #'exp))
1172 (make-constructor rtd n)))
1176 (if (< n *max-static-argument-count*)
1177 (cons (with-syntax (((formal ...) (make-formals n))
1180 (lambda (formal ...)
1181 (make-struct rtd 0 formal ...))))
1186 (if (= (length args) nfields)
1187 (apply make-struct rtd 0 args)
1188 (scm-error 'wrong-number-of-args
1189 (format #f "make-~a" type-name)
1190 "Wrong number of arguments" '() #f)))))))))
1192 (define (default-record-printer s p)
1194 (display (record-type-name (record-type-descriptor s)) p)
1195 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1198 ((not (null? fields))
1200 (display (car fields) p)
1202 (display (struct-ref s off) p)
1203 (loop (cdr fields) (+ 1 off)))))
1206 (let ((rtd (make-struct record-type-vtable 0
1208 (apply string-append
1209 (map (lambda (f) "pw") fields)))
1210 (or printer default-record-printer)
1212 (copy-tree fields))))
1213 (struct-set! rtd (+ vtable-offset-user 2)
1214 (make-constructor rtd (length fields)))
1215 ;; Temporary solution: Associate a name to the record type descriptor
1216 ;; so that the object system can create a wrapper class for it.
1217 (set-struct-vtable-name! rtd (if (symbol? type-name)
1219 (string->symbol type-name)))
1222 (define (record-type-name obj)
1223 (if (record-type? obj)
1224 (struct-ref obj vtable-offset-user)
1225 (error 'not-a-record-type obj)))
1227 (define (record-type-fields obj)
1228 (if (record-type? obj)
1229 (struct-ref obj (+ 1 vtable-offset-user))
1230 (error 'not-a-record-type obj)))
1232 (define* (record-constructor rtd #:optional field-names)
1233 (if (not field-names)
1234 (struct-ref rtd (+ 2 vtable-offset-user))
1236 `(lambda ,field-names
1237 (make-struct ',rtd 0 ,@(map (lambda (f)
1238 (if (memq f field-names)
1241 (record-type-fields rtd)))))))
1243 (define (record-predicate rtd)
1244 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1246 (define (%record-type-error rtd obj) ;; private helper
1247 (or (eq? rtd (record-type-descriptor obj))
1248 (scm-error 'wrong-type-arg "%record-type-check"
1249 "Wrong type record (want `~S'): ~S"
1250 (list (record-type-name rtd) obj)
1253 (define (record-accessor rtd field-name)
1254 (let ((pos (list-index (record-type-fields rtd) field-name)))
1256 (error 'no-such-field field-name))
1258 (if (eq? (struct-vtable obj) rtd)
1259 (struct-ref obj pos)
1260 (%record-type-error rtd obj)))))
1262 (define (record-modifier rtd field-name)
1263 (let ((pos (list-index (record-type-fields rtd) field-name)))
1265 (error 'no-such-field field-name))
1267 (if (eq? (struct-vtable obj) rtd)
1268 (struct-set! obj pos val)
1269 (%record-type-error rtd obj)))))
1271 (define (record? obj)
1272 (and (struct? obj) (record-type? (struct-vtable obj))))
1274 (define (record-type-descriptor obj)
1277 (error 'not-a-record obj)))
1287 ;; Three fields: the procedure itself, the fluid, and the converter.
1288 (make-struct <applicable-struct-vtable> 0 'pwprpr))
1289 (set-struct-vtable-name! <parameter> '<parameter>)
1291 (define* (make-parameter init #:optional (conv (lambda (x) x)))
1292 (let ((fluid (make-fluid (conv init))))
1293 (make-struct <parameter> 0
1295 (() (fluid-ref fluid))
1296 ((x) (let ((prev (fluid-ref fluid)))
1297 (fluid-set! fluid (conv x))
1301 (define (parameter? x)
1302 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
1304 (define (parameter-fluid p)
1307 (scm-error 'wrong-type-arg "parameter-fluid"
1308 "Not a parameter: ~S" (list p) #f)))
1310 (define (parameter-converter p)
1313 (scm-error 'wrong-type-arg "parameter-fluid"
1314 "Not a parameter: ~S" (list p) #f)))
1316 (define-syntax parameterize
1319 ((_ ((param value) ...) body body* ...)
1320 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
1321 #'(let ((p param) ...)
1322 (if (not (parameter? p))
1323 (scm-error 'wrong-type-arg "parameterize"
1324 "Not a parameter: ~S" (list p) #f))
1326 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
1328 body body* ...)))))))
1332 ;;; Once parameters have booted, define the default prompt tag as being
1336 (set! default-prompt-tag (make-parameter (default-prompt-tag)))
1340 ;;; Current ports as parameters.
1343 (let ((fluid->parameter
1344 (lambda (fluid conv)
1345 (make-struct <parameter> 0
1347 (() (fluid-ref fluid))
1348 ((x) (let ((prev (fluid-ref fluid)))
1349 (fluid-set! fluid (conv x))
1352 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
1354 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
1358 (hashq-remove! (%get-pre-modules-obarray) 'fluid)))
1360 (port-parameterize! current-input-port %current-input-port-fluid
1361 input-port? "expected an input port")
1362 (port-parameterize! current-output-port %current-output-port-fluid
1363 output-port? "expected an output port")
1364 (port-parameterize! current-error-port %current-error-port-fluid
1365 output-port? "expected an output port"))
1372 (define current-warning-port
1373 (make-parameter (current-error-port)
1375 (if (output-port? x)
1377 (error "expected an output port" x)))))
1381 ;;; {High-Level Port Routines}
1384 (define (call-with-input-file str proc)
1385 "PROC should be a procedure of one argument, and STR should be a
1386 string naming a file. The file must already exist. These procedures
1387 call PROC with one argument: the port obtained by opening the named file
1388 for input or output. If the file cannot be opened, an error is
1389 signalled. If the procedure returns, then the port is closed
1390 automatically and the values yielded by the procedure are returned. If
1391 the procedure does not return, then the port will not be closed
1392 automatically unless it is possible to prove that the port will never
1393 again be used for a read or write operation."
1394 (let ((p (open-input-file str)))
1396 (lambda () (proc p))
1398 (close-input-port p)
1399 (apply values vals)))))
1401 (define (call-with-output-file str proc)
1402 "PROC should be a procedure of one argument, and STR should be a
1403 string naming a file. The behaviour is unspecified if the file
1404 already exists. These procedures call PROC
1405 with one argument: the port obtained by opening the named file for
1406 input or output. If the file cannot be opened, an error is
1407 signalled. If the procedure returns, then the port is closed
1408 automatically and the values yielded by the procedure are returned.
1409 If the procedure does not return, then the port will not be closed
1410 automatically unless it is possible to prove that the port will
1411 never again be used for a read or write operation."
1412 (let ((p (open-output-file str)))
1414 (lambda () (proc p))
1416 (close-output-port p)
1417 (apply values vals)))))
1419 (define (with-input-from-port port thunk)
1420 (parameterize ((current-input-port port))
1423 (define (with-output-to-port port thunk)
1424 (parameterize ((current-output-port port))
1427 (define (with-error-to-port port thunk)
1428 (parameterize ((current-error-port port))
1431 (define (with-input-from-file file thunk)
1432 "THUNK must be a procedure of no arguments, and FILE must be a
1433 string naming a file. The file must already exist. The file is opened for
1434 input, an input port connected to it is made
1435 the default value returned by `current-input-port',
1436 and the THUNK is called with no arguments.
1437 When the THUNK returns, the port is closed and the previous
1438 default is restored. Returns the values yielded by THUNK. If an
1439 escape procedure is used to escape from the continuation of these
1440 procedures, their behavior is implementation dependent."
1441 (call-with-input-file file
1442 (lambda (p) (with-input-from-port p thunk))))
1444 (define (with-output-to-file file thunk)
1445 "THUNK must be a procedure of no arguments, and FILE must be a
1446 string naming a file. The effect is unspecified if the file already exists.
1447 The file is opened for output, an output port connected to it is made
1448 the default value returned by `current-output-port',
1449 and the THUNK is called with no arguments.
1450 When the THUNK returns, the port is closed and the previous
1451 default is restored. Returns the values yielded by THUNK. If an
1452 escape procedure is used to escape from the continuation of these
1453 procedures, their behavior is implementation dependent."
1454 (call-with-output-file file
1455 (lambda (p) (with-output-to-port p thunk))))
1457 (define (with-error-to-file file thunk)
1458 "THUNK must be a procedure of no arguments, and FILE must be a
1459 string naming a file. The effect is unspecified if the file already exists.
1460 The file is opened for output, an output port connected to it is made
1461 the default value returned by `current-error-port',
1462 and the THUNK is called with no arguments.
1463 When the THUNK returns, the port is closed and the previous
1464 default is restored. Returns the values yielded by THUNK. If an
1465 escape procedure is used to escape from the continuation of these
1466 procedures, their behavior is implementation dependent."
1467 (call-with-output-file file
1468 (lambda (p) (with-error-to-port p thunk))))
1470 (define (call-with-input-string string proc)
1471 "Calls the one-argument procedure @var{proc} with a newly created
1472 input port from which @var{string}'s contents may be read. The value
1473 yielded by the @var{proc} is returned."
1474 (proc (open-input-string string)))
1476 (define (with-input-from-string string thunk)
1477 "THUNK must be a procedure of no arguments.
1478 The test of STRING is opened for
1479 input, an input port connected to it is made,
1480 and the THUNK is called with no arguments.
1481 When the THUNK returns, the port is closed.
1482 Returns the values yielded by THUNK. If an
1483 escape procedure is used to escape from the continuation of these
1484 procedures, their behavior is implementation dependent."
1485 (call-with-input-string string
1486 (lambda (p) (with-input-from-port p thunk))))
1488 (define (call-with-output-string proc)
1489 "Calls the one-argument procedure @var{proc} with a newly created output
1490 port. When the function returns, the string composed of the characters
1491 written into the port is returned."
1492 (let ((port (open-output-string)))
1494 (get-output-string port)))
1496 (define (with-output-to-string thunk)
1497 "Calls THUNK and returns its output as a string."
1498 (call-with-output-string
1499 (lambda (p) (with-output-to-port p thunk))))
1501 (define (with-error-to-string thunk)
1502 "Calls THUNK and returns its error output as a string."
1503 (call-with-output-string
1504 (lambda (p) (with-error-to-port p thunk))))
1506 (define the-eof-object (call-with-input-string "" (lambda (p) (read-char p))))
1513 (define (->bool x) (not (not x)))
1520 (define (symbol-append . args)
1521 (string->symbol (apply string-append (map symbol->string args))))
1523 (define (list->symbol . args)
1524 (string->symbol (apply list->string args)))
1526 (define (symbol . args)
1527 (string->symbol (apply string args)))
1534 (define (list-index l k)
1537 (and (not (null? l))
1540 (loop (+ n 1) (cdr l))))))
1544 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1545 ;; `stat' accessors.
1546 (primitive-load-path "ice-9/posix")
1548 (if (provided? 'socket)
1549 (primitive-load-path "ice-9/networking"))
1551 ;; For reference, Emacs file-exists-p uses stat in this same way.
1552 (define file-exists?
1553 (if (provided? 'posix)
1555 (->bool (stat str #f)))
1557 (let ((port (catch 'system-error (lambda () (open-input-file str))
1559 (if port (begin (close-port port) #t)
1562 (define file-is-directory?
1563 (if (provided? 'posix)
1565 (eq? (stat:type (stat str)) 'directory))
1567 (let ((port (catch 'system-error
1569 (open-input-file (string-append str "/.")))
1571 (if port (begin (close-port port) #t)
1574 (define (system-error-errno args)
1575 (if (eq? (car args) 'system-error)
1576 (car (list-ref args 4))
1581 ;;; {Error Handling}
1587 (scm-error 'misc-error #f "?" #f #f))
1589 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1590 (scm-error 'misc-error #f msg (cons message args) #f)))))
1594 ;;; {Time Structures}
1597 (define (tm:sec obj) (vector-ref obj 0))
1598 (define (tm:min obj) (vector-ref obj 1))
1599 (define (tm:hour obj) (vector-ref obj 2))
1600 (define (tm:mday obj) (vector-ref obj 3))
1601 (define (tm:mon obj) (vector-ref obj 4))
1602 (define (tm:year obj) (vector-ref obj 5))
1603 (define (tm:wday obj) (vector-ref obj 6))
1604 (define (tm:yday obj) (vector-ref obj 7))
1605 (define (tm:isdst obj) (vector-ref obj 8))
1606 (define (tm:gmtoff obj) (vector-ref obj 9))
1607 (define (tm:zone obj) (vector-ref obj 10))
1609 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1610 (define (set-tm:min obj val) (vector-set! obj 1 val))
1611 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1612 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1613 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1614 (define (set-tm:year obj val) (vector-set! obj 5 val))
1615 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1616 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1617 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1618 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1619 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1621 (define (tms:clock obj) (vector-ref obj 0))
1622 (define (tms:utime obj) (vector-ref obj 1))
1623 (define (tms:stime obj) (vector-ref obj 2))
1624 (define (tms:cutime obj) (vector-ref obj 3))
1625 (define (tms:cstime obj) (vector-ref obj 4))
1629 ;;; {File Descriptors and Ports}
1632 (define file-position ftell)
1633 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1634 (seek port offset whence))
1636 (define (move->fdes fd/port fd)
1637 (cond ((integer? fd/port)
1638 (dup->fdes fd/port fd)
1642 (primitive-move->fdes fd/port fd)
1643 (set-port-revealed! fd/port 1)
1646 (define (release-port-handle port)
1647 (let ((revealed (port-revealed port)))
1649 (set-port-revealed! port (- revealed 1)))))
1654 (fdopen (dup->fdes port/fd) mode))
1655 ((port/fd mode new-fd)
1656 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1657 (set-port-revealed! port 1)
1663 (dup->port port/fd "r"))
1665 (dup->port port/fd "r" new-fd))))
1667 (define dup->outport
1670 (dup->port port/fd "w"))
1672 (dup->port port/fd "w" new-fd))))
1677 (if (integer? port/fd)
1679 (dup->port port/fd (port-mode port/fd))))
1681 (if (integer? port/fd)
1682 (dup->fdes port/fd new-fd)
1683 (dup->port port/fd (port-mode port/fd) new-fd)))))
1685 (define (duplicate-port port modes)
1686 (dup->port port modes))
1688 (define (fdes->inport fdes)
1689 (let loop ((rest-ports (fdes->ports fdes)))
1690 (cond ((null? rest-ports)
1691 (let ((result (fdopen fdes "r")))
1692 (set-port-revealed! result 1)
1694 ((input-port? (car rest-ports))
1695 (set-port-revealed! (car rest-ports)
1696 (+ (port-revealed (car rest-ports)) 1))
1699 (loop (cdr rest-ports))))))
1701 (define (fdes->outport fdes)
1702 (let loop ((rest-ports (fdes->ports fdes)))
1703 (cond ((null? rest-ports)
1704 (let ((result (fdopen fdes "w")))
1705 (set-port-revealed! result 1)
1707 ((output-port? (car rest-ports))
1708 (set-port-revealed! (car rest-ports)
1709 (+ (port-revealed (car rest-ports)) 1))
1712 (loop (cdr rest-ports))))))
1714 (define (port->fdes port)
1715 (set-port-revealed! port (+ (port-revealed port) 1))
1718 (define (setenv name value)
1720 (putenv (string-append name "=" value))
1723 (define (unsetenv name)
1724 "Remove the entry for NAME from the environment."
1732 (define (in-vicinity vicinity file)
1733 (let ((tail (let ((len (string-length vicinity)))
1736 (string-ref vicinity (- len 1))))))
1737 (string-append vicinity
1746 ;;; {Help for scm_shell}
1748 ;;; The argument-processing code used by Guile-based shells generates
1749 ;;; Scheme code based on the argument list. This page contains help
1750 ;;; functions for the code it generates.
1753 (define (command-line) (program-arguments))
1755 ;; This is mostly for the internal use of the code generated by
1756 ;; scm_compile_shell_switches.
1758 (define (load-user-init)
1759 (let* ((home (or (getenv "HOME")
1760 (false-if-exception (passwd:dir (getpwuid (getuid))))
1761 "/")) ;; fallback for cygwin etc.
1762 (init-file (in-vicinity home ".guile")))
1763 (if (file-exists? init-file)
1764 (primitive-load init-file))))
1768 ;;; {The interpreter stack}
1771 ;; %stacks defined in stacks.c
1772 (define (%start-stack tag thunk)
1773 (let ((prompt-tag (make-prompt-tag "start-stack")))
1777 (with-fluids ((%stacks (acons tag prompt-tag
1778 (or (fluid-ref %stacks) '()))))
1781 (%start-stack tag (lambda () (apply k args)))))))
1783 (define-syntax-rule (start-stack tag exp)
1784 (%start-stack tag (lambda () exp)))
1788 ;;; {Loading by paths}
1791 ;;; Load a Scheme source file named NAME, searching for it in the
1792 ;;; directories listed in %load-path, and applying each of the file
1793 ;;; name extensions listed in %load-extensions.
1794 (define (load-from-path name)
1795 (start-stack 'load-stack
1796 (primitive-load-path name)))
1798 (define-syntax-rule (add-to-load-path elt)
1799 "Add ELT to Guile's load path, at compile-time and at run-time."
1800 (eval-when (compile load eval)
1801 (set! %load-path (cons elt %load-path))))
1803 (define %load-verbosely #f)
1804 (define (assert-load-verbosity v) (set! %load-verbosely v))
1806 (define (%load-announce file)
1808 (with-output-to-port (current-warning-port)
1811 (display "loading ")
1816 (set! %load-hook %load-announce)
1820 ;;; {Reader Extensions}
1822 ;;; Reader code for various "#c" forms.
1825 (define read-eval? (make-fluid #f))
1826 (read-hash-extend #\.
1828 (if (fluid-ref read-eval?)
1829 (eval (read port) (interaction-environment))
1831 "#. read expansion found and read-eval? is #f."))))
1835 ;;; {Low Level Modules}
1837 ;;; These are the low level data structures for modules.
1839 ;;; Every module object is of the type 'module-type', which is a record
1840 ;;; consisting of the following members:
1842 ;;; - eval-closure: the function that defines for its module the strategy that
1843 ;;; shall be followed when looking up symbols in the module.
1845 ;;; An eval-closure is a function taking two arguments: the symbol to be
1846 ;;; looked up and a boolean value telling whether a binding for the symbol
1847 ;;; should be created if it does not exist yet. If the symbol lookup
1848 ;;; succeeded (either because an existing binding was found or because a new
1849 ;;; binding was created), a variable object representing the binding is
1850 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1851 ;;; closure does not take the module to be searched as an argument: During
1852 ;;; construction of the eval-closure, the eval-closure has to store the
1853 ;;; module it belongs to in its environment. This means, that any
1854 ;;; eval-closure can belong to only one module.
1856 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1857 ;;; special cases of eval-closures are to be distinguished: During startup
1858 ;;; the module system is not yet activated. In this phase, no modules are
1859 ;;; defined and all bindings are automatically stored by the system in the
1860 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1861 ;;; functions which require an eval-closure as their argument need to be
1862 ;;; passed the value #f.
1864 ;;; The other two special cases of eval-closures are the
1865 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1866 ;;; behave equally for the case that no new binding is to be created. The
1867 ;;; difference between the two comes in, when the boolean argument to the
1868 ;;; eval-closure indicates that a new binding shall be created if it is not
1871 ;;; Given that no new binding shall be created, both standard eval-closures
1872 ;;; define the following standard strategy of searching bindings in the
1873 ;;; module: First, the module's obarray is searched for the symbol. Second,
1874 ;;; if no binding for the symbol was found in the module's obarray, the
1875 ;;; module's binder procedure is exececuted. If this procedure did not
1876 ;;; return a binding for the symbol, the modules referenced in the module's
1877 ;;; uses list are recursively searched for a binding of the symbol. If the
1878 ;;; binding can not be found in these modules also, the symbol lookup has
1881 ;;; If a new binding shall be created, the standard-interface-eval-closure
1882 ;;; immediately returns indicating failure. That is, it does not even try
1883 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1884 ;;; first search the obarray, and if no binding was found there, would
1885 ;;; create a new binding in the obarray, therefore not calling the binder
1886 ;;; procedure or searching the modules in the uses list.
1888 ;;; The explanation of the following members obarray, binder and uses
1889 ;;; assumes that the symbol lookup follows the strategy that is defined in
1890 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1892 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1893 ;;; hash table, the definitions are found that are local to the module (that
1894 ;;; is, not imported from other modules). When looking up bindings in the
1895 ;;; module, this hash table is searched first.
1897 ;;; - binder: either #f or a function taking a module and a symbol argument.
1898 ;;; If it is a function it is called after the obarray has been
1899 ;;; unsuccessfully searched for a binding. It then can provide bindings
1900 ;;; that would otherwise not be found locally in the module.
1902 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1903 ;;; These modules are the third place queried for bindings after the obarray
1904 ;;; has been unsuccessfully searched and the binder function did not deliver
1905 ;;; a result either.
1907 ;;; - transformer: either #f or a function taking a scheme expression as
1908 ;;; delivered by read. If it is a function, it will be called to perform
1909 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1910 ;;; expression. The output of the transformer function will then be passed
1911 ;;; to Guile's internal memoizer. This means that the output must be valid
1912 ;;; scheme code. The only exception is, that the output may make use of the
1913 ;;; syntax extensions provided to identify the modules that a binding
1916 ;;; - name: the name of the module. This is used for all kinds of printing
1917 ;;; outputs. In certain places the module name also serves as a way of
1918 ;;; identification. When adding a module to the uses list of another
1919 ;;; module, it is made sure that the new uses list will not contain two
1920 ;;; modules of the same name.
1922 ;;; - kind: classification of the kind of module. The value is (currently?)
1923 ;;; only used for printing. It has no influence on how a module is treated.
1924 ;;; Currently the following values are used when setting the module kind:
1925 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1926 ;;; is set, it defaults to 'module.
1928 ;;; - duplicates-handlers: a list of procedures that get called to make a
1929 ;;; choice between two duplicate bindings when name clashes occur. See the
1930 ;;; `duplicate-handlers' global variable below.
1932 ;;; - observers: a list of procedures that get called when the module is
1935 ;;; - weak-observers: a weak-key hash table of procedures that get called
1936 ;;; when the module is modified. See `module-observe-weak' for details.
1938 ;;; In addition, the module may (must?) contain a binding for
1939 ;;; `%module-public-interface'. This variable should be bound to a module
1940 ;;; representing the exported interface of a module. See the
1941 ;;; `module-public-interface' and `module-export!' procedures.
1943 ;;; !!! warning: The interface to lazy binder procedures is going
1944 ;;; to be changed in an incompatible way to permit all the basic
1945 ;;; module ops to be virtualized.
1947 ;;; (make-module size use-list lazy-binding-proc) => module
1948 ;;; module-{obarray,uses,binder}[|-set!]
1949 ;;; (module? obj) => [#t|#f]
1950 ;;; (module-locally-bound? module symbol) => [#t|#f]
1951 ;;; (module-bound? module symbol) => [#t|#f]
1952 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1953 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1954 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1955 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1956 ;;; (module-symbol-binding module symbol opt-value)
1957 ;;; => [ <obj> | opt-value | an error occurs ]
1958 ;;; (module-make-local-var! module symbol) => #<variable...>
1959 ;;; (module-add! module symbol var) => unspecified
1960 ;;; (module-remove! module symbol) => unspecified
1961 ;;; (module-for-each proc module) => unspecified
1962 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1963 ;;; (set-current-module module) => unspecified
1964 ;;; (current-module) => #<module...>
1970 ;;; {Printing Modules}
1973 ;; This is how modules are printed. You can re-define it.
1974 (define (%print-module mod port)
1976 (display (or (module-kind mod) "module") port)
1978 (display (module-name mod) port)
1980 (display (number->string (object-address mod) 16) port)
1984 ;; Locally extend the syntax to allow record accessors to be defined at
1985 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1986 ;; the setters, in order to allow for redefinition of the record type; not
1987 ;; relevant in the case of modules, but perhaps if we make this public, it
1990 ((define-record-type
1992 (define (make-id scope . fragments)
1993 (datum->syntax scope
1994 (apply symbol-append
1996 (if (symbol? x) x (syntax->datum x)))
1999 (define (getter rtd type-name field slot)
2000 #`(define #,(make-id rtd type-name '- field)
2002 (lambda (#,type-name)
2003 (if (eq? (struct-vtable #,type-name) rtd)
2004 (struct-ref #,type-name #,slot)
2005 (%record-type-error rtd #,type-name))))))
2007 (define (setter rtd type-name field slot)
2008 #`(define #,(make-id rtd 'set- type-name '- field '!)
2010 (lambda (#,type-name val)
2011 (if (eq? (struct-vtable #,type-name) rtd)
2012 (struct-set! #,type-name #,slot val)
2013 (%record-type-error rtd #,type-name))))))
2015 (define (accessors rtd type-name fields n exp)
2016 (syntax-case fields ()
2018 (((field #:no-accessors) field* ...) (identifier? #'field)
2019 (accessors rtd type-name #'(field* ...) (1+ n)
2021 (((field #:no-setter) field* ...) (identifier? #'field)
2022 (accessors rtd type-name #'(field* ...) (1+ n)
2024 #,(getter rtd type-name #'field n))))
2025 (((field #:no-getter) field* ...) (identifier? #'field)
2026 (accessors rtd type-name #'(field* ...) (1+ n)
2028 #,(setter rtd type-name #'field n))))
2029 ((field field* ...) (identifier? #'field)
2030 (accessors rtd type-name #'(field* ...) (1+ n)
2032 #,(getter rtd type-name #'field n)
2033 #,(setter rtd type-name #'field n))))))
2035 (define (predicate rtd type-name fields exp)
2037 rtd type-name fields 0
2040 (define (#,(make-id rtd type-name '?) obj)
2041 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
2043 (define (field-list fields)
2044 (syntax-case fields ()
2046 (((f . opts) . rest) (identifier? #'f)
2047 (cons #'f (field-list #'rest)))
2048 ((f . rest) (identifier? #'f)
2049 (cons #'f (field-list #'rest)))))
2051 (define (constructor rtd type-name fields exp)
2052 (let ((ctor (make-id rtd type-name '-constructor))
2053 (args (field-list fields)))
2054 (predicate rtd type-name fields
2059 (make-struct rtd 0 #,@args))))
2060 (struct-set! #,rtd (+ vtable-offset-user 2)
2063 (define (type type-name printer fields)
2064 (define (make-layout)
2065 (let lp ((fields fields) (slots '()))
2066 (syntax-case fields ()
2067 (() (datum->syntax #'here
2069 (apply string-append slots))))
2070 ((_ . rest) (lp #'rest (cons "pw" slots))))))
2072 (let ((rtd (make-id type-name type-name '-type)))
2073 (constructor rtd type-name fields
2076 (make-struct record-type-vtable 0
2080 '#,(field-list fields)))
2081 (set-struct-vtable-name! #,rtd '#,type-name)))))
2084 ((_ type-name printer (field ...))
2085 (type #'type-name #'printer #'(field ...)))))))
2089 ;; A module is characterized by an obarray in which local symbols
2090 ;; are interned, a list of modules, "uses", from which non-local
2091 ;; bindings can be inherited, and an optional lazy-binder which
2092 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
2093 ;; bindings that would otherwise not be found locally in the module.
2095 ;; NOTE: If you change the set of fields or their order, you also need to
2096 ;; change the constants in libguile/modules.h.
2098 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
2099 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
2100 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
2101 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
2103 (define-record-type module
2104 (lambda (obj port) (%print-module obj port))
2109 (transformer #:no-getter)
2113 (import-obarray #:no-setter)
2115 (weak-observers #:no-setter)
2123 ;; make-module &opt size uses binder
2125 ;; Create a new module, perhaps with a particular size of obarray,
2126 ;; initial uses list, or binding procedure.
2128 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
2129 (if (not (integer? size))
2130 (error "Illegal size to make-module." size))
2131 (if (not (and (list? uses)
2132 (and-map module? uses)))
2133 (error "Incorrect use list." uses))
2134 (if (and binder (not (procedure? binder)))
2136 "Lazy-binder expected to be a procedure or #f." binder))
2138 (let ((module (module-constructor (make-hash-table size)
2139 uses binder #f macroexpand
2143 (make-weak-key-hash-table 31) #f
2144 (make-hash-table 7) #f #f #f)))
2146 ;; We can't pass this as an argument to module-constructor,
2147 ;; because we need it to close over a pointer to the module
2149 (set-module-eval-closure! module (standard-eval-closure module))
2156 ;;; {Observer protocol}
2159 (define (module-observe module proc)
2160 (set-module-observers! module (cons proc (module-observers module)))
2163 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
2164 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
2165 ;; be any Scheme object). PROC is invoked and passed MODULE any time
2166 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
2167 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
2170 ;; The two-argument version is kept for backward compatibility: when called
2171 ;; with two arguments, the observer gets unregistered when closure PROC
2172 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
2173 (hashq-set! (module-weak-observers module) observer-id proc))
2175 (define (module-unobserve token)
2176 (let ((module (car token))
2179 (hash-remove! (module-weak-observers module) id)
2180 (set-module-observers! module (delq1! id (module-observers module)))))
2183 (define module-defer-observers #f)
2184 (define module-defer-observers-mutex (make-mutex 'recursive))
2185 (define module-defer-observers-table (make-hash-table))
2187 (define (module-modified m)
2188 (if module-defer-observers
2189 (hash-set! module-defer-observers-table m #t)
2190 (module-call-observers m)))
2192 ;;; This function can be used to delay calls to observers so that they
2193 ;;; can be called once only in the face of massive updating of modules.
2195 (define (call-with-deferred-observers thunk)
2198 (lock-mutex module-defer-observers-mutex)
2199 (set! module-defer-observers #t))
2202 (set! module-defer-observers #f)
2203 (hash-for-each (lambda (m dummy)
2204 (module-call-observers m))
2205 module-defer-observers-table)
2206 (hash-clear! module-defer-observers-table)
2207 (unlock-mutex module-defer-observers-mutex))))
2209 (define (module-call-observers m)
2210 (for-each (lambda (proc) (proc m)) (module-observers m))
2212 ;; We assume that weak observers don't (un)register themselves as they are
2213 ;; called since this would preclude proper iteration over the hash table
2215 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
2219 ;;; {Module Searching in General}
2221 ;;; We sometimes want to look for properties of a symbol
2222 ;;; just within the obarray of one module. If the property
2223 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
2224 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
2227 ;;; Other times, we want to test for a symbol property in the obarray
2228 ;;; of M and, if it is not found there, try each of the modules in the
2229 ;;; uses list of M. This is the normal way of testing for some
2230 ;;; property, so we state these properties without qualification as
2231 ;;; in: ``The symbol 'fnord is interned in module M because it is
2232 ;;; interned locally in module M2 which is a member of the uses list
2236 ;; module-search fn m
2238 ;; return the first non-#f result of FN applied to M and then to
2239 ;; the modules in the uses of m, and so on recursively. If all applications
2240 ;; return #f, then so does this function.
2242 (define (module-search fn m v)
2245 (or (module-search fn (car pos) v)
2248 (loop (module-uses m))))
2251 ;;; {Is a symbol bound in a module?}
2253 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
2254 ;;; of S in M has been set to some well-defined value.
2257 ;; module-locally-bound? module symbol
2259 ;; Is a symbol bound (interned and defined) locally in a given module?
2261 (define (module-locally-bound? m v)
2262 (let ((var (module-local-variable m v)))
2264 (variable-bound? var))))
2266 ;; module-bound? module symbol
2268 ;; Is a symbol bound (interned and defined) anywhere in a given module
2271 (define (module-bound? m v)
2272 (let ((var (module-variable m v)))
2274 (variable-bound? var))))
2276 ;;; {Is a symbol interned in a module?}
2278 ;;; Symbol S in Module M is interned if S occurs in
2279 ;;; of S in M has been set to some well-defined value.
2281 ;;; It is possible to intern a symbol in a module without providing
2282 ;;; an initial binding for the corresponding variable. This is done
2284 ;;; (module-add! module symbol (make-undefined-variable))
2286 ;;; In that case, the symbol is interned in the module, but not
2287 ;;; bound there. The unbound symbol shadows any binding for that
2288 ;;; symbol that might otherwise be inherited from a member of the uses list.
2291 (define (module-obarray-get-handle ob key)
2292 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
2294 (define (module-obarray-ref ob key)
2295 ((if (symbol? key) hashq-ref hash-ref) ob key))
2297 (define (module-obarray-set! ob key val)
2298 ((if (symbol? key) hashq-set! hash-set!) ob key val))
2300 (define (module-obarray-remove! ob key)
2301 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
2303 ;; module-symbol-locally-interned? module symbol
2305 ;; is a symbol interned (not neccessarily defined) locally in a given module
2306 ;; or its uses? Interned symbols shadow inherited bindings even if
2307 ;; they are not themselves bound to a defined value.
2309 (define (module-symbol-locally-interned? m v)
2310 (not (not (module-obarray-get-handle (module-obarray m) v))))
2312 ;; module-symbol-interned? module symbol
2314 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
2315 ;; or its uses? Interned symbols shadow inherited bindings even if
2316 ;; they are not themselves bound to a defined value.
2318 (define (module-symbol-interned? m v)
2319 (module-search module-symbol-locally-interned? m v))
2322 ;;; {Mapping modules x symbols --> variables}
2325 ;; module-local-variable module symbol
2326 ;; return the local variable associated with a MODULE and SYMBOL.
2328 ;;; This function is very important. It is the only function that can
2329 ;;; return a variable from a module other than the mutators that store
2330 ;;; new variables in modules. Therefore, this function is the location
2331 ;;; of the "lazy binder" hack.
2333 ;;; If symbol is defined in MODULE, and if the definition binds symbol
2334 ;;; to a variable, return that variable object.
2336 ;;; If the symbols is not found at first, but the module has a lazy binder,
2337 ;;; then try the binder.
2339 ;;; If the symbol is not found at all, return #f.
2341 ;;; (This is now written in C, see `modules.c'.)
2344 ;;; {Mapping modules x symbols --> bindings}
2346 ;;; These are similar to the mapping to variables, except that the
2347 ;;; variable is dereferenced.
2350 ;; module-symbol-binding module symbol opt-value
2352 ;; return the binding of a variable specified by name within
2353 ;; a given module, signalling an error if the variable is unbound.
2354 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2355 ;; return OPT-VALUE.
2357 (define (module-symbol-local-binding m v . opt-val)
2358 (let ((var (module-local-variable m v)))
2359 (if (and var (variable-bound? var))
2361 (if (not (null? opt-val))
2363 (error "Locally unbound variable." v)))))
2365 ;; module-symbol-binding module symbol opt-value
2367 ;; return the binding of a variable specified by name within
2368 ;; a given module, signalling an error if the variable is unbound.
2369 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2370 ;; return OPT-VALUE.
2372 (define (module-symbol-binding m v . opt-val)
2373 (let ((var (module-variable m v)))
2374 (if (and var (variable-bound? var))
2376 (if (not (null? opt-val))
2378 (error "Unbound variable." v)))))
2383 ;;; {Adding Variables to Modules}
2386 ;; module-make-local-var! module symbol
2388 ;; ensure a variable for V in the local namespace of M.
2389 ;; If no variable was already there, then create a new and uninitialzied
2392 ;; This function is used in modules.c.
2394 (define (module-make-local-var! m v)
2395 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2398 ;; Mark as modified since this function is called when
2399 ;; the standard eval closure defines a binding
2403 ;; Create a new local variable.
2404 (let ((local-var (make-undefined-variable)))
2405 (module-add! m v local-var)
2408 ;; module-ensure-local-variable! module symbol
2410 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2411 ;; there is no binding for SYMBOL, create a new uninitialized
2412 ;; variable. Return the local variable.
2414 (define (module-ensure-local-variable! module symbol)
2415 (or (module-local-variable module symbol)
2416 (let ((var (make-undefined-variable)))
2417 (module-add! module symbol var)
2420 ;; module-add! module symbol var
2422 ;; ensure a particular variable for V in the local namespace of M.
2424 (define (module-add! m v var)
2425 (if (not (variable? var))
2426 (error "Bad variable to module-add!" var))
2427 (module-obarray-set! (module-obarray m) v var)
2428 (module-modified m))
2432 ;; make sure that a symbol is undefined in the local namespace of M.
2434 (define (module-remove! m v)
2435 (module-obarray-remove! (module-obarray m) v)
2436 (module-modified m))
2438 (define (module-clear! m)
2439 (hash-clear! (module-obarray m))
2440 (module-modified m))
2442 ;; MODULE-FOR-EACH -- exported
2444 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2446 (define (module-for-each proc module)
2447 (hash-for-each proc (module-obarray module)))
2449 (define (module-map proc module)
2450 (hash-map->list proc (module-obarray module)))
2454 ;; Modules exist in a separate namespace from values, because you generally do
2455 ;; not want the name of a submodule, which you might not even use, to collide
2456 ;; with local variables that happen to be named the same as the submodule.
2458 (define (module-ref-submodule module name)
2459 (or (hashq-ref (module-submodules module) name)
2460 (and (module-submodule-binder module)
2461 ((module-submodule-binder module) module name))))
2463 (define (module-define-submodule! module name submodule)
2464 (hashq-set! (module-submodules module) name submodule))
2468 ;;; {Module-based Loading}
2471 (define (save-module-excursion thunk)
2472 (let ((inner-module (current-module))
2474 (dynamic-wind (lambda ()
2475 (set! outer-module (current-module))
2476 (set-current-module inner-module)
2477 (set! inner-module #f))
2480 (set! inner-module (current-module))
2481 (set-current-module outer-module)
2482 (set! outer-module #f)))))
2486 ;;; {MODULE-REF -- exported}
2489 ;; Returns the value of a variable called NAME in MODULE or any of its
2490 ;; used modules. If there is no such variable, then if the optional third
2491 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2493 (define (module-ref module name . rest)
2494 (let ((variable (module-variable module name)))
2495 (if (and variable (variable-bound? variable))
2496 (variable-ref variable)
2498 (error "No variable named" name 'in module)
2499 (car rest) ; default value
2502 ;; MODULE-SET! -- exported
2504 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2505 ;; to VALUE; if there is no such variable, an error is signaled.
2507 (define (module-set! module name value)
2508 (let ((variable (module-variable module name)))
2510 (variable-set! variable value)
2511 (error "No variable named" name 'in module))))
2513 ;; MODULE-DEFINE! -- exported
2515 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2516 ;; variable, it is added first.
2518 (define (module-define! module name value)
2519 (let ((variable (module-local-variable module name)))
2522 (variable-set! variable value)
2523 (module-modified module))
2524 (let ((variable (make-variable value)))
2525 (module-add! module name variable)))))
2527 ;; MODULE-DEFINED? -- exported
2529 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2532 (define (module-defined? module name)
2533 (let ((variable (module-variable module name)))
2534 (and variable (variable-bound? variable))))
2536 ;; MODULE-USE! module interface
2538 ;; Add INTERFACE to the list of interfaces used by MODULE.
2540 (define (module-use! module interface)
2541 (if (not (or (eq? module interface)
2542 (memq interface (module-uses module))))
2544 ;; Newly used modules must be appended rather than consed, so that
2545 ;; `module-variable' traverses the use list starting from the first
2547 (set-module-uses! module (append (module-uses module)
2549 (hash-clear! (module-import-obarray module))
2550 (module-modified module))))
2552 ;; MODULE-USE-INTERFACES! module interfaces
2554 ;; Same as MODULE-USE!, but only notifies module observers after all
2555 ;; interfaces are added to the inports list.
2557 (define (module-use-interfaces! module interfaces)
2558 (let* ((cur (module-uses module))
2559 (new (let lp ((in interfaces) (out '()))
2563 (let ((iface (car in)))
2564 (if (or (memq iface cur) (memq iface out))
2566 (cons iface out))))))))
2567 (set-module-uses! module (append cur new))
2568 (hash-clear! (module-import-obarray module))
2569 (module-modified module)))
2573 ;;; {Recursive Namespaces}
2575 ;;; A hierarchical namespace emerges if we consider some module to be
2576 ;;; root, and submodules of that module to be nested namespaces.
2578 ;;; The routines here manage variable names in hierarchical namespace.
2579 ;;; Each variable name is a list of elements, looked up in successively nested
2582 ;;; (nested-ref some-root-module '(foo bar baz))
2583 ;;; => <value of a variable named baz in the submodule bar of
2584 ;;; the submodule foo of some-root-module>
2589 ;;; ;; a-root is a module
2590 ;;; ;; name is a list of symbols
2592 ;;; nested-ref a-root name
2593 ;;; nested-set! a-root name val
2594 ;;; nested-define! a-root name val
2595 ;;; nested-remove! a-root name
2597 ;;; These functions manipulate values in namespaces. For referencing the
2598 ;;; namespaces themselves, use the following:
2600 ;;; nested-ref-module a-root name
2601 ;;; nested-define-module! a-root name mod
2603 ;;; (current-module) is a natural choice for a root so for convenience there are
2606 ;;; local-ref name == nested-ref (current-module) name
2607 ;;; local-set! name val == nested-set! (current-module) name val
2608 ;;; local-define name val == nested-define! (current-module) name val
2609 ;;; local-remove name == nested-remove! (current-module) name
2610 ;;; local-ref-module name == nested-ref-module (current-module) name
2611 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2615 (define (nested-ref root names)
2618 (let loop ((cur root)
2622 (module-ref cur head #f)
2623 (let ((cur (module-ref-submodule cur head)))
2625 (loop cur (car tail) (cdr tail))))))))
2627 (define (nested-set! root names val)
2628 (let loop ((cur root)
2632 (module-set! cur head val)
2633 (let ((cur (module-ref-submodule cur head)))
2635 (error "failed to resolve module" names)
2636 (loop cur (car tail) (cdr tail)))))))
2638 (define (nested-define! root names val)
2639 (let loop ((cur root)
2643 (module-define! cur head val)
2644 (let ((cur (module-ref-submodule cur head)))
2646 (error "failed to resolve module" names)
2647 (loop cur (car tail) (cdr tail)))))))
2649 (define (nested-remove! root names)
2650 (let loop ((cur root)
2654 (module-remove! cur head)
2655 (let ((cur (module-ref-submodule cur head)))
2657 (error "failed to resolve module" names)
2658 (loop cur (car tail) (cdr tail)))))))
2661 (define (nested-ref-module root names)
2662 (let loop ((cur root)
2666 (let ((cur (module-ref-submodule cur (car names))))
2668 (loop cur (cdr names)))))))
2670 (define (nested-define-module! root names module)
2672 (error "can't redefine root module" root module)
2673 (let loop ((cur root)
2677 (module-define-submodule! cur head module)
2678 (let ((cur (or (module-ref-submodule cur head)
2679 (let ((m (make-module 31)))
2680 (set-module-kind! m 'directory)
2681 (set-module-name! m (append (module-name cur)
2683 (module-define-submodule! cur head m)
2685 (loop cur (car tail) (cdr tail)))))))
2688 (define (local-ref names)
2689 (nested-ref (current-module) names))
2691 (define (local-set! names val)
2692 (nested-set! (current-module) names val))
2694 (define (local-define names val)
2695 (nested-define! (current-module) names val))
2697 (define (local-remove names)
2698 (nested-remove! (current-module) names))
2700 (define (local-ref-module names)
2701 (nested-ref-module (current-module) names))
2703 (define (local-define-module names mod)
2704 (nested-define-module! (current-module) names mod))
2710 ;;; {The (guile) module}
2712 ;;; The standard module, which has the core Guile bindings. Also called the
2713 ;;; "root module", as it is imported by many other modules, but it is not
2714 ;;; necessarily the root of anything; and indeed, the module named '() might be
2715 ;;; better thought of as a root.
2718 (define (set-system-module! m s)
2719 (set-procedure-property! (module-eval-closure m) 'system-module s))
2721 ;; The root module uses the pre-modules-obarray as its obarray. This
2722 ;; special obarray accumulates all bindings that have been established
2723 ;; before the module system is fully booted.
2725 ;; (The obarray continues to be used by code that has been closed over
2726 ;; before the module system has been booted.)
2728 (define the-root-module
2729 (let ((m (make-module 0)))
2730 (set-module-obarray! m (%get-pre-modules-obarray))
2731 (set-module-name! m '(guile))
2732 (set-system-module! m #t)
2735 ;; The root interface is a module that uses the same obarray as the
2736 ;; root module. It does not allow new definitions, tho.
2738 (define the-scm-module
2739 (let ((m (make-module 0)))
2740 (set-module-obarray! m (%get-pre-modules-obarray))
2741 (set-module-eval-closure! m (standard-interface-eval-closure m))
2742 (set-module-name! m '(guile))
2743 (set-module-kind! m 'interface)
2744 (set-system-module! m #t)
2746 ;; In Guile 1.8 and earlier M was its own public interface.
2747 (set-module-public-interface! m m)
2751 (set-module-public-interface! the-root-module the-scm-module)
2755 ;; Now that we have a root module, even though modules aren't fully booted,
2756 ;; expand the definition of resolve-module.
2758 (define (resolve-module name . args)
2759 (if (equal? name '(guile))
2761 (error "unexpected module to resolve during module boot" name)))
2763 ;; Cheat. These bindings are needed by modules.c, but we don't want
2764 ;; to move their real definition here because that would be unnatural.
2766 (define define-module* #f)
2767 (define process-use-modules #f)
2768 (define module-export! #f)
2769 (define default-duplicate-binding-procedures #f)
2771 ;; This boots the module system. All bindings needed by modules.c
2772 ;; must have been defined by now.
2774 (set-current-module the-root-module)
2779 ;; Now that modules are booted, give module-name its final definition.
2782 (let ((accessor (record-accessor module-type 'name)))
2785 (let ((name (list (gensym))))
2786 ;; Name MOD and bind it in the module root so that it's visible to
2787 ;; `resolve-module'. This is important as `psyntax' stores module
2788 ;; names and relies on being able to `resolve-module' them.
2789 (set-module-name! mod name)
2790 (nested-define-module! (resolve-module '() #f) name mod)
2793 (define (make-modules-in module name)
2794 (or (nested-ref-module module name)
2795 (let ((m (make-module 31)))
2796 (set-module-kind! m 'directory)
2797 (set-module-name! m (append (module-name module) name))
2798 (nested-define-module! module name m)
2801 (define (beautify-user-module! module)
2802 (let ((interface (module-public-interface module)))
2803 (if (or (not interface)
2804 (eq? interface module))
2805 (let ((interface (make-module 31)))
2806 (set-module-name! interface (module-name module))
2807 (set-module-version! interface (module-version module))
2808 (set-module-kind! interface 'interface)
2809 (set-module-public-interface! module interface))))
2810 (if (and (not (memq the-scm-module (module-uses module)))
2811 (not (eq? module the-root-module)))
2812 ;; Import the default set of bindings (from the SCM module) in MODULE.
2813 (module-use! module the-scm-module)))
2815 (define (version-matches? version-ref target)
2816 (define (sub-versions-match? v-refs t)
2817 (define (sub-version-matches? v-ref t)
2818 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2820 ((number? v-ref) (eqv? v-ref t))
2823 ((>=) (>= t (cadr v-ref)))
2824 ((<=) (<= t (cadr v-ref)))
2825 ((and) (and-map matches? (cdr v-ref)))
2826 ((or) (or-map matches? (cdr v-ref)))
2827 ((not) (not (matches? (cadr v-ref))))
2828 (else (error "Invalid sub-version reference" v-ref))))
2829 (else (error "Invalid sub-version reference" v-ref)))))
2831 (and (not (null? t))
2832 (sub-version-matches? (car v-refs) (car t))
2833 (sub-versions-match? (cdr v-refs) (cdr t)))))
2835 (let ((matches? (lambda (v) (version-matches? v target))))
2836 (or (null? version-ref)
2837 (case (car version-ref)
2838 ((and) (and-map matches? (cdr version-ref)))
2839 ((or) (or-map matches? (cdr version-ref)))
2840 ((not) (not (matches? (cadr version-ref))))
2841 (else (sub-versions-match? version-ref target))))))
2843 (define (make-fresh-user-module)
2844 (let ((m (make-module)))
2845 (beautify-user-module! m)
2848 ;; NOTE: This binding is used in libguile/modules.c.
2850 (define resolve-module
2851 (let ((root (make-module)))
2852 (set-module-name! root '())
2853 ;; Define the-root-module as '(guile).
2854 (module-define-submodule! root 'guile the-root-module)
2856 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2857 (let ((already (nested-ref-module root name)))
2860 (or (not autoload) (module-public-interface already)))
2861 ;; A hit, a palpable hit.
2863 (not (version-matches? version (module-version already))))
2864 (error "incompatible module version already loaded" name))
2867 ;; Try to autoload the module, and recurse.
2868 (try-load-module name version)
2869 (resolve-module name #f #:ensure ensure))
2871 ;; No module found (or if one was, it had no public interface), and
2872 ;; we're not autoloading. Make an empty module if #:ensure is true.
2875 (make-modules-in root name)))))))))
2878 (define (try-load-module name version)
2879 (try-module-autoload name version))
2881 (define (reload-module m)
2882 "Revisit the source file corresponding to the module @var{m}."
2883 (let ((f (module-filename m)))
2885 (save-module-excursion
2887 ;; Re-set the initial environment, as in try-module-autoload.
2888 (set-current-module (make-fresh-user-module))
2889 (primitive-load-path f)
2891 ;; Though we could guess, we *should* know it.
2892 (error "unknown file name for module" m))))
2894 (define (purify-module! module)
2895 "Removes bindings in MODULE which are inherited from the (guile) module."
2896 (let ((use-list (module-uses module)))
2897 (if (and (pair? use-list)
2898 (eq? (car (last-pair use-list)) the-scm-module))
2899 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2901 ;; Return a module that is an interface to the module designated by
2904 ;; `resolve-interface' takes four keyword arguments:
2906 ;; #:select SELECTION
2908 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2909 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2910 ;; is the name in the used module and SEEN is the name in the using
2911 ;; module. Note that SEEN is also passed through RENAMER, below. The
2912 ;; default is to select all bindings. If you specify no selection but
2913 ;; a renamer, only the bindings that already exist in the used module
2914 ;; are made available in the interface. Bindings that are added later
2915 ;; are not picked up.
2919 ;; BINDINGS is a list of bindings which should not be imported.
2923 ;; PREFIX is a symbol that will be appended to each exported name.
2924 ;; The default is to not perform any renaming.
2926 ;; #:renamer RENAMER
2928 ;; RENAMER is a procedure that takes a symbol and returns its new
2929 ;; name. The default is not perform any renaming.
2931 ;; Signal "no code for module" error if module name is not resolvable
2932 ;; or its public interface is not available. Signal "no binding"
2933 ;; error if selected binding does not exist in the used module.
2935 (define* (resolve-interface name #:key
2940 (symbol-prefix-proc prefix)
2943 (let* ((module (resolve-module name #t version #:ensure #f))
2944 (public-i (and module (module-public-interface module))))
2945 (and (or (not module) (not public-i))
2946 (error "no code for module" name))
2947 (if (and (not select) (null? hide) (eq? renamer identity))
2949 (let ((selection (or select (module-map (lambda (sym var) sym)
2951 (custom-i (make-module 31)))
2952 (set-module-kind! custom-i 'custom-interface)
2953 (set-module-name! custom-i name)
2954 ;; XXX - should use a lazy binder so that changes to the
2955 ;; used module are picked up automatically.
2956 (for-each (lambda (bspec)
2957 (let* ((direct? (symbol? bspec))
2958 (orig (if direct? bspec (car bspec)))
2959 (seen (if direct? bspec (cdr bspec)))
2960 (var (or (module-local-variable public-i orig)
2961 (module-local-variable module orig)
2963 ;; fixme: format manually for now
2965 #f "no binding `~A' in module ~A"
2967 (if (memq orig hide)
2968 (set! hide (delq! orig hide))
2969 (module-add! custom-i
2973 ;; Check that we are not hiding bindings which don't exist
2974 (for-each (lambda (binding)
2975 (if (not (module-local-variable public-i binding))
2978 #f "no binding `~A' to hide in module ~A"
2983 (define (symbol-prefix-proc prefix)
2985 (symbol-append prefix symbol)))
2987 ;; This function is called from "modules.c". If you change it, be
2988 ;; sure to update "modules.c" as well.
2990 (define* (define-module* name
2991 #:key filename pure version (duplicates '())
2992 (imports '()) (exports '()) (replacements '())
2993 (re-exports '()) (autoloads '()) transformer)
2994 (define (list-of pred l)
2996 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2997 (define (valid-export? x)
2998 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2999 (define (valid-autoload? x)
3000 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
3002 (define (resolve-imports imports)
3003 (define (resolve-import import-spec)
3004 (if (list? import-spec)
3005 (apply resolve-interface import-spec)
3006 (error "unexpected use-module specification" import-spec)))
3007 (let lp ((imports imports) (out '()))
3009 ((null? imports) (reverse! out))
3012 (cons (resolve-import (car imports)) out)))
3013 (else (error "unexpected tail of imports list" imports)))))
3015 ;; We could add a #:no-check arg, set by the define-module macro, if
3016 ;; these checks are taking too much time.
3018 (let ((module (resolve-module name #f)))
3019 (beautify-user-module! module)
3021 (set-module-filename! module filename))
3023 (purify-module! module))
3026 (if (not (list-of integer? version))
3027 (error "expected list of integers for version"))
3028 (set-module-version! module version)
3029 (set-module-version! (module-public-interface module) version)))
3030 (let ((imports (resolve-imports imports)))
3031 (call-with-deferred-observers
3034 (module-use-interfaces! module imports))
3035 (if (list-of valid-export? exports)
3037 (module-export! module exports))
3038 (error "expected exports to be a list of symbols or symbol pairs"))
3039 (if (list-of valid-export? replacements)
3040 (if (pair? replacements)
3041 (module-replace! module replacements))
3042 (error "expected replacements to be a list of symbols or symbol pairs"))
3043 (if (list-of valid-export? re-exports)
3044 (if (pair? re-exports)
3045 (module-re-export! module re-exports))
3046 (error "expected re-exports to be a list of symbols or symbol pairs"))
3048 (if (not (null? autoloads))
3049 (apply module-autoload! module autoloads))
3050 ;; Wait until modules have been loaded to resolve duplicates
3052 (if (pair? duplicates)
3053 (let ((handlers (lookup-duplicates-handlers duplicates)))
3054 (set-module-duplicates-handlers! module handlers))))))
3057 (if (and (pair? transformer) (list-of symbol? transformer))
3058 (let ((iface (resolve-interface transformer))
3059 (sym (car (last-pair transformer))))
3060 (set-module-transformer! module (module-ref iface sym)))
3061 (error "expected transformer to be a module name" transformer)))
3063 (run-hook module-defined-hook module)
3066 ;; `module-defined-hook' is a hook that is run whenever a new module
3067 ;; is defined. Its members are called with one argument, the new
3069 (define module-defined-hook (make-hook 1))
3076 (define (make-autoload-interface module name bindings)
3077 (let ((b (lambda (a sym definep)
3078 (and (memq sym bindings)
3079 (let ((i (module-public-interface (resolve-module name))))
3081 (error "missing interface for module" name))
3082 (let ((autoload (memq a (module-uses module))))
3083 ;; Replace autoload-interface with actual interface if
3084 ;; that has not happened yet.
3085 (if (pair? autoload)
3086 (set-car! autoload i)))
3087 (module-local-variable i sym))))))
3088 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
3089 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
3090 (make-hash-table 0) #f #f #f)))
3092 (define (module-autoload! module . args)
3093 "Have @var{module} automatically load the module named @var{name} when one
3094 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
3095 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
3096 module '(ice-9 q) '(make-q q-length))}."
3097 (let loop ((args args))
3101 (error "invalid name+binding autoload list" args))
3103 (let ((name (car args))
3104 (bindings (cadr args)))
3105 (module-use! module (make-autoload-interface module
3107 (loop (cddr args)))))))
3112 ;;; {Autoloading modules}
3115 (define autoloads-in-progress '())
3117 ;; This function is called from "modules.c". If you change it, be
3118 ;; sure to update "modules.c" as well.
3120 (define* (try-module-autoload module-name #:optional version)
3121 (let* ((reverse-name (reverse module-name))
3122 (name (symbol->string (car reverse-name)))
3123 (dir-hint-module-name (reverse (cdr reverse-name)))
3124 (dir-hint (apply string-append
3126 (string-append (symbol->string elt) "/"))
3127 dir-hint-module-name))))
3128 (resolve-module dir-hint-module-name #f)
3129 (and (not (autoload-done-or-in-progress? dir-hint name))
3132 (lambda () (autoload-in-progress! dir-hint name))
3134 (with-fluids ((current-reader #f))
3135 (save-module-excursion
3137 ;; The initial environment when loading a module is a fresh
3139 (set-current-module (make-fresh-user-module))
3140 ;; Here we could allow some other search strategy (other than
3141 ;; primitive-load-path), for example using versions encoded
3142 ;; into the file system -- but then we would have to figure
3143 ;; out how to locate the compiled file, do auto-compilation,
3144 ;; etc. Punt for now, and don't use versions when locating
3146 (primitive-load-path (in-vicinity dir-hint name) #f)
3148 (lambda () (set-autoloaded! dir-hint name didit)))
3153 ;;; {Dynamic linking of modules}
3156 (define autoloads-done '((guile . guile)))
3158 (define (autoload-done-or-in-progress? p m)
3159 (let ((n (cons p m)))
3160 (->bool (or (member n autoloads-done)
3161 (member n autoloads-in-progress)))))
3163 (define (autoload-done! p m)
3164 (let ((n (cons p m)))
3165 (set! autoloads-in-progress
3166 (delete! n autoloads-in-progress))
3167 (or (member n autoloads-done)
3168 (set! autoloads-done (cons n autoloads-done)))))
3170 (define (autoload-in-progress! p m)
3171 (let ((n (cons p m)))
3172 (set! autoloads-done
3173 (delete! n autoloads-done))
3174 (set! autoloads-in-progress (cons n autoloads-in-progress))))
3176 (define (set-autoloaded! p m done?)
3178 (autoload-done! p m)
3179 (let ((n (cons p m)))
3180 (set! autoloads-done (delete! n autoloads-done))
3181 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
3185 ;;; {Run-time options}
3188 (define-syntax define-option-interface
3190 ((_ (interface (options enable disable) (option-set!)))
3197 (begin (interface arg) (interface))
3200 (apply (lambda (name value documentation)
3202 (if (< (string-length (symbol->string name)) 8)
3207 (display documentation)
3211 (define (enable . flags)
3212 (interface (append flags (interface)))
3214 (define (disable . flags)
3215 (let ((options (interface)))
3216 (for-each (lambda (flag) (set! options (delq! flag options)))
3220 (define-syntax-rule (option-set! opt val)
3221 (eval-when (eval load compile expand)
3222 (options (append (options) (list 'opt val)))))))))
3224 (define-option-interface
3225 (debug-options-interface
3226 (debug-options debug-enable debug-disable)
3229 (define-option-interface
3230 (read-options-interface
3231 (read-options read-enable read-disable)
3234 (define-option-interface
3235 (print-options-interface
3236 (print-options print-enable print-disable)
3241 ;;; {The Unspecified Value}
3243 ;;; Currently Guile represents unspecified values via one particular value,
3244 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
3245 ;;; future if we could replace this with a return of 0 values, though.
3248 (define-syntax *unspecified*
3249 (identifier-syntax (if #f #f)))
3251 (define (unspecified? v) (eq? v *unspecified*))
3259 (define *repl-stack* (make-fluid '()))
3261 ;; Programs can call `batch-mode?' to see if they are running as part of a
3262 ;; script or if they are running interactively. REPL implementations ensure that
3263 ;; `batch-mode?' returns #f during their extent.
3265 (define (batch-mode?)
3266 (null? (fluid-ref *repl-stack*)))
3268 ;; Programs can re-enter batch mode, for example after a fork, by calling
3269 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3270 ;; to abort to the outermost prompt, and call a thunk there.
3272 (define (ensure-batch-mode!)
3273 (set! batch-mode? (lambda () #t)))
3275 (define (quit . args)
3276 (apply throw 'quit args))
3280 (define (gc-run-time)
3281 (cdr (assq 'gc-time-taken (gc-stats))))
3283 (define abort-hook (make-hook))
3284 (define before-error-hook (make-hook))
3285 (define after-error-hook (make-hook))
3286 (define before-backtrace-hook (make-hook))
3287 (define after-backtrace-hook (make-hook))
3289 (define before-read-hook (make-hook))
3290 (define after-read-hook (make-hook))
3291 (define before-eval-hook (make-hook 1))
3292 (define after-eval-hook (make-hook 1))
3293 (define before-print-hook (make-hook 1))
3294 (define after-print-hook (make-hook 1))
3296 ;;; This hook is run at the very end of an interactive session.
3298 (define exit-hook (make-hook))
3300 ;;; The default repl-reader function. We may override this if we've
3301 ;;; the readline library.
3303 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3304 (if (not (char-ready?))
3306 (display (if (string? prompt) prompt (prompt)))
3307 ;; An interesting situation. The printer resets the column to
3308 ;; 0 by printing a newline, but we then advance it by printing
3309 ;; the prompt. However the port-column of the output port
3310 ;; does not typically correspond with the actual column on the
3311 ;; screen, because the input is echoed back! Since the
3312 ;; input is line-buffered and thus ends with a newline, the
3313 ;; output will really start on column zero. So, here we zero
3314 ;; it out. See bug 9664.
3316 ;; Note that for similar reasons, the output-line will not
3317 ;; reflect the actual line on the screen. But given the
3318 ;; possibility of multiline input, the fix is not as
3319 ;; straightforward, so we don't bother.
3321 ;; Also note that the readline implementation papers over
3322 ;; these concerns, because it's readline itself printing the
3323 ;; prompt, and not Guile.
3324 (set-port-column! (current-output-port) 0)))
3326 (run-hook before-read-hook)
3327 ((or reader read) (current-input-port))))
3332 ;;; {IOTA functions: generating lists of numbers}
3336 (let loop ((count (1- n)) (result '()))
3337 (if (< count 0) result
3338 (loop (1- count) (cons count result)))))
3344 ;;; with `continue' and `break'.
3347 ;; The inliner will remove the prompts at compile-time if it finds that
3348 ;; `continue' or `break' are not used.
3350 (define-syntax while
3353 ((while cond body ...)
3354 #`(let ((break-tag (make-prompt-tag "break"))
3355 (continue-tag (make-prompt-tag "continue")))
3359 (define-syntax #,(datum->syntax #'while 'break)
3363 #'(abort-to-prompt break-tag arg (... ...)))
3366 (apply abort-to-prompt break-tag args))))))
3371 (define-syntax #,(datum->syntax #'while 'continue)
3375 #'(abort-to-prompt continue-tag))
3377 (syntax-violation 'continue "too many arguments" x))
3380 (abort-to-prompt continue-tag))))))
3381 (do () ((not cond) #f) body ...))
3382 (lambda (k) (lp)))))
3386 (apply values args)))))))))
3391 ;;; {Module System Macros}
3394 ;; Return a list of expressions that evaluate to the appropriate
3395 ;; arguments for resolve-interface according to SPEC.
3397 (eval-when (compile)
3398 (if (memq 'prefix (read-options))
3399 (error "boot-9 must be compiled with #:kw, not :kw")))
3401 (define (keyword-like-symbol->keyword sym)
3402 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3404 (define-syntax define-module
3406 (define (keyword-like? stx)
3407 (let ((dat (syntax->datum stx)))
3409 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3410 (define (->keyword sym)
3411 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3413 (define (parse-iface args)
3414 (let loop ((in args) (out '()))
3417 ;; The user wanted #:foo, but wrote :foo. Fix it.
3418 ((sym . in) (keyword-like? #'sym)
3419 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3420 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3421 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3422 ((#:renamer renamer . in)
3423 (loop #'in (cons* #',renamer #:renamer out)))
3425 (loop #'in (cons* #'val #'kw out))))))
3427 (define (parse args imp exp rex rep aut)
3428 ;; Just quote everything except #:use-module and #:use-syntax. We
3429 ;; need to know about all arguments regardless since we want to turn
3430 ;; symbols that look like keywords into real keywords, and the
3431 ;; keyword args in a define-module form are not regular
3432 ;; (i.e. no-backtrace doesn't take a value).
3433 (syntax-case args ()
3435 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3436 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3437 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3438 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3439 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3440 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3441 ;; The user wanted #:foo, but wrote :foo. Fix it.
3442 ((sym . args) (keyword-like? #'sym)
3443 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3444 imp exp rex rep aut))
3445 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3446 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3447 ((#:no-backtrace . args)
3449 (parse #'args imp exp rex rep aut))
3451 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3453 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3454 ((#:version (v ...) . args)
3455 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3456 ((#:duplicates (d ...) . args)
3457 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3458 ((#:filename f . args)
3459 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3460 ((#:use-module (name name* ...) . args)
3461 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3462 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3463 ((#:use-syntax (name name* ...) . args)
3464 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3465 #`(#:transformer '(name name* ...)
3466 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3467 ((#:use-module ((name name* ...) arg ...) . args)
3468 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3470 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3472 ((#:export (ex ...) . args)
3473 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3474 ((#:export-syntax (ex ...) . args)
3475 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3476 ((#:re-export (re ...) . args)
3477 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3478 ((#:re-export-syntax (re ...) . args)
3479 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3480 ((#:replace (r ...) . args)
3481 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3482 ((#:replace-syntax (r ...) . args)
3483 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3484 ((#:autoload name bindings . args)
3485 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3487 (syntax-violation 'define-module "unknown keyword or bad argument"
3491 ((_ (name name* ...) arg ...)
3492 (and-map symbol? (syntax->datum #'(name name* ...)))
3493 (with-syntax (((quoted-arg ...)
3494 (parse #'(arg ...) '() '() '() '() '()))
3495 ;; Ideally the filename is either a string or #f;
3496 ;; this hack is to work around a case in which
3497 ;; port-filename returns a symbol (`socket') for
3499 (filename (let ((f (assq-ref (or (syntax-source x) '())
3501 (and (string? f) f))))
3502 #'(eval-when (eval load compile expand)
3503 (let ((m (define-module* '(name name* ...)
3504 #:filename filename quoted-arg ...)))
3505 (set-current-module m)
3508 ;; The guts of the use-modules macro. Add the interfaces of the named
3509 ;; modules to the use-list of the current module, in order.
3511 ;; This function is called by "modules.c". If you change it, be sure
3512 ;; to change scm_c_use_module as well.
3514 (define (process-use-modules module-interface-args)
3515 (let ((interfaces (map (lambda (mif-args)
3516 (or (apply resolve-interface mif-args)
3517 (error "no such module" mif-args)))
3518 module-interface-args)))
3519 (call-with-deferred-observers
3521 (module-use-interfaces! (current-module) interfaces)))))
3523 (define-syntax use-modules
3525 (define (keyword-like? stx)
3526 (let ((dat (syntax->datum stx)))
3528 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3529 (define (->keyword sym)
3530 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3532 (define (quotify-iface args)
3533 (let loop ((in args) (out '()))
3536 ;; The user wanted #:foo, but wrote :foo. Fix it.
3537 ((sym . in) (keyword-like? #'sym)
3538 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3539 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3540 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3541 ((#:renamer renamer . in)
3542 (loop #'in (cons* #'renamer #:renamer out)))
3544 (loop #'in (cons* #''val #'kw out))))))
3546 (define (quotify specs)
3547 (let lp ((in specs) (out '()))
3550 (((name name* ...) . in)
3551 (and-map symbol? (syntax->datum #'(name name* ...)))
3552 (lp #'in (cons #''((name name* ...)) out)))
3553 ((((name name* ...) arg ...) . in)
3554 (and-map symbol? (syntax->datum #'(name name* ...)))
3555 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3556 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3561 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3562 #'(eval-when (eval load compile expand)
3563 (process-use-modules (list quoted-args ...))
3566 (include-from-path "ice-9/r6rs-libraries")
3568 (define-syntax-rule (define-private foo bar)
3571 (define-syntax define-public
3573 ((_ (name . args) . body)
3574 (define-public name (lambda args . body)))
3580 (define-syntax-rule (defmacro-public name args body ...)
3582 (defmacro name args body ...)
3583 (export-syntax name)))
3585 ;; And now for the most important macro.
3586 (define-syntax-rule (λ formals body ...)
3587 (lambda formals body ...))
3590 ;; Export a local variable
3592 ;; This function is called from "modules.c". If you change it, be
3593 ;; sure to update "modules.c" as well.
3595 (define (module-export! m names)
3596 (let ((public-i (module-public-interface m)))
3597 (for-each (lambda (name)
3598 (let* ((internal-name (if (pair? name) (car name) name))
3599 (external-name (if (pair? name) (cdr name) name))
3600 (var (module-ensure-local-variable! m internal-name)))
3601 (module-add! public-i external-name var)))
3604 (define (module-replace! m names)
3605 (let ((public-i (module-public-interface m)))
3606 (for-each (lambda (name)
3607 (let* ((internal-name (if (pair? name) (car name) name))
3608 (external-name (if (pair? name) (cdr name) name))
3609 (var (module-ensure-local-variable! m internal-name)))
3610 ;; FIXME: use a bit on variables instead of object
3612 (set-object-property! var 'replace #t)
3613 (module-add! public-i external-name var)))
3616 ;; Export all local variables from a module
3618 (define (module-export-all! mod)
3619 (define (fresh-interface!)
3620 (let ((iface (make-module)))
3621 (set-module-name! iface (module-name mod))
3622 (set-module-version! iface (module-version mod))
3623 (set-module-kind! iface 'interface)
3624 (set-module-public-interface! mod iface)
3626 (let ((iface (or (module-public-interface mod)
3627 (fresh-interface!))))
3628 (set-module-obarray! iface (module-obarray mod))))
3630 ;; Re-export a imported variable
3632 (define (module-re-export! m names)
3633 (let ((public-i (module-public-interface m)))
3634 (for-each (lambda (name)
3635 (let* ((internal-name (if (pair? name) (car name) name))
3636 (external-name (if (pair? name) (cdr name) name))
3637 (var (module-variable m internal-name)))
3639 (error "Undefined variable:" internal-name))
3640 ((eq? var (module-local-variable m internal-name))
3641 (error "re-exporting local variable:" internal-name))
3643 (module-add! public-i external-name var)))))
3646 (define-syntax-rule (export name ...)
3647 (eval-when (eval load compile expand)
3648 (call-with-deferred-observers
3650 (module-export! (current-module) '(name ...))))))
3652 (define-syntax-rule (re-export name ...)
3653 (eval-when (eval load compile expand)
3654 (call-with-deferred-observers
3656 (module-re-export! (current-module) '(name ...))))))
3658 (define-syntax-rule (export! name ...)
3659 (eval-when (eval load compile expand)
3660 (call-with-deferred-observers
3662 (module-replace! (current-module) '(name ...))))))
3664 (define-syntax-rule (export-syntax name ...)
3667 (define-syntax-rule (re-export-syntax name ...)
3668 (re-export name ...))
3675 (define* (make-mutable-parameter init #:optional (converter identity))
3676 (let ((fluid (make-fluid (converter init))))
3678 (() (fluid-ref fluid))
3679 ((val) (fluid-set! fluid (converter val))))))
3684 ;;; {Handling of duplicate imported bindings}
3687 ;; Duplicate handlers take the following arguments:
3689 ;; module importing module
3690 ;; name conflicting name
3691 ;; int1 old interface where name occurs
3692 ;; val1 value of binding in old interface
3693 ;; int2 new interface where name occurs
3694 ;; val2 value of binding in new interface
3695 ;; var previous resolution or #f
3696 ;; val value of previous resolution
3698 ;; A duplicate handler can take three alternative actions:
3700 ;; 1. return #f => leave responsibility to next handler
3701 ;; 2. exit with an error
3702 ;; 3. return a variable resolving the conflict
3705 (define duplicate-handlers
3706 (let ((m (make-module 7)))
3708 (define (check module name int1 val1 int2 val2 var val)
3709 (scm-error 'misc-error
3711 "~A: `~A' imported from both ~A and ~A"
3712 (list (module-name module)
3718 (define (warn module name int1 val1 int2 val2 var val)
3719 (format (current-warning-port)
3720 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3721 (module-name module)
3727 (define (replace module name int1 val1 int2 val2 var val)
3728 (let ((old (or (and var (object-property var 'replace) var)
3729 (module-variable int1 name)))
3730 (new (module-variable int2 name)))
3731 (if (object-property old 'replace)
3732 (and (or (eq? old new)
3733 (not (object-property new 'replace)))
3735 (and (object-property new 'replace)
3738 (define (warn-override-core module name int1 val1 int2 val2 var val)
3739 (and (eq? int1 the-scm-module)
3741 (format (current-warning-port)
3742 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3743 (module-name module)
3746 (module-local-variable int2 name))))
3748 (define (first module name int1 val1 int2 val2 var val)
3749 (or var (module-local-variable int1 name)))
3751 (define (last module name int1 val1 int2 val2 var val)
3752 (module-local-variable int2 name))
3754 (define (noop module name int1 val1 int2 val2 var val)
3757 (set-module-name! m 'duplicate-handlers)
3758 (set-module-kind! m 'interface)
3759 (module-define! m 'check check)
3760 (module-define! m 'warn warn)
3761 (module-define! m 'replace replace)
3762 (module-define! m 'warn-override-core warn-override-core)
3763 (module-define! m 'first first)
3764 (module-define! m 'last last)
3765 (module-define! m 'merge-generics noop)
3766 (module-define! m 'merge-accessors noop)
3769 (define (lookup-duplicates-handlers handler-names)
3771 (map (lambda (handler-name)
3772 (or (module-symbol-local-binding
3773 duplicate-handlers handler-name #f)
3774 (error "invalid duplicate handler name:"
3776 (if (list? handler-names)
3778 (list handler-names)))))
3780 (define default-duplicate-binding-procedures
3781 (make-mutable-parameter #f))
3783 (define default-duplicate-binding-handler
3784 (make-mutable-parameter '(replace warn-override-core warn last)
3785 (lambda (handler-names)
3786 (default-duplicate-binding-procedures
3787 (lookup-duplicates-handlers handler-names))
3794 ;;; Load is tricky when combined with relative paths, compilation, and
3795 ;;; the file system. If a path is relative, what is it relative to? The
3796 ;;; path of the source file at the time it was compiled? The path of
3797 ;;; the compiled file? What if both or either were installed? And how
3798 ;;; do you get that information? Tricky, I say.
3800 ;;; To get around all of this, we're going to do something nasty, and
3801 ;;; turn `load' into a macro. That way it can know the path of the
3802 ;;; source file with respect to which it was invoked, so it can resolve
3803 ;;; relative paths with respect to the original source path.
3805 ;;; There is an exception, and that is that if the source file was in
3806 ;;; the load path when it was compiled, instead of looking up against
3807 ;;; the absolute source location, we load-from-path against the relative
3808 ;;; source location.
3811 (define %auto-compilation-options
3812 ;; Default `compile-file' option when auto-compiling.
3813 '(#:warnings (unbound-variable arity-mismatch format)))
3815 (define* (load-in-vicinity dir path #:optional reader)
3816 (define (canonical->suffix canon)
3818 ((string-prefix? "/" canon) canon)
3819 ((and (> (string-length canon) 2)
3820 (eqv? (string-ref canon 1) #\:))
3821 ;; Paths like C:... transform to /C...
3822 (string-append "/" (substring canon 0 1) (substring canon 2)))
3825 ;; Returns the .go file corresponding to `name'. Does not search load
3826 ;; paths, only the fallback path. If the .go file is missing or out of
3827 ;; date, and auto-compilation is enabled, will try auto-compilation, just
3828 ;; as primitive-load-path does internally. primitive-load is
3829 ;; unaffected. Returns #f if auto-compilation failed or was disabled.
3831 ;; NB: Unless we need to compile the file, this function should not cause
3832 ;; (system base compile) to be loaded up. For that reason compiled-file-name
3833 ;; partially duplicates functionality from (system base compile).
3835 (define (compiled-file-name canon-path)
3836 ;; FIXME: would probably be better just to append SHA1(canon-path)
3837 ;; to the %compile-fallback-path, to avoid deep directory stats.
3838 (and %compile-fallback-path
3840 %compile-fallback-path
3841 (canonical->suffix canon-path)
3842 (cond ((or (null? %load-compiled-extensions)
3843 (string-null? (car %load-compiled-extensions)))
3844 (warn "invalid %load-compiled-extensions"
3845 %load-compiled-extensions)
3847 (else (car %load-compiled-extensions))))))
3849 (define (fresh-compiled-file-name name go-path)
3852 (let* ((scmstat (stat name))
3853 (gostat (and (not %fresh-auto-compile)
3854 (stat go-path #f))))
3856 (or (> (stat:mtime gostat) (stat:mtime scmstat))
3857 (and (= (stat:mtime gostat) (stat:mtime scmstat))
3858 (>= (stat:mtimensec gostat)
3859 (stat:mtimensec scmstat)))))
3863 (format (current-warning-port)
3864 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
3867 (%load-should-auto-compile
3868 (%warn-auto-compilation-enabled)
3869 (format (current-warning-port) ";;; compiling ~a\n" name)
3872 (resolve-interface '(system base compile))
3875 #:opts %auto-compilation-options
3876 #:env (current-module))))
3877 (format (current-warning-port) ";;; compiled ~a\n" cfn)
3881 (format (current-warning-port)
3882 ";;; WARNING: compilation of ~a failed:\n" name)
3883 (for-each (lambda (s)
3884 (if (not (string-null? s))
3885 (format (current-warning-port) ";;; ~a\n" s)))
3887 (call-with-output-string
3888 (lambda (port) (print-exception port #f k args)))
3892 (define (absolute-path? path)
3893 (string-prefix? "/" path))
3895 (define (load-absolute abs-path)
3896 (let ((cfn (let ((canon (false-if-exception (canonicalize-path abs-path))))
3898 (let ((go-path (compiled-file-name canon)))
3900 (fresh-compiled-file-name abs-path go-path)))))))
3904 (%load-hook abs-path))
3905 (load-compiled cfn))
3906 (start-stack 'load-stack
3907 (primitive-load abs-path)))))
3909 (save-module-excursion
3911 (with-fluids ((current-reader reader)
3912 (%file-port-name-canonicalization 'relative))
3914 ((or (absolute-path? path))
3915 (load-absolute path))
3916 ((absolute-path? dir)
3917 (load-absolute (in-vicinity dir path)))
3919 (load-from-path (in-vicinity dir path))))))))
3922 (make-variable-transformer
3924 (let* ((src (syntax-source x))
3925 (file (and src (assq-ref src 'filename)))
3926 (dir (and (string? file) (dirname file))))
3929 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
3933 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
3937 ;;; {`cond-expand' for SRFI-0 support.}
3939 ;;; This syntactic form expands into different commands or
3940 ;;; definitions, depending on the features provided by the Scheme
3946 ;;; --> (cond-expand <cond-expand-clause>+)
3947 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3948 ;;; <cond-expand-clause>
3949 ;;; --> (<feature-requirement> <command-or-definition>*)
3950 ;;; <feature-requirement>
3951 ;;; --> <feature-identifier>
3952 ;;; | (and <feature-requirement>*)
3953 ;;; | (or <feature-requirement>*)
3954 ;;; | (not <feature-requirement>)
3955 ;;; <feature-identifier>
3956 ;;; --> <a symbol which is the name or alias of a SRFI>
3958 ;;; Additionally, this implementation provides the
3959 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3960 ;;; determine the implementation type and the supported standard.
3962 ;;; Currently, the following feature identifiers are supported:
3964 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3966 ;;; Remember to update the features list when adding more SRFIs.
3969 (define %cond-expand-features
3970 ;; Adjust the above comment when changing this.
3974 srfi-0 ;; cond-expand itself
3975 srfi-4 ;; homogenous numeric vectors
3976 srfi-6 ;; open-input-string etc, in the guile core
3977 srfi-13 ;; string library
3978 srfi-14 ;; character sets
3979 srfi-23 ;; `error` procedure
3980 srfi-39 ;; parameterize
3981 srfi-55 ;; require-extension
3982 srfi-61 ;; general cond clause
3985 ;; This table maps module public interfaces to the list of features.
3987 (define %cond-expand-table (make-hash-table 31))
3989 ;; Add one or more features to the `cond-expand' feature list of the
3992 (define (cond-expand-provide module features)
3993 (let ((mod (module-public-interface module)))
3995 (hashq-set! %cond-expand-table mod
3996 (append (hashq-ref %cond-expand-table mod '())
3999 (define-syntax cond-expand
4001 (define (module-has-feature? mod sym)
4002 (or-map (lambda (mod)
4003 (memq sym (hashq-ref %cond-expand-table mod '())))
4006 (define (condition-matches? condition)
4007 (syntax-case condition (and or not)
4009 (and-map condition-matches? #'(c ...)))
4011 (or-map condition-matches? #'(c ...)))
4013 (if (condition-matches? #'c) #f #t))
4016 (let ((sym (syntax->datum #'c)))
4017 (if (memq sym %cond-expand-features)
4019 (module-has-feature? (current-module) sym))))))
4021 (define (match clauses alternate)
4022 (syntax-case clauses ()
4023 (((condition form ...) . rest)
4024 (if (condition-matches? #'condition)
4026 (match #'rest alternate)))
4029 (syntax-case x (else)
4030 ((_ clause ... (else form ...))
4031 (match #'(clause ...)
4033 #'(begin form ...))))
4035 (match #'(clause ...)
4037 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
4039 ;; This procedure gets called from the startup code with a list of
4040 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
4042 (define (use-srfis srfis)
4043 (process-use-modules
4045 (list (list 'srfi (string->symbol
4046 (string-append "srfi-" (number->string num))))))
4051 ;;; srfi-55: require-extension
4054 (define-syntax require-extension
4056 (syntax-case x (srfi)
4058 (and-map integer? (syntax->datum #'(n ...)))
4062 (datum->syntax x (symbol-append 'srfi- n)))
4064 (map number->string (syntax->datum #'(n ...)))))))
4065 #'(use-modules (srfi srfi-n) ...)))
4067 (identifier? #'type)
4068 (syntax-violation 'require-extension "Not a recognized extension type"
4072 ;;; Defining transparently inlinable procedures
4075 (define-syntax define-inlinable
4076 ;; Define a macro and a procedure such that direct calls are inlined, via
4077 ;; the macro expansion, whereas references in non-call contexts refer to
4078 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
4080 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
4082 (define prefix (string->symbol "% "))
4083 (define (make-procedure-name name)
4085 (symbol-append prefix (syntax->datum name)
4089 ((_ (name formals ...) body ...)
4090 (identifier? #'name)
4091 (with-syntax ((proc-name (make-procedure-name #'name))
4092 ((args ...) (generate-temporaries #'(formals ...))))
4094 (define (proc-name formals ...)
4095 (syntax-parameterize ((name (identifier-syntax proc-name)))
4097 (define-syntax-parameter name
4101 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
4102 (lambda (formals ...)
4107 #'proc-name))))))))))
4111 (define using-readline?
4112 (let ((using-readline? (make-fluid)))
4113 (make-procedure-with-setter
4114 (lambda () (fluid-ref using-readline?))
4115 (lambda (v) (fluid-set! using-readline? v)))))
4119 ;;; {Deprecated stuff}
4123 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
4127 ;;; SRFI-4 in the default environment. FIXME: we should figure out how
4128 ;;; to deprecate this.
4132 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
4136 ;;; A few identifiers that need to be defined in this file are really
4137 ;;; internal implementation details. We shove them off into internal
4138 ;;; modules, removing them from the (guile) module.
4141 (define-module (system syntax))
4144 (define (steal-bindings! from to ids)
4147 (let ((v (module-local-variable from sym)))
4148 (module-remove! from sym)
4149 (module-add! to sym v)))
4151 (module-export! to ids))
4153 (steal-bindings! the-root-module (resolve-module '(system syntax))
4154 '(syntax-local-binding
4156 syntax-locally-bound-identifiers
4157 syntax-session-id)))
4162 ;;; Place the user in the guile-user module.
4165 ;; Set filename to #f to prevent reload.
4166 (define-module (guile-user)
4167 #:autoload (system base compile) (compile compile-file)
4170 ;; Remain in the `(guile)' module at compilation-time so that the
4171 ;; `-Wunused-toplevel' warning works as expected.
4172 (eval-when (compile) (set-current-module the-root-module))
4174 ;;; boot-9.scm ends here