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, 2013, 2014
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 ((@@ primitive call-with-prompt) tag thunk handler))
66 (define (abort-to-prompt tag . args)
67 (abort-to-prompt* tag args))
69 (define (with-fluid* fluid val thunk)
70 "Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
71 @var{thunk} must be a procedure of no arguments."
72 ((@@ primitive push-fluid) fluid val)
73 (call-with-values thunk
75 ((@@ primitive pop-fluid))
76 (apply values vals))))
78 ;; Define catch and with-throw-handler, using some common helper routines and a
79 ;; shared fluid. Hide the helpers in a lexical contour.
81 (define with-throw-handler #f)
83 (define (default-exception-handler k . args)
87 ((not (pair? args)) 0)
88 ((integer? (car args)) (car args))
92 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
95 (define %running-exception-handlers (make-fluid '()))
96 (define %exception-handler (make-fluid default-exception-handler))
98 (define (default-throw-handler prompt-tag catch-k)
99 (let ((prev (fluid-ref %exception-handler)))
100 (lambda (thrown-k . args)
101 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
102 (apply abort-to-prompt prompt-tag thrown-k args)
103 (apply prev thrown-k args)))))
105 (define (custom-throw-handler prompt-tag catch-k pre)
106 (let ((prev (fluid-ref %exception-handler)))
107 (lambda (thrown-k . args)
108 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
109 (let ((running (fluid-ref %running-exception-handlers)))
110 (with-fluid* %running-exception-handlers (cons pre running)
112 (if (not (memq pre running))
113 (apply pre thrown-k args))
116 (apply abort-to-prompt prompt-tag thrown-k args)
117 (apply prev thrown-k args)))))
118 (apply prev thrown-k args)))))
121 (lambda* (k thunk handler #:optional pre-unwind-handler)
122 "Invoke @var{thunk} in the dynamic context of @var{handler} for
123 exceptions matching @var{key}. If thunk throws to the symbol
124 @var{key}, then @var{handler} is invoked this way:
126 (handler key args ...)
129 @var{key} is a symbol or @code{#t}.
131 @var{thunk} takes no arguments. If @var{thunk} returns
132 normally, that is the return value of @code{catch}.
134 Handler is invoked outside the scope of its own @code{catch}.
135 If @var{handler} again throws to the same key, a new handler
136 from further up the call chain is invoked.
138 If the key is @code{#t}, then a throw to @emph{any} symbol will
139 match this call to @code{catch}.
141 If a @var{pre-unwind-handler} is given and @var{thunk} throws
142 an exception that matches @var{key}, Guile calls the
143 @var{pre-unwind-handler} before unwinding the dynamic state and
144 invoking the main @var{handler}. @var{pre-unwind-handler} should
145 be a procedure with the same signature as @var{handler}, that
146 is @code{(lambda (key . args))}. It is typically used to save
147 the stack at the point where the exception occurred, but can also
148 query other parts of the dynamic state at that point, such as
151 A @var{pre-unwind-handler} can exit either normally or non-locally.
152 If it exits normally, Guile unwinds the stack and dynamic context
153 and then calls the normal (third argument) handler. If it exits
154 non-locally, that exit determines the continuation."
155 (if (not (or (symbol? k) (eqv? k #t)))
156 (scm-error 'wrong-type-arg "catch"
157 "Wrong type argument in position ~a: ~a"
158 (list 1 k) (list k)))
159 (let ((tag (make-prompt-tag "catch")))
163 (with-fluid* %exception-handler
164 (if pre-unwind-handler
165 (custom-throw-handler tag k pre-unwind-handler)
166 (default-throw-handler tag k))
168 (lambda (cont k . args)
169 (apply handler k args))))))
171 (set! with-throw-handler
172 (lambda (k thunk pre-unwind-handler)
173 "Add @var{handler} to the dynamic context as a throw handler
174 for key @var{k}, then invoke @var{thunk}."
175 (if (not (or (symbol? k) (eqv? k #t)))
176 (scm-error 'wrong-type-arg "with-throw-handler"
177 "Wrong type argument in position ~a: ~a"
178 (list 1 k) (list k)))
179 (with-fluid* %exception-handler
180 (custom-throw-handler #f k pre-unwind-handler)
185 "Invoke the catch form matching @var{key}, passing @var{args} to the
188 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
190 If there is no handler at all, Guile prints an error and then exits."
191 (if (not (symbol? key))
192 ((fluid-ref %exception-handler) 'wrong-type-arg "throw"
193 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
194 (apply (fluid-ref %exception-handler) key args)))))
199 ;;; {Language primitives}
202 ;; These are are the procedural wrappers around the primitives of
203 ;; Guile's language: apply, call-with-current-continuation, etc.
205 ;; Usually, a call to a primitive is compiled specially. The compiler
206 ;; knows about all these kinds of expressions. But the primitives may
207 ;; be referenced not only as operators, but as values as well. These
208 ;; stub procedures are the "values" of apply, dynamic-wind, and other
214 ((@@ primitive apply) fun args))
216 (letrec ((append* (lambda (tail)
217 (let ((tail (car tail))
221 (cons tail (append* tail*)))))))
222 (apply fun (cons arg1 (append* args)))))))
223 (define (call-with-current-continuation proc)
224 ((@@ primitive call-with-current-continuation) proc))
225 (define (call-with-values producer consumer)
226 ((@@ primitive call-with-values) producer consumer))
227 (define (dynamic-wind in thunk out)
228 "All three arguments must be 0-argument procedures.
229 Guard @var{in} is called, then @var{thunk}, then
232 If, any time during the execution of @var{thunk}, the
233 continuation of the @code{dynamic_wind} expression is escaped
234 non-locally, @var{out} is called. If the continuation of
235 the dynamic-wind is re-entered, @var{in} is called. Thus
236 @var{in} and @var{out} may be called any number of
239 (define x 'normal-binding)
242 (call-with-current-continuation
248 (lambda () (set! x 'special-binding))
252 (lambda () (display x) (newline)
253 (call-with-current-continuation escape)
254 (display x) (newline)
259 (lambda () (set! x old-x)))))))
266 @result{} normal-binding
271 @result{} a-cont ;; the value of the (define a-cont...)
273 @result{} normal-binding
275 @result{} special-binding
277 ;; FIXME: Here we don't check that the out procedure is a thunk before
278 ;; calling the in-guard, as dynamic-wind is called as part of loading
279 ;; modules, but thunk? requires loading (system vm debug). This is in
280 ;; contrast to the open-coded version of dynamic-wind, which does
281 ;; currently insert an eager thunk? check (but often optimizes it
282 ;; out). Not sure what the right thing to do is here -- make thunk?
283 ;; callable before modules are loaded, live with this inconsistency,
284 ;; or remove the thunk? check from the compiler? Questions,
288 (scm-error 'wrong-type-arg "dynamic-wind" "Not a thunk: ~S"
291 ((@@ primitive wind) in out)
292 (call-with-values thunk
294 ((@@ primitive unwind))
296 (apply values vals))))
300 ;;; {Low-Level Port Code}
303 ;; These are used to request the proper mode to open files in.
305 (define OPEN_READ "r")
306 (define OPEN_WRITE "w")
307 (define OPEN_BOTH "r+")
309 (define *null-device* "/dev/null")
311 ;; NOTE: Later in this file, this is redefined to support keywords
312 (define (open-input-file str)
313 "Takes a string naming an existing file and returns an input port
314 capable of delivering characters from the file. If the file
315 cannot be opened, an error is signalled."
316 (open-file str OPEN_READ))
318 ;; NOTE: Later in this file, this is redefined to support keywords
319 (define (open-output-file str)
320 "Takes a string naming an output file to be created and returns an
321 output port capable of writing characters to a new file by that
322 name. If the file cannot be opened, an error is signalled. If a
323 file with the given name already exists, the effect is unspecified."
324 (open-file str OPEN_WRITE))
326 (define (open-io-file str)
327 "Open file with name STR for both input and output."
328 (open-file str OPEN_BOTH))
332 ;;; {Simple Debugging Tools}
335 ;; peek takes any number of arguments, writes them to the
336 ;; current ouput port, and returns the last argument.
337 ;; It is handy to wrap around an expression to look at
338 ;; a value each time is evaluated, e.g.:
340 ;; (+ 10 (troublesome-fn))
341 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
344 (define (peek . stuff)
349 (car (last-pair stuff)))
353 ;; Temporary definition; replaced later.
354 (define current-warning-port current-error-port)
356 (define (warn . stuff)
357 (newline (current-warning-port))
358 (display ";;; WARNING " (current-warning-port))
359 (display stuff (current-warning-port))
360 (newline (current-warning-port))
361 (car (last-pair stuff)))
368 (define (provide sym)
369 (if (not (memq sym *features*))
370 (set! *features* (cons sym *features*))))
372 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
373 ;; provided? also checks to see if the module is available. We should do that
376 (define (provided? feature)
377 (and (memq feature *features*) #t))
384 (define (make-struct/no-tail vtable . args)
385 (apply make-struct vtable 0 args))
389 ;;; Boot versions of `map' and `for-each', enough to get the expander
398 (cons (f (car l)) (map1 (cdr l))))))
400 (let map2 ((l1 l1) (l2 l2))
403 (cons (f (car l1) (car l2))
404 (map2 (cdr l1) (cdr l2))))))
406 (let lp ((l1 l1) (rest rest))
409 (cons (apply f (car l1) (map car rest))
410 (lp (cdr l1) (map cdr rest))))))))
415 (let for-each1 ((l l))
419 (for-each1 (cdr l))))))
421 (let for-each2 ((l1 l1) (l2 l2))
424 (f (car l1) (car l2))
425 (for-each2 (cdr l1) (cdr l2))))))
427 (let lp ((l1 l1) (rest rest))
430 (apply f (car l1) (map car rest))
431 (lp (cdr l1) (map cdr rest))))))))
433 ;; Temporary definition used in the include-from-path expansion;
436 (define (absolute-file-name? file-name)
439 ;;; {and-map and or-map}
441 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
442 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
447 ;; Apply f to successive elements of l until exhaustion or f returns #f.
448 ;; If returning early, return #f. Otherwise, return the last value returned
449 ;; by f. If f has never been called because l is empty, return #t.
451 (define (and-map f lst)
452 (let loop ((result #t)
457 (loop (f (car l)) (cdr l))))))
461 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
462 ;; If returning early, return the return value of f.
464 (define (or-map f lst)
465 (let loop ((result #f)
469 (loop (f (car l)) (cdr l))))))
473 ;; let format alias simple-format until the more complete version is loaded
475 (define format simple-format)
477 ;; this is scheme wrapping the C code so the final pred call is a tail call,
480 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
481 (if (and (procedure? char_pred)
483 (<= end (string-length s))) ;; let c-code handle range error
484 (or (string-any-c-code char_pred s start (1- end))
485 (char_pred (string-ref s (1- end))))
486 (string-any-c-code char_pred s start end))))
488 ;; this is scheme wrapping the C code so the final pred call is a tail call,
491 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
492 (if (and (procedure? char_pred)
494 (<= end (string-length s))) ;; let c-code handle range error
495 (and (string-every-c-code char_pred s start (1- end))
496 (char_pred (string-ref s (1- end))))
497 (string-every-c-code char_pred s start end))))
499 ;; A variant of string-fill! that we keep for compatability
501 (define (substring-fill! str start end fill)
502 (string-fill! str fill start end))
506 ;; Define a minimal stub of the module API for psyntax, before modules
508 (define (module-name x)
510 (define (module-add! module sym var)
511 (hashq-set! (%get-pre-modules-obarray) sym var))
512 (define (module-define! module sym val)
513 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
515 (variable-set! v val)
516 (module-add! (current-module) sym (make-variable val)))))
517 (define (module-ref module sym)
518 (let ((v (module-variable module sym)))
519 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
520 (define (resolve-module . args)
523 ;; API provided by psyntax
524 (define syntax-violation #f)
525 (define datum->syntax #f)
526 (define syntax->datum #f)
527 (define syntax-source #f)
528 (define identifier? #f)
529 (define generate-temporaries #f)
530 (define bound-identifier=? #f)
531 (define free-identifier=? #f)
533 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
534 ;; expanded macros, to dispatch an input against a set of patterns.
535 (define $sc-dispatch #f)
538 (primitive-load-path "ice-9/psyntax-pp")
539 ;; The binding for `macroexpand' has now been overridden, making psyntax the
546 ((_ x y ...) (if x (and y ...) #f))))
552 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
554 (include-from-path "ice-9/quasisyntax")
556 (define-syntax-rule (when test stmt stmt* ...)
557 (if test (begin stmt stmt* ...)))
559 (define-syntax-rule (unless test stmt stmt* ...)
560 (if (not test) (begin stmt stmt* ...)))
564 (define (fold f seed xs)
565 (let loop ((xs xs) (seed seed))
567 (loop (cdr xs) (f (car xs) seed)))))
568 (define (reverse-map f xs)
569 (fold (lambda (x seed) (cons (f x) seed))
571 (syntax-case whole-expr ()
572 ((_ clause clauses ...)
574 #,@(fold (lambda (clause-builder tail)
575 (clause-builder tail))
579 (define* (bad-clause #:optional (msg "invalid clause"))
580 (syntax-violation 'cond msg whole-expr clause))
581 (syntax-case clause (=> else)
586 (bad-clause "else must be the last clause"))))
587 ((else . _) (bad-clause))
594 ((test => receiver ...)
595 (bad-clause "wrong number of receiver expressions"))
596 ((generator guard => receiver)
598 #`((call-with-values (lambda () generator)
600 (if (apply guard vals)
601 (apply receiver vals)
603 ((generator guard => receiver ...)
604 (bad-clause "wrong number of receiver expressions"))
615 #'(clause clauses ...))))))))
619 (define (fold f seed xs)
620 (let loop ((xs xs) (seed seed))
622 (loop (cdr xs) (f (car xs) seed)))))
623 (define (fold2 f a b xs)
624 (let loop ((xs xs) (a a) (b b))
625 (if (null? xs) (values a b)
627 (lambda () (f (car xs) a b))
629 (loop (cdr xs) a b))))))
630 (define (reverse-map-with-seed f seed xs)
631 (fold2 (lambda (x ys seed)
633 (lambda () (f x seed))
635 (values (cons y ys) seed))))
637 (syntax-case whole-expr ()
638 ((_ expr clause clauses ...)
639 (with-syntax ((key #'key))
642 (lambda (clause-builder tail)
643 (clause-builder tail))
645 (reverse-map-with-seed
646 (lambda (clause seen)
647 (define* (bad-clause #:optional (msg "invalid clause"))
648 (syntax-violation 'case msg whole-expr clause))
649 (syntax-case clause ()
653 (syntax-case #'rest (=>)
654 ((=> receiver) #'(receiver key))
657 "wrong number of receiver expressions"))
658 ((e e* ...) #'(begin e e* ...))
660 (syntax-case #'test (else)
665 (define (warn-datum type)
666 ((@ (system base message)
669 (append (source-properties datum)
671 (syntax->datum #'test)))
673 (syntax->datum clause)
674 (syntax->datum whole-expr)))
675 (when (memv datum seen)
676 (warn-datum 'duplicate-case-datum))
677 (when (or (pair? datum) (array? datum))
678 (warn-datum 'bad-case-datum))
681 (map syntax->datum #'(datums ...)))))
682 (values (lambda (tail)
683 #`((if (memv key '(datums ...))
687 (else (values (lambda (tail)
691 "else must be the last clause")))
695 '() #'(clause clauses ...)))))))))
699 ((do ((var init step ...) ...)
712 (loop (do "step" var step ...)
720 (define-syntax define-values
722 (syntax-case orig-form ()
724 ;; XXX Work around the lack of hygienic top-level identifiers
725 (with-syntax (((dummy) (generate-temporaries '(dummy))))
727 (call-with-values (lambda () expr)
732 (call-with-values (lambda () expr)
734 ((_ (var0 ... varn) expr)
735 (and-map identifier? #'(var0 ... varn))
736 ;; XXX Work around the lack of hygienic toplevel identifiers
737 (with-syntax (((dummy) (generate-temporaries '(dummy))))
739 ;; Avoid mutating the user-visible variables
741 (call-with-values (lambda () expr)
742 (lambda (var0 ... varn)
743 (list var0 ... varn))))
745 (let ((v (car dummy)))
746 (set! dummy (cdr dummy))
750 (let ((v (car dummy)))
751 (set! dummy #f) ; blackhole dummy
756 (call-with-values (lambda () expr)
758 ((_ (var0 ... . varn) expr)
759 (and-map identifier? #'(var0 ... varn))
760 ;; XXX Work around the lack of hygienic toplevel identifiers
761 (with-syntax (((dummy) (generate-temporaries '(dummy))))
763 ;; Avoid mutating the user-visible variables
765 (call-with-values (lambda () expr)
766 (lambda (var0 ... . varn)
767 (list var0 ... varn))))
769 (let ((v (car dummy)))
770 (set! dummy (cdr dummy))
774 (let ((v (car dummy)))
775 (set! dummy #f) ; blackhole dummy
778 (define-syntax-rule (delay exp)
779 (make-promise (lambda () exp)))
781 (define-syntax with-fluids
783 (define (emit-with-fluids bindings body)
784 (syntax-case bindings ()
790 #,(emit-with-fluids #'bindings body))))))
792 ((_ ((fluid val) ...) exp exp* ...)
793 (with-syntax (((fluid-tmp ...) (generate-temporaries #'(fluid ...)))
794 ((val-tmp ...) (generate-temporaries #'(val ...))))
795 #`(let ((fluid-tmp fluid) ...)
796 (let ((val-tmp val) ...)
797 #,(emit-with-fluids #'((fluid-tmp val-tmp) ...)
798 #'(begin exp exp* ...)))))))))
800 (define-syntax current-source-location
804 (with-syntax ((s (datum->syntax x (syntax-source x))))
807 ;; We provide this accessor out of convenience. current-line and
808 ;; current-column aren't so interesting, because they distort what they
809 ;; are measuring; better to use syntax-source from a macro.
811 (define-syntax current-filename
813 "A macro that expands to the current filename: the filename that
814 the (current-filename) form appears in. Expands to #f if this
815 information is unavailable."
817 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
819 (define-syntax-rule (define-once sym val)
821 (if (module-locally-bound? (current-module) 'sym) sym val)))
823 ;;; The real versions of `map' and `for-each', with cycle detection, and
824 ;;; that use reverse! instead of recursion in the case of `map'.
829 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
832 (if (eq? tortoise hare)
833 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
835 (map1 (cdr hare) (cdr tortoise) #f
836 (cons (f (car hare)) out)))
837 (map1 (cdr hare) tortoise #t
838 (cons (f (car hare)) out)))
841 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
845 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
850 (scm-error 'wrong-type-arg "map"
852 "List of wrong length: ~S"
856 (map2 (cdr h1) (cdr h2) t1 t2 #t
857 (cons (f (car h1) (car h2)) out)))
859 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
862 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
865 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
866 (cons (f (car h1) (car h2)) out)))))
868 ((and (null? h1) (null? h2))
872 (scm-error 'wrong-type-arg "map"
874 "List of wrong length: ~S"
878 (scm-error 'wrong-type-arg "map"
883 (let ((len (length l1)))
884 (let mapn ((rest rest))
886 (if (= (length (car rest)) len)
888 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
889 (list (car rest)) #f)))))
890 (let mapn ((l1 l1) (rest rest) (out '()))
893 (mapn (cdr l1) (map cdr rest)
894 (cons (apply f (car l1) (map car rest)) out)))))))
896 (define map-in-order map)
901 (let for-each1 ((hare l) (tortoise l))
905 (let ((hare (cdr hare)))
908 (when (eq? tortoise hare)
909 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
912 (for-each1 (cdr hare) (cdr tortoise))))))
913 (if (not (null? hare))
914 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
918 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
920 ((and (pair? h1) (pair? h2))
923 (f (car h1) (car h2))
924 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
926 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
929 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
932 (f (car h1) (car h2))
933 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
936 (or (null? h2) (pair? h2))
937 (and (pair? h1) (null? h2)))
941 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
944 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
948 (let ((len (length l1)))
949 (let for-eachn ((rest rest))
951 (if (= (length (car rest)) len)
952 (for-eachn (cdr rest))
953 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
954 (list (car rest)) #f)))))
956 (let for-eachn ((l1 l1) (rest rest))
959 (apply f (car l1) (map car rest))
960 (for-eachn (cdr l1) (map cdr rest))))))))
966 ;;; Extensible exception printing.
969 (define set-exception-printer! #f)
970 ;; There is already a definition of print-exception from backtrace.c
971 ;; that we will override.
973 (let ((exception-printers '()))
974 (define (print-location frame port)
975 (let ((source (and=> frame frame-source)))
976 ;; source := (addr . (filename . (line . column)))
978 (let ((filename (or (cadr source) "<unnamed port>"))
979 (line (caddr source))
980 (col (cdddr source)))
981 (format port "~a:~a:~a: " filename (1+ line) col))
982 (format port "ERROR: "))))
984 (set! set-exception-printer!
986 (set! exception-printers (acons key proc exception-printers))))
988 (set! print-exception
989 (lambda (port frame key args)
990 (define (default-printer)
991 (format port "Throw to key `~a' with args `~s'." key args))
994 (let ((proc (frame-procedure frame)))
995 (print-location frame port)
996 (format port "In procedure ~a:\n"
997 (or (false-if-exception (procedure-name proc))
1000 (print-location frame port)
1003 (let ((printer (assq-ref exception-printers key)))
1005 (printer port key args default-printer)
1006 (default-printer))))
1008 (format port "Error while printing exception.")))
1010 (force-output port))))
1013 ;;; Printers for those keys thrown by Guile.
1016 (define (scm-error-printer port key args default-printer)
1017 ;; Abuse case-lambda as a pattern matcher, given that we don't have
1018 ;; ice-9 match at this point.
1020 ((subr msg args . rest)
1022 (format port "In procedure ~a: " subr))
1023 (apply format port msg (or args '())))
1024 (_ (default-printer)))
1027 (define (syntax-error-printer port key args default-printer)
1029 ((who what where form subform . extra)
1030 (format port "Syntax error:\n")
1032 (let ((file (or (assq-ref where 'filename) "unknown file"))
1033 (line (and=> (assq-ref where 'line) 1+))
1034 (col (assq-ref where 'column)))
1035 (format port "~a:~a:~a: " file line col))
1036 (format port "unknown location: "))
1038 (format port "~a: " who))
1039 (format port "~a" what)
1041 (format port " in subform ~s of ~s" subform form)
1043 (format port " in form ~s" form))))
1044 (_ (default-printer)))
1047 (define (keyword-error-printer port key args default-printer)
1048 (let ((message (cadr args))
1049 (faulty (car (cadddr args)))) ; I won't do it again, I promise.
1050 (format port "~a: ~s" message faulty)))
1052 (define (getaddrinfo-error-printer port key args default-printer)
1053 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
1055 (set-exception-printer! 'goops-error scm-error-printer)
1056 (set-exception-printer! 'host-not-found scm-error-printer)
1057 (set-exception-printer! 'keyword-argument-error keyword-error-printer)
1058 (set-exception-printer! 'misc-error scm-error-printer)
1059 (set-exception-printer! 'no-data scm-error-printer)
1060 (set-exception-printer! 'no-recovery scm-error-printer)
1061 (set-exception-printer! 'null-pointer-error scm-error-printer)
1062 (set-exception-printer! 'out-of-range scm-error-printer)
1063 (set-exception-printer! 'program-error scm-error-printer)
1064 (set-exception-printer! 'read-error scm-error-printer)
1065 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
1066 (set-exception-printer! 'signal scm-error-printer)
1067 (set-exception-printer! 'stack-overflow scm-error-printer)
1068 (set-exception-printer! 'system-error scm-error-printer)
1069 (set-exception-printer! 'try-again scm-error-printer)
1070 (set-exception-printer! 'unbound-variable scm-error-printer)
1071 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
1072 (set-exception-printer! 'wrong-type-arg scm-error-printer)
1074 (set-exception-printer! 'syntax-error syntax-error-printer)
1076 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
1084 (define-syntax define-macro
1086 "Define a defmacro."
1088 ((_ (macro . args) doc body1 body ...)
1089 (string? (syntax->datum #'doc))
1090 #'(define-macro macro doc (lambda args body1 body ...)))
1091 ((_ (macro . args) body ...)
1092 #'(define-macro macro #f (lambda args body ...)))
1093 ((_ macro transformer)
1094 #'(define-macro macro #f transformer))
1095 ((_ macro doc transformer)
1096 (or (string? (syntax->datum #'doc))
1097 (not (syntax->datum #'doc)))
1098 #'(define-syntax macro
1101 #((macro-type . defmacro)
1102 (defmacro-args args))
1105 (let ((v (syntax->datum #'args)))
1106 (datum->syntax y (apply transformer v)))))))))))
1108 (define-syntax defmacro
1110 "Define a defmacro, with the old lispy defun syntax."
1112 ((_ macro args doc body1 body ...)
1113 (string? (syntax->datum #'doc))
1114 #'(define-macro macro doc (lambda args body1 body ...)))
1115 ((_ macro args body ...)
1116 #'(define-macro macro #f (lambda args body ...))))))
1125 (define-syntax begin-deprecated
1129 (if (include-deprecated-features)
1130 #'(begin form form* ...)
1135 ;;; {Trivial Functions}
1138 (define (identity x) x)
1140 (define (compose proc . rest)
1141 "Compose PROC with the procedures in REST, such that the last one in
1142 REST is applied first and PROC last, and return the resulting procedure.
1143 The given procedures must have compatible arity."
1146 (let ((g (apply compose rest)))
1148 (call-with-values (lambda () (apply g args)) proc)))))
1150 (define (negate proc)
1151 "Return a procedure with the same arity as PROC that returns the `not'
1154 (not (apply proc args))))
1156 (define (const value)
1157 "Return a procedure that accepts any number of arguments and returns
1162 (define (and=> value procedure)
1163 "When VALUE is #f, return #f. Otherwise, return (PROC VALUE)."
1164 (and value (procedure value)))
1166 (define call/cc call-with-current-continuation)
1168 (define-syntax false-if-exception
1170 ((false-if-exception expr)
1174 ((false-if-exception expr #:warning template arg ...)
1177 (lambda (key . args)
1178 (for-each (lambda (s)
1179 (if (not (string-null? s))
1180 (format (current-warning-port) ";;; ~a\n" s)))
1182 (call-with-output-string
1184 (format port template arg ...)
1185 (print-exception port #f key args)))
1191 ;;; {General Properties}
1194 ;; Properties are a lispy way to associate random info with random objects.
1195 ;; Traditionally properties are implemented as an alist or a plist actually
1196 ;; pertaining to the object in question.
1198 ;; These "object properties" have the advantage that they can be associated with
1199 ;; any object, even if the object has no plist. Object properties are good when
1200 ;; you are extending pre-existing objects in unexpected ways. They also present
1201 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
1202 ;; type that always has properties, it's often still best to store those
1203 ;; properties within the object itself.
1205 (define (make-object-property)
1206 ;; Weak tables are thread-safe.
1207 (let ((prop (make-weak-key-hash-table)))
1208 (make-procedure-with-setter
1209 (lambda (obj) (hashq-ref prop obj))
1210 (lambda (obj val) (hashq-set! prop obj val)))))
1215 ;;; {Symbol Properties}
1218 ;;; Symbol properties are something you see in old Lisp code. In most current
1219 ;;; Guile code, symbols are not used as a data structure -- they are used as
1220 ;;; keys into other data structures.
1222 (define (symbol-property sym prop)
1223 (let ((pair (assoc prop (symbol-pref sym))))
1224 (and pair (cdr pair))))
1226 (define (set-symbol-property! sym prop val)
1227 (let ((pair (assoc prop (symbol-pref sym))))
1230 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
1232 (define (symbol-property-remove! sym prop)
1233 (let ((pair (assoc prop (symbol-pref sym))))
1235 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
1242 (define (array-shape a)
1243 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1244 (array-dimensions a)))
1251 ;;; It's much better if you can use lambda* / define*, of course.
1253 (define (kw-arg-ref args kw)
1254 (let ((rem (member kw args)))
1255 (and rem (pair? (cdr rem)) (cadr rem))))
1259 ;;; {IOTA functions: generating lists of numbers}
1263 (let loop ((count (1- n)) (result '()))
1264 (if (< count 0) result
1265 (loop (1- count) (cons count result)))))
1272 (define (struct-layout s)
1273 (struct-ref (struct-vtable s) vtable-index-layout))
1280 ;; Printing records: by default, records are printed as
1282 ;; #<type-name field1: val1 field2: val2 ...>
1284 ;; You can change that by giving a custom printing function to
1285 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1286 ;; will be called like
1288 ;; (<printer> object port)
1290 ;; It should print OBJECT to PORT.
1292 (define (inherit-print-state old-port new-port)
1293 (if (get-print-state old-port)
1294 (port-with-print-state new-port (get-print-state old-port))
1297 ;; 0: type-name, 1: fields, 2: constructor
1298 (define record-type-vtable
1299 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1301 (display "#<record-type " p)
1302 (display (record-type-name s) p)
1304 (set-struct-vtable-name! s 'record-type)
1307 (define (record-type? obj)
1308 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1310 (define* (make-record-type type-name fields #:optional printer)
1311 ;; Pre-generate constructors for nfields < 20.
1312 (define-syntax make-constructor
1314 (define *max-static-argument-count* 20)
1315 (define (make-formals n)
1318 (cons (datum->syntax
1321 (string (integer->char (+ (char->integer #\a) i)))))
1325 ((_ rtd exp) (not (identifier? #'exp))
1327 (make-constructor rtd n)))
1331 (if (< n *max-static-argument-count*)
1332 (cons (with-syntax (((formal ...) (make-formals n))
1333 ((idx ...) (iota n))
1336 (lambda (formal ...)
1337 (let ((s (allocate-struct rtd n)))
1338 (struct-set! s idx formal)
1345 (if (= (length args) nfields)
1346 (apply make-struct rtd 0 args)
1347 (scm-error 'wrong-number-of-args
1348 (format #f "make-~a" type-name)
1349 "Wrong number of arguments" '() #f)))))))))
1351 (define (default-record-printer s p)
1353 (display (record-type-name (record-type-descriptor s)) p)
1354 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1357 ((not (null? fields))
1359 (display (car fields) p)
1361 (display (struct-ref s off) p)
1362 (loop (cdr fields) (+ 1 off)))))
1365 (let ((rtd (make-struct record-type-vtable 0
1367 (apply string-append
1368 (map (lambda (f) "pw") fields)))
1369 (or printer default-record-printer)
1371 (copy-tree fields))))
1372 (struct-set! rtd (+ vtable-offset-user 2)
1373 (make-constructor rtd (length fields)))
1374 ;; Temporary solution: Associate a name to the record type descriptor
1375 ;; so that the object system can create a wrapper class for it.
1376 (set-struct-vtable-name! rtd (if (symbol? type-name)
1378 (string->symbol type-name)))
1381 (define (record-type-name obj)
1382 (if (record-type? obj)
1383 (struct-ref obj vtable-offset-user)
1384 (error 'not-a-record-type obj)))
1386 (define (record-type-fields obj)
1387 (if (record-type? obj)
1388 (struct-ref obj (+ 1 vtable-offset-user))
1389 (error 'not-a-record-type obj)))
1391 (define* (record-constructor rtd #:optional field-names)
1392 (if (not field-names)
1393 (struct-ref rtd (+ 2 vtable-offset-user))
1395 `(lambda ,field-names
1396 (make-struct ',rtd 0 ,@(map (lambda (f)
1397 (if (memq f field-names)
1400 (record-type-fields rtd)))))))
1402 (define (record-predicate rtd)
1403 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1405 (define (%record-type-error rtd obj) ;; private helper
1406 (or (eq? rtd (record-type-descriptor obj))
1407 (scm-error 'wrong-type-arg "%record-type-check"
1408 "Wrong type record (want `~S'): ~S"
1409 (list (record-type-name rtd) obj)
1412 (define (record-accessor rtd field-name)
1413 (let ((pos (list-index (record-type-fields rtd) field-name)))
1415 (error 'no-such-field field-name))
1417 (if (eq? (struct-vtable obj) rtd)
1418 (struct-ref obj pos)
1419 (%record-type-error rtd obj)))))
1421 (define (record-modifier rtd field-name)
1422 (let ((pos (list-index (record-type-fields rtd) field-name)))
1424 (error 'no-such-field field-name))
1426 (if (eq? (struct-vtable obj) rtd)
1427 (struct-set! obj pos val)
1428 (%record-type-error rtd obj)))))
1430 (define (record? obj)
1431 (and (struct? obj) (record-type? (struct-vtable obj))))
1433 (define (record-type-descriptor obj)
1436 (error 'not-a-record obj)))
1446 ;; Three fields: the procedure itself, the fluid, and the converter.
1447 (make-struct <applicable-struct-vtable> 0 'pwprpr))
1448 (set-struct-vtable-name! <parameter> '<parameter>)
1450 (define* (make-parameter init #:optional (conv (lambda (x) x)))
1451 "Make a new parameter.
1453 A parameter is a dynamically bound value, accessed through a procedure.
1454 To access the current value, apply the procedure with no arguments:
1456 (define p (make-parameter 10))
1459 To provide a new value for the parameter in a dynamic extent, use
1462 (parameterize ((p 20))
1466 The value outside of the dynamic extent of the body is unaffected. To
1467 update the current value, apply it to one argument:
1472 As you can see, the call that updates a parameter returns its previous
1475 All values for the parameter are first run through the CONV procedure,
1476 including INIT, the initial value. The default CONV procedure is the
1477 identity procedure. CONV is commonly used to ensure some set of
1478 invariants on the values that a parameter may have."
1479 (let ((fluid (make-fluid (conv init))))
1480 (make-struct <parameter> 0
1482 (() (fluid-ref fluid))
1483 ((x) (let ((prev (fluid-ref fluid)))
1484 (fluid-set! fluid (conv x))
1488 (define (parameter? x)
1489 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
1491 (define (parameter-fluid p)
1494 (scm-error 'wrong-type-arg "parameter-fluid"
1495 "Not a parameter: ~S" (list p) #f)))
1497 (define (parameter-converter p)
1500 (scm-error 'wrong-type-arg "parameter-fluid"
1501 "Not a parameter: ~S" (list p) #f)))
1503 (define-syntax parameterize
1506 ((_ ((param value) ...) body body* ...)
1507 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
1508 #'(let ((p param) ...)
1509 (if (not (parameter? p))
1510 (scm-error 'wrong-type-arg "parameterize"
1511 "Not a parameter: ~S" (list p) #f))
1513 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
1515 body body* ...)))))))
1517 (define* (fluid->parameter fluid #:optional (conv (lambda (x) x)))
1518 "Make a parameter that wraps a fluid.
1520 The value of the parameter will be the same as the value of the fluid.
1521 If the parameter is rebound in some dynamic extent, perhaps via
1522 `parameterize', the new value will be run through the optional CONV
1523 procedure, as with any parameter. Note that unlike `make-parameter',
1524 CONV is not applied to the initial value."
1525 (make-struct <parameter> 0
1527 (() (fluid-ref fluid))
1528 ((x) (let ((prev (fluid-ref fluid)))
1529 (fluid-set! fluid (conv x))
1535 ;;; Once parameters have booted, define the default prompt tag as being
1539 (set! default-prompt-tag (make-parameter (default-prompt-tag)))
1543 ;;; Current ports as parameters.
1547 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
1549 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
1553 (hashq-remove! (%get-pre-modules-obarray) 'fluid)))
1555 (port-parameterize! current-input-port %current-input-port-fluid
1556 input-port? "expected an input port")
1557 (port-parameterize! current-output-port %current-output-port-fluid
1558 output-port? "expected an output port")
1559 (port-parameterize! current-error-port %current-error-port-fluid
1560 output-port? "expected an output port"))
1567 (define current-warning-port
1568 (make-parameter (current-error-port)
1570 (if (output-port? x)
1572 (error "expected an output port" x)))))
1580 ;; The language can be a symbolic name or a <language> object from
1581 ;; (system base language).
1583 (define current-language (make-parameter 'scheme))
1588 ;;; {High-Level Port Routines}
1591 (define* (open-input-file
1592 file #:key (binary #f) (encoding #f) (guess-encoding #f))
1593 "Takes a string naming an existing file and returns an input port
1594 capable of delivering characters from the file. If the file
1595 cannot be opened, an error is signalled."
1596 (open-file file (if binary "rb" "r")
1598 #:guess-encoding guess-encoding))
1600 (define* (open-output-file file #:key (binary #f) (encoding #f))
1601 "Takes a string naming an output file to be created and returns an
1602 output port capable of writing characters to a new file by that
1603 name. If the file cannot be opened, an error is signalled. If a
1604 file with the given name already exists, the effect is unspecified."
1605 (open-file file (if binary "wb" "w")
1606 #:encoding encoding))
1608 (define* (call-with-input-file
1609 file proc #:key (binary #f) (encoding #f) (guess-encoding #f))
1610 "PROC should be a procedure of one argument, and FILE should be a
1611 string naming a file. The file must
1612 already exist. These procedures call PROC
1613 with one argument: the port obtained by opening the named file for
1614 input or output. If the file cannot be opened, an error is
1615 signalled. If the procedure returns, then the port is closed
1616 automatically and the values yielded by the procedure are returned.
1617 If the procedure does not return, then the port will not be closed
1618 automatically unless it is possible to prove that the port will
1619 never again be used for a read or write operation."
1620 (let ((p (open-input-file file
1623 #:guess-encoding guess-encoding)))
1625 (lambda () (proc p))
1627 (close-input-port p)
1628 (apply values vals)))))
1630 (define* (call-with-output-file file proc #:key (binary #f) (encoding #f))
1631 "PROC should be a procedure of one argument, and FILE should be a
1632 string naming a file. The behaviour is unspecified if the file
1633 already exists. These procedures call PROC
1634 with one argument: the port obtained by opening the named file for
1635 input or output. If the file cannot be opened, an error is
1636 signalled. If the procedure returns, then the port is closed
1637 automatically and the values yielded by the procedure are returned.
1638 If the procedure does not return, then the port will not be closed
1639 automatically unless it is possible to prove that the port will
1640 never again be used for a read or write operation."
1641 (let ((p (open-output-file file #:binary binary #:encoding encoding)))
1643 (lambda () (proc p))
1645 (close-output-port p)
1646 (apply values vals)))))
1648 (define (with-input-from-port port thunk)
1649 (parameterize ((current-input-port port))
1652 (define (with-output-to-port port thunk)
1653 (parameterize ((current-output-port port))
1656 (define (with-error-to-port port thunk)
1657 (parameterize ((current-error-port port))
1660 (define* (with-input-from-file
1661 file thunk #:key (binary #f) (encoding #f) (guess-encoding #f))
1662 "THUNK must be a procedure of no arguments, and FILE must be a
1663 string naming a file. The file must already exist. The file is opened for
1664 input, an input port connected to it is made
1665 the default value returned by `current-input-port',
1666 and the THUNK is called with no arguments.
1667 When the THUNK returns, the port is closed and the previous
1668 default is restored. Returns the values yielded by THUNK. If an
1669 escape procedure is used to escape from the continuation of these
1670 procedures, their behavior is implementation dependent."
1671 (call-with-input-file file
1672 (lambda (p) (with-input-from-port p thunk))
1675 #:guess-encoding guess-encoding))
1677 (define* (with-output-to-file file thunk #:key (binary #f) (encoding #f))
1678 "THUNK must be a procedure of no arguments, and FILE must be a
1679 string naming a file. The effect is unspecified if the file already exists.
1680 The file is opened for output, an output port connected to it is made
1681 the default value returned by `current-output-port',
1682 and the THUNK is called with no arguments.
1683 When the THUNK returns, the port is closed and the previous
1684 default is restored. Returns the values yielded by THUNK. If an
1685 escape procedure is used to escape from the continuation of these
1686 procedures, their behavior is implementation dependent."
1687 (call-with-output-file file
1688 (lambda (p) (with-output-to-port p thunk))
1690 #:encoding encoding))
1692 (define* (with-error-to-file file thunk #:key (binary #f) (encoding #f))
1693 "THUNK must be a procedure of no arguments, and FILE must be a
1694 string naming a file. The effect is unspecified if the file already exists.
1695 The file is opened for output, an output port connected to it is made
1696 the default value returned by `current-error-port',
1697 and the THUNK is called with no arguments.
1698 When the THUNK returns, the port is closed and the previous
1699 default is restored. Returns the values yielded by THUNK. If an
1700 escape procedure is used to escape from the continuation of these
1701 procedures, their behavior is implementation dependent."
1702 (call-with-output-file file
1703 (lambda (p) (with-error-to-port p thunk))
1705 #:encoding encoding))
1707 (define (call-with-input-string string proc)
1708 "Calls the one-argument procedure @var{proc} with a newly created
1709 input port from which @var{string}'s contents may be read. The value
1710 yielded by the @var{proc} is returned."
1711 (proc (open-input-string string)))
1713 (define (with-input-from-string string thunk)
1714 "THUNK must be a procedure of no arguments.
1715 The test of STRING is opened for
1716 input, an input port connected to it is made,
1717 and the THUNK is called with no arguments.
1718 When the THUNK returns, the port is closed.
1719 Returns the values yielded by THUNK. If an
1720 escape procedure is used to escape from the continuation of these
1721 procedures, their behavior is implementation dependent."
1722 (call-with-input-string string
1723 (lambda (p) (with-input-from-port p thunk))))
1725 (define (call-with-output-string proc)
1726 "Calls the one-argument procedure @var{proc} with a newly created output
1727 port. When the function returns, the string composed of the characters
1728 written into the port is returned."
1729 (let ((port (open-output-string)))
1731 (get-output-string port)))
1733 (define (with-output-to-string thunk)
1734 "Calls THUNK and returns its output as a string."
1735 (call-with-output-string
1736 (lambda (p) (with-output-to-port p thunk))))
1738 (define (with-error-to-string thunk)
1739 "Calls THUNK and returns its error output as a string."
1740 (call-with-output-string
1741 (lambda (p) (with-error-to-port p thunk))))
1743 (define the-eof-object (call-with-input-string "" (lambda (p) (read-char p))))
1750 (define (->bool x) (not (not x)))
1757 (define (symbol-append . args)
1758 (string->symbol (apply string-append (map symbol->string args))))
1760 (define (list->symbol . args)
1761 (string->symbol (apply list->string args)))
1763 (define (symbol . args)
1764 (string->symbol (apply string args)))
1771 (define (list-index l k)
1774 (and (not (null? l))
1777 (loop (+ n 1) (cdr l))))))
1781 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1782 ;; `stat' accessors.
1783 (primitive-load-path "ice-9/posix")
1785 (if (provided? 'socket)
1786 (primitive-load-path "ice-9/networking"))
1788 ;; For reference, Emacs file-exists-p uses stat in this same way.
1789 (define file-exists?
1790 (if (provided? 'posix)
1792 (->bool (stat str #f)))
1794 (let ((port (catch 'system-error (lambda () (open-input-file str))
1796 (if port (begin (close-port port) #t)
1799 (define file-is-directory?
1800 (if (provided? 'posix)
1802 (eq? (stat:type (stat str)) 'directory))
1804 (let ((port (catch 'system-error
1806 (open-input-file (string-append str "/.")))
1808 (if port (begin (close-port port) #t)
1811 (define (system-error-errno args)
1812 (if (eq? (car args) 'system-error)
1813 (car (list-ref args 4))
1818 ;;; {Error Handling}
1824 (scm-error 'misc-error #f "?" #f #f))
1826 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1827 (scm-error 'misc-error #f msg (cons message args) #f)))))
1831 ;;; {Time Structures}
1834 (define (tm:sec obj) (vector-ref obj 0))
1835 (define (tm:min obj) (vector-ref obj 1))
1836 (define (tm:hour obj) (vector-ref obj 2))
1837 (define (tm:mday obj) (vector-ref obj 3))
1838 (define (tm:mon obj) (vector-ref obj 4))
1839 (define (tm:year obj) (vector-ref obj 5))
1840 (define (tm:wday obj) (vector-ref obj 6))
1841 (define (tm:yday obj) (vector-ref obj 7))
1842 (define (tm:isdst obj) (vector-ref obj 8))
1843 (define (tm:gmtoff obj) (vector-ref obj 9))
1844 (define (tm:zone obj) (vector-ref obj 10))
1846 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1847 (define (set-tm:min obj val) (vector-set! obj 1 val))
1848 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1849 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1850 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1851 (define (set-tm:year obj val) (vector-set! obj 5 val))
1852 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1853 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1854 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1855 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1856 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1858 (define (tms:clock obj) (vector-ref obj 0))
1859 (define (tms:utime obj) (vector-ref obj 1))
1860 (define (tms:stime obj) (vector-ref obj 2))
1861 (define (tms:cutime obj) (vector-ref obj 3))
1862 (define (tms:cstime obj) (vector-ref obj 4))
1866 ;;; {File Descriptors and Ports}
1869 (define file-position ftell)
1870 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1871 (seek port offset whence))
1873 (define (move->fdes fd/port fd)
1874 (cond ((integer? fd/port)
1875 (dup->fdes fd/port fd)
1879 (primitive-move->fdes fd/port fd)
1880 (set-port-revealed! fd/port 1)
1883 (define (release-port-handle port)
1884 (let ((revealed (port-revealed port)))
1886 (set-port-revealed! port (- revealed 1)))))
1891 (fdopen (dup->fdes port/fd) mode))
1892 ((port/fd mode new-fd)
1893 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1894 (set-port-revealed! port 1)
1900 (dup->port port/fd "r"))
1902 (dup->port port/fd "r" new-fd))))
1904 (define dup->outport
1907 (dup->port port/fd "w"))
1909 (dup->port port/fd "w" new-fd))))
1914 (if (integer? port/fd)
1916 (dup->port port/fd (port-mode port/fd))))
1918 (if (integer? port/fd)
1919 (dup->fdes port/fd new-fd)
1920 (dup->port port/fd (port-mode port/fd) new-fd)))))
1922 (define (duplicate-port port modes)
1923 (dup->port port modes))
1925 (define (fdes->inport fdes)
1926 (let loop ((rest-ports (fdes->ports fdes)))
1927 (cond ((null? rest-ports)
1928 (let ((result (fdopen fdes "r")))
1929 (set-port-revealed! result 1)
1931 ((input-port? (car rest-ports))
1932 (set-port-revealed! (car rest-ports)
1933 (+ (port-revealed (car rest-ports)) 1))
1936 (loop (cdr rest-ports))))))
1938 (define (fdes->outport fdes)
1939 (let loop ((rest-ports (fdes->ports fdes)))
1940 (cond ((null? rest-ports)
1941 (let ((result (fdopen fdes "w")))
1942 (set-port-revealed! result 1)
1944 ((output-port? (car rest-ports))
1945 (set-port-revealed! (car rest-ports)
1946 (+ (port-revealed (car rest-ports)) 1))
1949 (loop (cdr rest-ports))))))
1951 (define (port->fdes port)
1952 (set-port-revealed! port (+ (port-revealed port) 1))
1955 (define (setenv name value)
1957 (putenv (string-append name "=" value))
1960 (define (unsetenv name)
1961 "Remove the entry for NAME from the environment."
1969 (let-syntax ((compile-time-case
1972 ((_ exp clauses ...)
1973 (let ((val (primitive-eval (syntax->datum #'exp))))
1974 (let next-clause ((clauses #'(clauses ...)))
1975 (syntax-case clauses (else)
1977 (syntax-violation 'compile-time-case
1978 "all clauses failed to match" stx))
1981 ((((k ...) form ...) clauses ...)
1982 (if (memv val (syntax->datum #'(k ...)))
1984 (next-clause #'(clauses ...))))))))))))
1985 ;; emacs: (put 'compile-time-case 'scheme-indent-function 1)
1986 (compile-time-case (system-file-name-convention)
1988 (define (file-name-separator? c)
1991 (define file-name-separator-string "/")
1993 (define (absolute-file-name? file-name)
1994 (string-prefix? "/" file-name)))
1997 (define (file-name-separator? c)
2001 (define file-name-separator-string "\\")
2003 (define (absolute-file-name? file-name)
2004 (define (file-name-separator-at-index? idx)
2005 (and (> (string-length file-name) idx)
2006 (file-name-separator? (string-ref file-name idx))))
2007 (define (unc-file-name?)
2008 ;; Universal Naming Convention (UNC) file-names start with \\,
2009 ;; and are always absolute. See:
2010 ;; http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
2011 (and (file-name-separator-at-index? 0)
2012 (file-name-separator-at-index? 1)))
2013 (define (has-drive-specifier?)
2014 (and (>= (string-length file-name) 2)
2015 (let ((drive (string-ref file-name 0)))
2016 (or (char<=? #\a drive #\z)
2017 (char<=? #\A drive #\Z)))
2018 (eqv? (string-ref file-name 1) #\:)))
2019 (or (unc-file-name?)
2020 (if (has-drive-specifier?)
2021 (file-name-separator-at-index? 2)
2022 (file-name-separator-at-index? 0)))))))
2024 (define (in-vicinity vicinity file)
2025 (let ((tail (let ((len (string-length vicinity)))
2028 (string-ref vicinity (- len 1))))))
2029 (string-append vicinity
2030 (if (or (not tail) (file-name-separator? tail))
2032 file-name-separator-string)
2037 ;;; {Help for scm_shell}
2039 ;;; The argument-processing code used by Guile-based shells generates
2040 ;;; Scheme code based on the argument list. This page contains help
2041 ;;; functions for the code it generates.
2044 (define (command-line) (program-arguments))
2046 ;; This is mostly for the internal use of the code generated by
2047 ;; scm_compile_shell_switches.
2049 (define (load-user-init)
2050 (let* ((home (or (getenv "HOME")
2051 (false-if-exception (passwd:dir (getpwuid (getuid))))
2052 file-name-separator-string)) ;; fallback for cygwin etc.
2053 (init-file (in-vicinity home ".guile")))
2054 (if (file-exists? init-file)
2055 (primitive-load init-file))))
2059 ;;; {The interpreter stack}
2062 ;; %stacks defined in stacks.c
2063 (define (%start-stack tag thunk)
2064 (let ((prompt-tag (make-prompt-tag "start-stack")))
2068 (with-fluids ((%stacks (acons tag prompt-tag
2069 (or (fluid-ref %stacks) '()))))
2072 (%start-stack tag (lambda () (apply k args)))))))
2074 (define-syntax-rule (start-stack tag exp)
2075 (%start-stack tag (lambda () exp)))
2079 ;;; {Loading by paths}
2082 ;;; Load a Scheme source file named NAME, searching for it in the
2083 ;;; directories listed in %load-path, and applying each of the file
2084 ;;; name extensions listed in %load-extensions.
2085 (define (load-from-path name)
2086 (start-stack 'load-stack
2087 (primitive-load-path name)))
2089 (define-syntax-rule (add-to-load-path elt)
2090 "Add ELT to Guile's load path, at compile-time and at run-time."
2091 (eval-when (expand load eval)
2092 (set! %load-path (cons elt %load-path))))
2094 (define %load-verbosely #f)
2095 (define (assert-load-verbosity v) (set! %load-verbosely v))
2097 (define (%load-announce file)
2099 (with-output-to-port (current-warning-port)
2102 (display "loading ")
2107 (set! %load-hook %load-announce)
2111 ;;; {Reader Extensions}
2113 ;;; Reader code for various "#c" forms.
2116 (define read-eval? (make-fluid #f))
2117 (read-hash-extend #\.
2119 (if (fluid-ref read-eval?)
2120 (eval (read port) (interaction-environment))
2122 "#. read expansion found and read-eval? is #f."))))
2126 ;;; {Low Level Modules}
2128 ;;; These are the low level data structures for modules.
2130 ;;; Every module object is of the type 'module-type', which is a record
2131 ;;; consisting of the following members:
2133 ;;; - eval-closure: A deprecated field, to be removed in Guile 2.2.
2135 ;;; - obarray: a hash table that maps symbols to variable objects. In this
2136 ;;; hash table, the definitions are found that are local to the module (that
2137 ;;; is, not imported from other modules). When looking up bindings in the
2138 ;;; module, this hash table is searched first.
2140 ;;; - binder: either #f or a function taking a module and a symbol argument.
2141 ;;; If it is a function it is called after the obarray has been
2142 ;;; unsuccessfully searched for a binding. It then can provide bindings
2143 ;;; that would otherwise not be found locally in the module.
2145 ;;; - uses: a list of modules from which non-local bindings can be inherited.
2146 ;;; These modules are the third place queried for bindings after the obarray
2147 ;;; has been unsuccessfully searched and the binder function did not deliver
2148 ;;; a result either.
2150 ;;; - transformer: either #f or a function taking a scheme expression as
2151 ;;; delivered by read. If it is a function, it will be called to perform
2152 ;;; syntax transformations (e. g. makro expansion) on the given scheme
2153 ;;; expression. The output of the transformer function will then be passed
2154 ;;; to Guile's internal memoizer. This means that the output must be valid
2155 ;;; scheme code. The only exception is, that the output may make use of the
2156 ;;; syntax extensions provided to identify the modules that a binding
2159 ;;; - name: the name of the module. This is used for all kinds of printing
2160 ;;; outputs. In certain places the module name also serves as a way of
2161 ;;; identification. When adding a module to the uses list of another
2162 ;;; module, it is made sure that the new uses list will not contain two
2163 ;;; modules of the same name.
2165 ;;; - kind: classification of the kind of module. The value is (currently?)
2166 ;;; only used for printing. It has no influence on how a module is treated.
2167 ;;; Currently the following values are used when setting the module kind:
2168 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
2169 ;;; is set, it defaults to 'module.
2171 ;;; - duplicates-handlers: a list of procedures that get called to make a
2172 ;;; choice between two duplicate bindings when name clashes occur. See the
2173 ;;; `duplicate-handlers' global variable below.
2175 ;;; - observers: a list of procedures that get called when the module is
2178 ;;; - weak-observers: a weak-key hash table of procedures that get called
2179 ;;; when the module is modified. See `module-observe-weak' for details.
2181 ;;; In addition, the module may (must?) contain a binding for
2182 ;;; `%module-public-interface'. This variable should be bound to a module
2183 ;;; representing the exported interface of a module. See the
2184 ;;; `module-public-interface' and `module-export!' procedures.
2186 ;;; !!! warning: The interface to lazy binder procedures is going
2187 ;;; to be changed in an incompatible way to permit all the basic
2188 ;;; module ops to be virtualized.
2190 ;;; (make-module size use-list lazy-binding-proc) => module
2191 ;;; module-{obarray,uses,binder}[|-set!]
2192 ;;; (module? obj) => [#t|#f]
2193 ;;; (module-locally-bound? module symbol) => [#t|#f]
2194 ;;; (module-bound? module symbol) => [#t|#f]
2195 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
2196 ;;; (module-symbol-interned? module symbol) => [#t|#f]
2197 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
2198 ;;; (module-variable module symbol) => [#<variable ...> | #f]
2199 ;;; (module-symbol-binding module symbol opt-value)
2200 ;;; => [ <obj> | opt-value | an error occurs ]
2201 ;;; (module-make-local-var! module symbol) => #<variable...>
2202 ;;; (module-add! module symbol var) => unspecified
2203 ;;; (module-remove! module symbol) => unspecified
2204 ;;; (module-for-each proc module) => unspecified
2205 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
2206 ;;; (set-current-module module) => unspecified
2207 ;;; (current-module) => #<module...>
2213 ;;; {Printing Modules}
2216 ;; This is how modules are printed. You can re-define it.
2217 (define (%print-module mod port)
2219 (display (or (module-kind mod) "module") port)
2221 (display (module-name mod) port)
2223 (display (number->string (object-address mod) 16) port)
2227 ;; Locally extend the syntax to allow record accessors to be defined at
2228 ;; compile-time. Cache the rtd locally to the constructor, the getters and
2229 ;; the setters, in order to allow for redefinition of the record type; not
2230 ;; relevant in the case of modules, but perhaps if we make this public, it
2233 ((define-record-type
2235 (define (make-id scope . fragments)
2236 (datum->syntax scope
2237 (apply symbol-append
2239 (if (symbol? x) x (syntax->datum x)))
2242 (define (getter rtd type-name field slot)
2243 #`(define #,(make-id rtd type-name '- field)
2245 (lambda (#,type-name)
2246 (if (eq? (struct-vtable #,type-name) rtd)
2247 (struct-ref #,type-name #,slot)
2248 (%record-type-error rtd #,type-name))))))
2250 (define (setter rtd type-name field slot)
2251 #`(define #,(make-id rtd 'set- type-name '- field '!)
2253 (lambda (#,type-name val)
2254 (if (eq? (struct-vtable #,type-name) rtd)
2255 (struct-set! #,type-name #,slot val)
2256 (%record-type-error rtd #,type-name))))))
2258 (define (accessors rtd type-name fields n exp)
2259 (syntax-case fields ()
2261 (((field #:no-accessors) field* ...) (identifier? #'field)
2262 (accessors rtd type-name #'(field* ...) (1+ n)
2264 (((field #:no-setter) field* ...) (identifier? #'field)
2265 (accessors rtd type-name #'(field* ...) (1+ n)
2267 #,(getter rtd type-name #'field n))))
2268 (((field #:no-getter) field* ...) (identifier? #'field)
2269 (accessors rtd type-name #'(field* ...) (1+ n)
2271 #,(setter rtd type-name #'field n))))
2272 ((field field* ...) (identifier? #'field)
2273 (accessors rtd type-name #'(field* ...) (1+ n)
2275 #,(getter rtd type-name #'field n)
2276 #,(setter rtd type-name #'field n))))))
2278 (define (predicate rtd type-name fields exp)
2280 rtd type-name fields 0
2283 (define (#,(make-id rtd type-name '?) obj)
2284 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
2286 (define (field-list fields)
2287 (syntax-case fields ()
2289 (((f . opts) . rest) (identifier? #'f)
2290 (cons #'f (field-list #'rest)))
2291 ((f . rest) (identifier? #'f)
2292 (cons #'f (field-list #'rest)))))
2294 (define (constructor rtd type-name fields exp)
2295 (let* ((ctor (make-id rtd type-name '-constructor))
2296 (args (field-list fields))
2299 (predicate rtd type-name fields
2304 (let ((s (allocate-struct rtd #,n)))
2307 #`(struct-set! s #,slot #,arg))
2310 (struct-set! #,rtd (+ vtable-offset-user 2)
2313 (define (type type-name printer fields)
2314 (define (make-layout)
2315 (let lp ((fields fields) (slots '()))
2316 (syntax-case fields ()
2317 (() (datum->syntax #'here
2319 (apply string-append slots))))
2320 ((_ . rest) (lp #'rest (cons "pw" slots))))))
2322 (let ((rtd (make-id type-name type-name '-type)))
2323 (constructor rtd type-name fields
2326 (make-struct record-type-vtable 0
2330 '#,(field-list fields)))
2331 (set-struct-vtable-name! #,rtd '#,type-name)))))
2334 ((_ type-name printer (field ...))
2335 (type #'type-name #'printer #'(field ...)))))))
2339 ;; A module is characterized by an obarray in which local symbols
2340 ;; are interned, a list of modules, "uses", from which non-local
2341 ;; bindings can be inherited, and an optional lazy-binder which
2342 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
2343 ;; bindings that would otherwise not be found locally in the module.
2345 ;; NOTE: If you change the set of fields or their order, you also need to
2346 ;; change the constants in libguile/modules.h.
2348 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
2349 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
2350 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
2352 (define-record-type module
2353 (lambda (obj port) (%print-module obj port))
2358 (transformer #:no-getter)
2362 (import-obarray #:no-setter)
2364 (weak-observers #:no-setter)
2372 ;; make-module &opt size uses binder
2374 ;; Create a new module, perhaps with a particular size of obarray,
2375 ;; initial uses list, or binding procedure.
2377 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
2378 (if (not (integer? size))
2379 (error "Illegal size to make-module." size))
2380 (if (not (and (list? uses)
2381 (and-map module? uses)))
2382 (error "Incorrect use list." uses))
2383 (if (and binder (not (procedure? binder)))
2385 "Lazy-binder expected to be a procedure or #f." binder))
2387 (module-constructor (make-hash-table size)
2388 uses binder #f macroexpand
2392 (make-weak-key-hash-table 31) #f
2393 (make-hash-table 7) #f #f #f))
2398 ;;; {Observer protocol}
2401 (define (module-observe module proc)
2402 (set-module-observers! module (cons proc (module-observers module)))
2405 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
2406 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
2407 ;; be any Scheme object). PROC is invoked and passed MODULE any time
2408 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
2409 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
2412 ;; The two-argument version is kept for backward compatibility: when called
2413 ;; with two arguments, the observer gets unregistered when closure PROC
2414 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
2415 (hashq-set! (module-weak-observers module) observer-id proc))
2417 (define (module-unobserve token)
2418 (let ((module (car token))
2421 (hash-remove! (module-weak-observers module) id)
2422 (set-module-observers! module (delq1! id (module-observers module)))))
2425 (define module-defer-observers #f)
2426 (define module-defer-observers-mutex (make-mutex 'recursive))
2427 (define module-defer-observers-table (make-hash-table))
2429 (define (module-modified m)
2430 (if module-defer-observers
2431 (hash-set! module-defer-observers-table m #t)
2432 (module-call-observers m)))
2434 ;;; This function can be used to delay calls to observers so that they
2435 ;;; can be called once only in the face of massive updating of modules.
2437 (define (call-with-deferred-observers thunk)
2440 (lock-mutex module-defer-observers-mutex)
2441 (set! module-defer-observers #t))
2444 (set! module-defer-observers #f)
2445 (hash-for-each (lambda (m dummy)
2446 (module-call-observers m))
2447 module-defer-observers-table)
2448 (hash-clear! module-defer-observers-table)
2449 (unlock-mutex module-defer-observers-mutex))))
2451 (define (module-call-observers m)
2452 (for-each (lambda (proc) (proc m)) (module-observers m))
2454 ;; We assume that weak observers don't (un)register themselves as they are
2455 ;; called since this would preclude proper iteration over the hash table
2457 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
2461 ;;; {Module Searching in General}
2463 ;;; We sometimes want to look for properties of a symbol
2464 ;;; just within the obarray of one module. If the property
2465 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
2466 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
2469 ;;; Other times, we want to test for a symbol property in the obarray
2470 ;;; of M and, if it is not found there, try each of the modules in the
2471 ;;; uses list of M. This is the normal way of testing for some
2472 ;;; property, so we state these properties without qualification as
2473 ;;; in: ``The symbol 'fnord is interned in module M because it is
2474 ;;; interned locally in module M2 which is a member of the uses list
2478 ;; module-search fn m
2480 ;; return the first non-#f result of FN applied to M and then to
2481 ;; the modules in the uses of m, and so on recursively. If all applications
2482 ;; return #f, then so does this function.
2484 (define (module-search fn m v)
2487 (or (module-search fn (car pos) v)
2490 (loop (module-uses m))))
2493 ;;; {Is a symbol bound in a module?}
2495 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
2496 ;;; of S in M has been set to some well-defined value.
2499 ;; module-locally-bound? module symbol
2501 ;; Is a symbol bound (interned and defined) locally in a given module?
2503 (define (module-locally-bound? m v)
2504 (let ((var (module-local-variable m v)))
2506 (variable-bound? var))))
2508 ;; module-bound? module symbol
2510 ;; Is a symbol bound (interned and defined) anywhere in a given module
2513 (define (module-bound? m v)
2514 (let ((var (module-variable m v)))
2516 (variable-bound? var))))
2518 ;;; {Is a symbol interned in a module?}
2520 ;;; Symbol S in Module M is interned if S occurs in
2521 ;;; of S in M has been set to some well-defined value.
2523 ;;; It is possible to intern a symbol in a module without providing
2524 ;;; an initial binding for the corresponding variable. This is done
2526 ;;; (module-add! module symbol (make-undefined-variable))
2528 ;;; In that case, the symbol is interned in the module, but not
2529 ;;; bound there. The unbound symbol shadows any binding for that
2530 ;;; symbol that might otherwise be inherited from a member of the uses list.
2533 (define (module-obarray-get-handle ob key)
2534 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
2536 (define (module-obarray-ref ob key)
2537 ((if (symbol? key) hashq-ref hash-ref) ob key))
2539 (define (module-obarray-set! ob key val)
2540 ((if (symbol? key) hashq-set! hash-set!) ob key val))
2542 (define (module-obarray-remove! ob key)
2543 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
2545 ;; module-symbol-locally-interned? module symbol
2547 ;; is a symbol interned (not neccessarily defined) locally in a given module
2548 ;; or its uses? Interned symbols shadow inherited bindings even if
2549 ;; they are not themselves bound to a defined value.
2551 (define (module-symbol-locally-interned? m v)
2552 (not (not (module-obarray-get-handle (module-obarray m) v))))
2554 ;; module-symbol-interned? module symbol
2556 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
2557 ;; or its uses? Interned symbols shadow inherited bindings even if
2558 ;; they are not themselves bound to a defined value.
2560 (define (module-symbol-interned? m v)
2561 (module-search module-symbol-locally-interned? m v))
2564 ;;; {Mapping modules x symbols --> variables}
2567 ;; module-local-variable module symbol
2568 ;; return the local variable associated with a MODULE and SYMBOL.
2570 ;;; This function is very important. It is the only function that can
2571 ;;; return a variable from a module other than the mutators that store
2572 ;;; new variables in modules. Therefore, this function is the location
2573 ;;; of the "lazy binder" hack.
2575 ;;; If symbol is defined in MODULE, and if the definition binds symbol
2576 ;;; to a variable, return that variable object.
2578 ;;; If the symbols is not found at first, but the module has a lazy binder,
2579 ;;; then try the binder.
2581 ;;; If the symbol is not found at all, return #f.
2583 ;;; (This is now written in C, see `modules.c'.)
2586 ;;; {Mapping modules x symbols --> bindings}
2588 ;;; These are similar to the mapping to variables, except that the
2589 ;;; variable is dereferenced.
2592 ;; module-symbol-binding module symbol opt-value
2594 ;; return the binding of a variable specified by name within
2595 ;; a given module, signalling an error if the variable is unbound.
2596 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2597 ;; return OPT-VALUE.
2599 (define (module-symbol-local-binding m v . opt-val)
2600 (let ((var (module-local-variable m v)))
2601 (if (and var (variable-bound? var))
2603 (if (not (null? opt-val))
2605 (error "Locally unbound variable." v)))))
2607 ;; module-symbol-binding module symbol opt-value
2609 ;; return the binding of a variable specified by name within
2610 ;; a given module, signalling an error if the variable is unbound.
2611 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2612 ;; return OPT-VALUE.
2614 (define (module-symbol-binding m v . opt-val)
2615 (let ((var (module-variable m v)))
2616 (if (and var (variable-bound? var))
2618 (if (not (null? opt-val))
2620 (error "Unbound variable." v)))))
2625 ;;; {Adding Variables to Modules}
2628 ;; module-make-local-var! module symbol
2630 ;; ensure a variable for V in the local namespace of M.
2631 ;; If no variable was already there, then create a new and uninitialzied
2634 ;; This function is used in modules.c.
2636 (define (module-make-local-var! m v)
2637 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2640 ;; Mark as modified since this function is called when
2641 ;; the standard eval closure defines a binding
2645 ;; Create a new local variable.
2646 (let ((local-var (make-undefined-variable)))
2647 (module-add! m v local-var)
2650 ;; module-ensure-local-variable! module symbol
2652 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2653 ;; there is no binding for SYMBOL, create a new uninitialized
2654 ;; variable. Return the local variable.
2656 (define (module-ensure-local-variable! module symbol)
2657 (or (module-local-variable module symbol)
2658 (let ((var (make-undefined-variable)))
2659 (module-add! module symbol var)
2662 ;; module-add! module symbol var
2664 ;; ensure a particular variable for V in the local namespace of M.
2666 (define (module-add! m v var)
2667 (if (not (variable? var))
2668 (error "Bad variable to module-add!" var))
2669 (if (not (symbol? v))
2670 (error "Bad symbol to module-add!" v))
2671 (module-obarray-set! (module-obarray m) v var)
2672 (module-modified m))
2676 ;; make sure that a symbol is undefined in the local namespace of M.
2678 (define (module-remove! m v)
2679 (module-obarray-remove! (module-obarray m) v)
2680 (module-modified m))
2682 (define (module-clear! m)
2683 (hash-clear! (module-obarray m))
2684 (module-modified m))
2686 ;; MODULE-FOR-EACH -- exported
2688 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2690 (define (module-for-each proc module)
2691 (hash-for-each proc (module-obarray module)))
2693 (define (module-map proc module)
2694 (hash-map->list proc (module-obarray module)))
2698 ;; Modules exist in a separate namespace from values, because you generally do
2699 ;; not want the name of a submodule, which you might not even use, to collide
2700 ;; with local variables that happen to be named the same as the submodule.
2702 (define (module-ref-submodule module name)
2703 (or (hashq-ref (module-submodules module) name)
2704 (and (module-submodule-binder module)
2705 ((module-submodule-binder module) module name))))
2707 (define (module-define-submodule! module name submodule)
2708 (hashq-set! (module-submodules module) name submodule))
2712 ;;; {Module-based Loading}
2715 (define (save-module-excursion thunk)
2716 (let ((inner-module (current-module))
2718 (dynamic-wind (lambda ()
2719 (set! outer-module (current-module))
2720 (set-current-module inner-module)
2721 (set! inner-module #f))
2724 (set! inner-module (current-module))
2725 (set-current-module outer-module)
2726 (set! outer-module #f)))))
2730 ;;; {MODULE-REF -- exported}
2733 ;; Returns the value of a variable called NAME in MODULE or any of its
2734 ;; used modules. If there is no such variable, then if the optional third
2735 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2737 (define (module-ref module name . rest)
2738 (let ((variable (module-variable module name)))
2739 (if (and variable (variable-bound? variable))
2740 (variable-ref variable)
2742 (error "No variable named" name 'in module)
2743 (car rest) ; default value
2746 ;; MODULE-SET! -- exported
2748 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2749 ;; to VALUE; if there is no such variable, an error is signaled.
2751 (define (module-set! module name value)
2752 (let ((variable (module-variable module name)))
2754 (variable-set! variable value)
2755 (error "No variable named" name 'in module))))
2757 ;; MODULE-DEFINE! -- exported
2759 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2760 ;; variable, it is added first.
2762 (define (module-define! module name value)
2763 (let ((variable (module-local-variable module name)))
2766 (variable-set! variable value)
2767 (module-modified module))
2768 (let ((variable (make-variable value)))
2769 (module-add! module name variable)))))
2771 ;; MODULE-DEFINED? -- exported
2773 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2776 (define (module-defined? module name)
2777 (let ((variable (module-variable module name)))
2778 (and variable (variable-bound? variable))))
2780 ;; MODULE-USE! module interface
2782 ;; Add INTERFACE to the list of interfaces used by MODULE.
2784 (define (module-use! module interface)
2785 (if (not (or (eq? module interface)
2786 (memq interface (module-uses module))))
2788 ;; Newly used modules must be appended rather than consed, so that
2789 ;; `module-variable' traverses the use list starting from the first
2791 (set-module-uses! module (append (module-uses module)
2793 (hash-clear! (module-import-obarray module))
2794 (module-modified module))))
2796 ;; MODULE-USE-INTERFACES! module interfaces
2798 ;; Same as MODULE-USE!, but only notifies module observers after all
2799 ;; interfaces are added to the inports list.
2801 (define (module-use-interfaces! module interfaces)
2802 (let* ((cur (module-uses module))
2803 (new (let lp ((in interfaces) (out '()))
2807 (let ((iface (car in)))
2808 (if (or (memq iface cur) (memq iface out))
2810 (cons iface out))))))))
2811 (set-module-uses! module (append cur new))
2812 (hash-clear! (module-import-obarray module))
2813 (module-modified module)))
2817 ;;; {Recursive Namespaces}
2819 ;;; A hierarchical namespace emerges if we consider some module to be
2820 ;;; root, and submodules of that module to be nested namespaces.
2822 ;;; The routines here manage variable names in hierarchical namespace.
2823 ;;; Each variable name is a list of elements, looked up in successively nested
2826 ;;; (nested-ref some-root-module '(foo bar baz))
2827 ;;; => <value of a variable named baz in the submodule bar of
2828 ;;; the submodule foo of some-root-module>
2833 ;;; ;; a-root is a module
2834 ;;; ;; name is a list of symbols
2836 ;;; nested-ref a-root name
2837 ;;; nested-set! a-root name val
2838 ;;; nested-define! a-root name val
2839 ;;; nested-remove! a-root name
2841 ;;; These functions manipulate values in namespaces. For referencing the
2842 ;;; namespaces themselves, use the following:
2844 ;;; nested-ref-module a-root name
2845 ;;; nested-define-module! a-root name mod
2847 ;;; (current-module) is a natural choice for a root so for convenience there are
2850 ;;; local-ref name == nested-ref (current-module) name
2851 ;;; local-set! name val == nested-set! (current-module) name val
2852 ;;; local-define name val == nested-define! (current-module) name val
2853 ;;; local-remove name == nested-remove! (current-module) name
2854 ;;; local-ref-module name == nested-ref-module (current-module) name
2855 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2859 (define (nested-ref root names)
2862 (let loop ((cur root)
2866 (module-ref cur head #f)
2867 (let ((cur (module-ref-submodule cur head)))
2869 (loop cur (car tail) (cdr tail))))))))
2871 (define (nested-set! root names val)
2872 (let loop ((cur root)
2876 (module-set! cur head val)
2877 (let ((cur (module-ref-submodule cur head)))
2879 (error "failed to resolve module" names)
2880 (loop cur (car tail) (cdr tail)))))))
2882 (define (nested-define! root names val)
2883 (let loop ((cur root)
2887 (module-define! cur head val)
2888 (let ((cur (module-ref-submodule cur head)))
2890 (error "failed to resolve module" names)
2891 (loop cur (car tail) (cdr tail)))))))
2893 (define (nested-remove! root names)
2894 (let loop ((cur root)
2898 (module-remove! cur head)
2899 (let ((cur (module-ref-submodule cur head)))
2901 (error "failed to resolve module" names)
2902 (loop cur (car tail) (cdr tail)))))))
2905 (define (nested-ref-module root names)
2906 (let loop ((cur root)
2910 (let ((cur (module-ref-submodule cur (car names))))
2912 (loop cur (cdr names)))))))
2914 (define (nested-define-module! root names module)
2916 (error "can't redefine root module" root module)
2917 (let loop ((cur root)
2921 (module-define-submodule! cur head module)
2922 (let ((cur (or (module-ref-submodule cur head)
2923 (let ((m (make-module 31)))
2924 (set-module-kind! m 'directory)
2925 (set-module-name! m (append (module-name cur)
2927 (module-define-submodule! cur head m)
2929 (loop cur (car tail) (cdr tail)))))))
2932 (define (local-ref names)
2933 (nested-ref (current-module) names))
2935 (define (local-set! names val)
2936 (nested-set! (current-module) names val))
2938 (define (local-define names val)
2939 (nested-define! (current-module) names val))
2941 (define (local-remove names)
2942 (nested-remove! (current-module) names))
2944 (define (local-ref-module names)
2945 (nested-ref-module (current-module) names))
2947 (define (local-define-module names mod)
2948 (nested-define-module! (current-module) names mod))
2954 ;;; {The (guile) module}
2956 ;;; The standard module, which has the core Guile bindings. Also called the
2957 ;;; "root module", as it is imported by many other modules, but it is not
2958 ;;; necessarily the root of anything; and indeed, the module named '() might be
2959 ;;; better thought of as a root.
2962 ;; The root module uses the pre-modules-obarray as its obarray. This
2963 ;; special obarray accumulates all bindings that have been established
2964 ;; before the module system is fully booted.
2966 ;; (The obarray continues to be used by code that has been closed over
2967 ;; before the module system has been booted.)
2969 (define the-root-module
2970 (let ((m (make-module 0)))
2971 (set-module-obarray! m (%get-pre-modules-obarray))
2972 (set-module-name! m '(guile))
2975 ;; The root interface is a module that uses the same obarray as the
2976 ;; root module. It does not allow new definitions, tho.
2978 (define the-scm-module
2979 (let ((m (make-module 0)))
2980 (set-module-obarray! m (%get-pre-modules-obarray))
2981 (set-module-name! m '(guile))
2982 (set-module-kind! m 'interface)
2984 ;; In Guile 1.8 and earlier M was its own public interface.
2985 (set-module-public-interface! m m)
2989 (set-module-public-interface! the-root-module the-scm-module)
2993 ;; Now that we have a root module, even though modules aren't fully booted,
2994 ;; expand the definition of resolve-module.
2996 (define (resolve-module name . args)
2997 (if (equal? name '(guile))
2999 (error "unexpected module to resolve during module boot" name)))
3001 ;; Cheat. These bindings are needed by modules.c, but we don't want
3002 ;; to move their real definition here because that would be unnatural.
3004 (define define-module* #f)
3005 (define process-use-modules #f)
3006 (define module-export! #f)
3007 (define default-duplicate-binding-procedures #f)
3009 ;; This boots the module system. All bindings needed by modules.c
3010 ;; must have been defined by now.
3012 (set-current-module the-root-module)
3017 ;; Now that modules are booted, give module-name its final definition.
3020 (let ((accessor (record-accessor module-type 'name)))
3023 (let ((name (list (gensym))))
3024 ;; Name MOD and bind it in the module root so that it's visible to
3025 ;; `resolve-module'. This is important as `psyntax' stores module
3026 ;; names and relies on being able to `resolve-module' them.
3027 (set-module-name! mod name)
3028 (nested-define-module! (resolve-module '() #f) name mod)
3031 (define (make-modules-in module name)
3032 (or (nested-ref-module module name)
3033 (let ((m (make-module 31)))
3034 (set-module-kind! m 'directory)
3035 (set-module-name! m (append (module-name module) name))
3036 (nested-define-module! module name m)
3039 (define (beautify-user-module! module)
3040 (let ((interface (module-public-interface module)))
3041 (if (or (not interface)
3042 (eq? interface module))
3043 (let ((interface (make-module 31)))
3044 (set-module-name! interface (module-name module))
3045 (set-module-version! interface (module-version module))
3046 (set-module-kind! interface 'interface)
3047 (set-module-public-interface! module interface))))
3048 (if (and (not (memq the-scm-module (module-uses module)))
3049 (not (eq? module the-root-module)))
3050 ;; Import the default set of bindings (from the SCM module) in MODULE.
3051 (module-use! module the-scm-module)))
3053 (define (version-matches? version-ref target)
3054 (define (sub-versions-match? v-refs t)
3055 (define (sub-version-matches? v-ref t)
3056 (let ((matches? (lambda (v) (sub-version-matches? v t))))
3058 ((number? v-ref) (eqv? v-ref t))
3061 ((>=) (>= t (cadr v-ref)))
3062 ((<=) (<= t (cadr v-ref)))
3063 ((and) (and-map matches? (cdr v-ref)))
3064 ((or) (or-map matches? (cdr v-ref)))
3065 ((not) (not (matches? (cadr v-ref))))
3066 (else (error "Invalid sub-version reference" v-ref))))
3067 (else (error "Invalid sub-version reference" v-ref)))))
3069 (and (not (null? t))
3070 (sub-version-matches? (car v-refs) (car t))
3071 (sub-versions-match? (cdr v-refs) (cdr t)))))
3073 (let ((matches? (lambda (v) (version-matches? v target))))
3074 (or (null? version-ref)
3075 (case (car version-ref)
3076 ((and) (and-map matches? (cdr version-ref)))
3077 ((or) (or-map matches? (cdr version-ref)))
3078 ((not) (not (matches? (cadr version-ref))))
3079 (else (sub-versions-match? version-ref target))))))
3081 (define (make-fresh-user-module)
3082 (let ((m (make-module)))
3083 (beautify-user-module! m)
3086 ;; NOTE: This binding is used in libguile/modules.c.
3088 (define resolve-module
3089 (let ((root (make-module)))
3090 (set-module-name! root '())
3091 ;; Define the-root-module as '(guile).
3092 (module-define-submodule! root 'guile the-root-module)
3094 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
3095 (let ((already (nested-ref-module root name)))
3098 (or (not autoload) (module-public-interface already)))
3099 ;; A hit, a palpable hit.
3101 (not (version-matches? version (module-version already))))
3102 (error "incompatible module version already loaded" name))
3105 ;; Try to autoload the module, and recurse.
3106 (try-load-module name version)
3107 (resolve-module name #f #:ensure ensure))
3109 ;; No module found (or if one was, it had no public interface), and
3110 ;; we're not autoloading. Make an empty module if #:ensure is true.
3113 (make-modules-in root name)))))))))
3116 (define (try-load-module name version)
3117 (try-module-autoload name version))
3119 (define (reload-module m)
3120 "Revisit the source file corresponding to the module @var{m}."
3121 (let ((f (module-filename m)))
3123 (save-module-excursion
3125 ;; Re-set the initial environment, as in try-module-autoload.
3126 (set-current-module (make-fresh-user-module))
3127 (primitive-load-path f)
3129 ;; Though we could guess, we *should* know it.
3130 (error "unknown file name for module" m))))
3132 (define (purify-module! module)
3133 "Removes bindings in MODULE which are inherited from the (guile) module."
3134 (let ((use-list (module-uses module)))
3135 (if (and (pair? use-list)
3136 (eq? (car (last-pair use-list)) the-scm-module))
3137 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
3139 ;; Return a module that is an interface to the module designated by
3142 ;; `resolve-interface' takes four keyword arguments:
3144 ;; #:select SELECTION
3146 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
3147 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
3148 ;; is the name in the used module and SEEN is the name in the using
3149 ;; module. Note that SEEN is also passed through RENAMER, below. The
3150 ;; default is to select all bindings. If you specify no selection but
3151 ;; a renamer, only the bindings that already exist in the used module
3152 ;; are made available in the interface. Bindings that are added later
3153 ;; are not picked up.
3157 ;; BINDINGS is a list of bindings which should not be imported.
3161 ;; PREFIX is a symbol that will be appended to each exported name.
3162 ;; The default is to not perform any renaming.
3164 ;; #:renamer RENAMER
3166 ;; RENAMER is a procedure that takes a symbol and returns its new
3167 ;; name. The default is not perform any renaming.
3169 ;; Signal "no code for module" error if module name is not resolvable
3170 ;; or its public interface is not available. Signal "no binding"
3171 ;; error if selected binding does not exist in the used module.
3173 (define* (resolve-interface name #:key
3178 (symbol-prefix-proc prefix)
3181 (let* ((module (resolve-module name #t version #:ensure #f))
3182 (public-i (and module (module-public-interface module))))
3184 (error "no code for module" name))
3185 (if (and (not select) (null? hide) (eq? renamer identity))
3187 (let ((selection (or select (module-map (lambda (sym var) sym)
3189 (custom-i (make-module 31)))
3190 (set-module-kind! custom-i 'custom-interface)
3191 (set-module-name! custom-i name)
3192 ;; XXX - should use a lazy binder so that changes to the
3193 ;; used module are picked up automatically.
3194 (for-each (lambda (bspec)
3195 (let* ((direct? (symbol? bspec))
3196 (orig (if direct? bspec (car bspec)))
3197 (seen (if direct? bspec (cdr bspec)))
3198 (var (or (module-local-variable public-i orig)
3199 (module-local-variable module orig)
3201 ;; fixme: format manually for now
3203 #f "no binding `~A' in module ~A"
3205 (if (memq orig hide)
3206 (set! hide (delq! orig hide))
3207 (module-add! custom-i
3211 ;; Check that we are not hiding bindings which don't exist
3212 (for-each (lambda (binding)
3213 (if (not (module-local-variable public-i binding))
3216 #f "no binding `~A' to hide in module ~A"
3221 (define (symbol-prefix-proc prefix)
3223 (symbol-append prefix symbol)))
3225 ;; This function is called from "modules.c". If you change it, be
3226 ;; sure to update "modules.c" as well.
3228 (define* (define-module* name
3229 #:key filename pure version (duplicates '())
3230 (imports '()) (exports '()) (replacements '())
3231 (re-exports '()) (autoloads '()) transformer)
3232 (define (list-of pred l)
3234 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
3235 (define (valid-export? x)
3236 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
3237 (define (valid-autoload? x)
3238 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
3240 (define (resolve-imports imports)
3241 (define (resolve-import import-spec)
3242 (if (list? import-spec)
3243 (apply resolve-interface import-spec)
3244 (error "unexpected use-module specification" import-spec)))
3245 (let lp ((imports imports) (out '()))
3247 ((null? imports) (reverse! out))
3250 (cons (resolve-import (car imports)) out)))
3251 (else (error "unexpected tail of imports list" imports)))))
3253 ;; We could add a #:no-check arg, set by the define-module macro, if
3254 ;; these checks are taking too much time.
3256 (let ((module (resolve-module name #f)))
3257 (beautify-user-module! module)
3259 (set-module-filename! module filename))
3261 (purify-module! module))
3264 (if (not (list-of integer? version))
3265 (error "expected list of integers for version"))
3266 (set-module-version! module version)
3267 (set-module-version! (module-public-interface module) version)))
3268 (let ((imports (resolve-imports imports)))
3269 (call-with-deferred-observers
3272 (module-use-interfaces! module imports))
3273 (if (list-of valid-export? exports)
3275 (module-export! module exports))
3276 (error "expected exports to be a list of symbols or symbol pairs"))
3277 (if (list-of valid-export? replacements)
3278 (if (pair? replacements)
3279 (module-replace! module replacements))
3280 (error "expected replacements to be a list of symbols or symbol pairs"))
3281 (if (list-of valid-export? re-exports)
3282 (if (pair? re-exports)
3283 (module-re-export! module re-exports))
3284 (error "expected re-exports to be a list of symbols or symbol pairs"))
3286 (if (not (null? autoloads))
3287 (apply module-autoload! module autoloads))
3288 ;; Wait until modules have been loaded to resolve duplicates
3290 (if (pair? duplicates)
3291 (let ((handlers (lookup-duplicates-handlers duplicates)))
3292 (set-module-duplicates-handlers! module handlers))))))
3295 (if (and (pair? transformer) (list-of symbol? transformer))
3296 (let ((iface (resolve-interface transformer))
3297 (sym (car (last-pair transformer))))
3298 (set-module-transformer! module (module-ref iface sym)))
3299 (error "expected transformer to be a module name" transformer)))
3301 (run-hook module-defined-hook module)
3304 ;; `module-defined-hook' is a hook that is run whenever a new module
3305 ;; is defined. Its members are called with one argument, the new
3307 (define module-defined-hook (make-hook 1))
3314 (define (make-autoload-interface module name bindings)
3315 (let ((b (lambda (a sym definep)
3317 (and (memq sym bindings)
3318 (let ((i (module-public-interface (resolve-module name))))
3320 (error "missing interface for module" name))
3321 (let ((autoload (memq a (module-uses module))))
3322 ;; Replace autoload-interface with actual interface if
3323 ;; that has not happened yet.
3324 (if (pair? autoload)
3325 (set-car! autoload i)))
3326 (module-local-variable i sym)))
3327 #:warning "Failed to autoload ~a in ~a:\n" sym name))))
3328 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
3329 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
3330 (make-hash-table 0) #f #f #f)))
3332 (define (module-autoload! module . args)
3333 "Have @var{module} automatically load the module named @var{name} when one
3334 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
3335 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
3336 module '(ice-9 q) '(make-q q-length))}."
3337 (let loop ((args args))
3341 (error "invalid name+binding autoload list" args))
3343 (let ((name (car args))
3344 (bindings (cadr args)))
3345 (module-use! module (make-autoload-interface module
3347 (loop (cddr args)))))))
3352 ;;; {Autoloading modules}
3355 ;;; XXX FIXME autoloads-in-progress and autoloads-done
3356 ;;; are not handled in a thread-safe way.
3358 (define autoloads-in-progress '())
3360 ;; This function is called from scm_load_scheme_module in
3361 ;; "deprecated.c". Please do not change its interface.
3363 (define* (try-module-autoload module-name #:optional version)
3364 "Try to load a module of the given name. If it is not found, return
3365 #f. Otherwise return #t. May raise an exception if a file is found,
3366 but it fails to load."
3367 (let* ((reverse-name (reverse module-name))
3368 (name (symbol->string (car reverse-name)))
3369 (dir-hint-module-name (reverse (cdr reverse-name)))
3370 (dir-hint (apply string-append
3372 (string-append (symbol->string elt)
3373 file-name-separator-string))
3374 dir-hint-module-name))))
3375 (resolve-module dir-hint-module-name #f)
3376 (and (not (autoload-done-or-in-progress? dir-hint name))
3379 (lambda () (autoload-in-progress! dir-hint name))
3381 (with-fluids ((current-reader #f))
3382 (save-module-excursion
3384 (define (call/ec proc)
3385 (let ((tag (make-prompt-tag)))
3389 (proc (lambda () (abort-to-prompt tag))))
3390 (lambda (k) (values)))))
3391 ;; The initial environment when loading a module is a fresh
3393 (set-current-module (make-fresh-user-module))
3394 ;; Here we could allow some other search strategy (other than
3395 ;; primitive-load-path), for example using versions encoded
3396 ;; into the file system -- but then we would have to figure
3397 ;; out how to locate the compiled file, do auto-compilation,
3398 ;; etc. Punt for now, and don't use versions when locating
3402 (primitive-load-path (in-vicinity dir-hint name)
3404 (set! didit #t)))))))
3405 (lambda () (set-autoloaded! dir-hint name didit)))
3410 ;;; {Dynamic linking of modules}
3413 (define autoloads-done '((guile . guile)))
3415 (define (autoload-done-or-in-progress? p m)
3416 (let ((n (cons p m)))
3417 (->bool (or (member n autoloads-done)
3418 (member n autoloads-in-progress)))))
3420 (define (autoload-done! p m)
3421 (let ((n (cons p m)))
3422 (set! autoloads-in-progress
3423 (delete! n autoloads-in-progress))
3424 (or (member n autoloads-done)
3425 (set! autoloads-done (cons n autoloads-done)))))
3427 (define (autoload-in-progress! p m)
3428 (let ((n (cons p m)))
3429 (set! autoloads-done
3430 (delete! n autoloads-done))
3431 (set! autoloads-in-progress (cons n autoloads-in-progress))))
3433 (define (set-autoloaded! p m done?)
3435 (autoload-done! p m)
3436 (let ((n (cons p m)))
3437 (set! autoloads-done (delete! n autoloads-done))
3438 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
3442 ;;; {Run-time options}
3445 (define-syntax define-option-interface
3447 ((_ (interface (options enable disable) (option-set!)))
3454 (begin (interface arg) (interface))
3457 (apply (lambda (name value documentation)
3459 (let ((len (string-length (symbol->string name))))
3467 (display documentation)
3471 (define (enable . flags)
3472 (interface (append flags (interface)))
3474 (define (disable . flags)
3475 (let ((options (interface)))
3476 (for-each (lambda (flag) (set! options (delq! flag options)))
3480 (define-syntax-rule (option-set! opt val)
3481 (eval-when (expand load eval)
3482 (options (append (options) (list 'opt val)))))))))
3484 (define-option-interface
3485 (debug-options-interface
3486 (debug-options debug-enable debug-disable)
3489 (define-option-interface
3490 (read-options-interface
3491 (read-options read-enable read-disable)
3494 (define-option-interface
3495 (print-options-interface
3496 (print-options print-enable print-disable)
3501 ;;; {The Unspecified Value}
3503 ;;; Currently Guile represents unspecified values via one particular value,
3504 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
3505 ;;; future if we could replace this with a return of 0 values, though.
3508 (define-syntax *unspecified*
3509 (identifier-syntax (if #f #f)))
3511 (define (unspecified? v) (eq? v *unspecified*))
3519 (define *repl-stack* (make-fluid '()))
3521 ;; Programs can call `batch-mode?' to see if they are running as part of a
3522 ;; script or if they are running interactively. REPL implementations ensure that
3523 ;; `batch-mode?' returns #f during their extent.
3525 (define (batch-mode?)
3526 (null? (fluid-ref *repl-stack*)))
3528 ;; Programs can re-enter batch mode, for example after a fork, by calling
3529 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3530 ;; to abort to the outermost prompt, and call a thunk there.
3532 (define (ensure-batch-mode!)
3533 (set! batch-mode? (lambda () #t)))
3535 (define (quit . args)
3536 (apply throw 'quit args))
3540 (define (gc-run-time)
3541 (cdr (assq 'gc-time-taken (gc-stats))))
3543 (define abort-hook (make-hook))
3544 (define before-error-hook (make-hook))
3545 (define after-error-hook (make-hook))
3546 (define before-backtrace-hook (make-hook))
3547 (define after-backtrace-hook (make-hook))
3549 (define before-read-hook (make-hook))
3550 (define after-read-hook (make-hook))
3551 (define before-eval-hook (make-hook 1))
3552 (define after-eval-hook (make-hook 1))
3553 (define before-print-hook (make-hook 1))
3554 (define after-print-hook (make-hook 1))
3556 ;;; This hook is run at the very end of an interactive session.
3558 (define exit-hook (make-hook))
3560 ;;; The default repl-reader function. We may override this if we've
3561 ;;; the readline library.
3563 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3564 (if (not (char-ready?))
3566 (display (if (string? prompt) prompt (prompt)))
3567 ;; An interesting situation. The printer resets the column to
3568 ;; 0 by printing a newline, but we then advance it by printing
3569 ;; the prompt. However the port-column of the output port
3570 ;; does not typically correspond with the actual column on the
3571 ;; screen, because the input is echoed back! Since the
3572 ;; input is line-buffered and thus ends with a newline, the
3573 ;; output will really start on column zero. So, here we zero
3574 ;; it out. See bug 9664.
3576 ;; Note that for similar reasons, the output-line will not
3577 ;; reflect the actual line on the screen. But given the
3578 ;; possibility of multiline input, the fix is not as
3579 ;; straightforward, so we don't bother.
3581 ;; Also note that the readline implementation papers over
3582 ;; these concerns, because it's readline itself printing the
3583 ;; prompt, and not Guile.
3584 (set-port-column! (current-output-port) 0)))
3586 (run-hook before-read-hook)
3587 ((or reader read) (current-input-port))))
3594 ;;; with `continue' and `break'.
3597 ;; The inliner will remove the prompts at compile-time if it finds that
3598 ;; `continue' or `break' are not used.
3600 (define-syntax while
3603 ((while cond body ...)
3604 #`(let ((break-tag (make-prompt-tag "break"))
3605 (continue-tag (make-prompt-tag "continue")))
3609 (define-syntax #,(datum->syntax #'while 'break)
3613 #'(abort-to-prompt break-tag arg (... ...)))
3616 (apply abort-to-prompt break-tag args))))))
3621 (define-syntax #,(datum->syntax #'while 'continue)
3625 #'(abort-to-prompt continue-tag))
3627 (syntax-violation 'continue "too many arguments" x))
3630 (abort-to-prompt continue-tag))))))
3631 (do () ((not cond) #f) body ...))
3632 (lambda (k) (lp)))))
3636 (apply values args)))))))))
3641 ;;; {Module System Macros}
3644 ;; Return a list of expressions that evaluate to the appropriate
3645 ;; arguments for resolve-interface according to SPEC.
3648 (if (memq 'prefix (read-options))
3649 (error "boot-9 must be compiled with #:kw, not :kw")))
3651 (define (keyword-like-symbol->keyword sym)
3652 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3654 (define-syntax define-module
3656 (define (keyword-like? stx)
3657 (let ((dat (syntax->datum stx)))
3659 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3660 (define (->keyword sym)
3661 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3663 (define (parse-iface args)
3664 (let loop ((in args) (out '()))
3667 ;; The user wanted #:foo, but wrote :foo. Fix it.
3668 ((sym . in) (keyword-like? #'sym)
3669 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3670 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3671 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3672 ((#:renamer renamer . in)
3673 (loop #'in (cons* #',renamer #:renamer out)))
3675 (loop #'in (cons* #'val #'kw out))))))
3677 (define (parse args imp exp rex rep aut)
3678 ;; Just quote everything except #:use-module and #:use-syntax. We
3679 ;; need to know about all arguments regardless since we want to turn
3680 ;; symbols that look like keywords into real keywords, and the
3681 ;; keyword args in a define-module form are not regular
3682 ;; (i.e. no-backtrace doesn't take a value).
3683 (syntax-case args ()
3685 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3686 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3687 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3688 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3689 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3690 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3691 ;; The user wanted #:foo, but wrote :foo. Fix it.
3692 ((sym . args) (keyword-like? #'sym)
3693 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3694 imp exp rex rep aut))
3695 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3696 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3697 ((#:no-backtrace . args)
3699 (parse #'args imp exp rex rep aut))
3701 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3703 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3704 ((#:version (v ...) . args)
3705 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3706 ((#:duplicates (d ...) . args)
3707 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3708 ((#:filename f . args)
3709 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3710 ((#:use-module (name name* ...) . args)
3711 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3712 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3713 ((#:use-syntax (name name* ...) . args)
3714 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3715 #`(#:transformer '(name name* ...)
3716 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3717 ((#:use-module ((name name* ...) arg ...) . args)
3718 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3720 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3722 ((#:export (ex ...) . args)
3723 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3724 ((#:export-syntax (ex ...) . args)
3725 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3726 ((#:re-export (re ...) . args)
3727 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3728 ((#:re-export-syntax (re ...) . args)
3729 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3730 ((#:replace (r ...) . args)
3731 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3732 ((#:replace-syntax (r ...) . args)
3733 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3734 ((#:autoload name bindings . args)
3735 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3737 (syntax-violation 'define-module "unknown keyword or bad argument"
3741 ((_ (name name* ...) arg ...)
3742 (and-map symbol? (syntax->datum #'(name name* ...)))
3743 (with-syntax (((quoted-arg ...)
3744 (parse #'(arg ...) '() '() '() '() '()))
3745 ;; Ideally the filename is either a string or #f;
3746 ;; this hack is to work around a case in which
3747 ;; port-filename returns a symbol (`socket') for
3749 (filename (let ((f (assq-ref (or (syntax-source x) '())
3751 (and (string? f) f))))
3752 #'(eval-when (expand load eval)
3753 (let ((m (define-module* '(name name* ...)
3754 #:filename filename quoted-arg ...)))
3755 (set-current-module m)
3758 ;; The guts of the use-modules macro. Add the interfaces of the named
3759 ;; modules to the use-list of the current module, in order.
3761 ;; This function is called by "modules.c". If you change it, be sure
3762 ;; to change scm_c_use_module as well.
3764 (define (process-use-modules module-interface-args)
3765 (let ((interfaces (map (lambda (mif-args)
3766 (or (apply resolve-interface mif-args)
3767 (error "no such module" mif-args)))
3768 module-interface-args)))
3769 (call-with-deferred-observers
3771 (module-use-interfaces! (current-module) interfaces)))))
3773 (define-syntax use-modules
3775 (define (keyword-like? stx)
3776 (let ((dat (syntax->datum stx)))
3778 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3779 (define (->keyword sym)
3780 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3782 (define (quotify-iface args)
3783 (let loop ((in args) (out '()))
3786 ;; The user wanted #:foo, but wrote :foo. Fix it.
3787 ((sym . in) (keyword-like? #'sym)
3788 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3789 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3790 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3791 ((#:renamer renamer . in)
3792 (loop #'in (cons* #'renamer #:renamer out)))
3794 (loop #'in (cons* #''val #'kw out))))))
3796 (define (quotify specs)
3797 (let lp ((in specs) (out '()))
3800 (((name name* ...) . in)
3801 (and-map symbol? (syntax->datum #'(name name* ...)))
3802 (lp #'in (cons #''((name name* ...)) out)))
3803 ((((name name* ...) arg ...) . in)
3804 (and-map symbol? (syntax->datum #'(name name* ...)))
3805 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3806 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3811 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3812 #'(eval-when (expand load eval)
3813 (process-use-modules (list quoted-args ...))
3816 (include-from-path "ice-9/r6rs-libraries")
3818 (define-syntax-rule (define-private foo bar)
3821 (define-syntax define-public
3823 ((_ (name . args) . body)
3825 (define (name . args) . body)
3832 (define-syntax-rule (defmacro-public name args body ...)
3834 (defmacro name args body ...)
3835 (export-syntax name)))
3837 ;; And now for the most important macro.
3838 (define-syntax-rule (λ formals body ...)
3839 (lambda formals body ...))
3842 ;; Export a local variable
3844 ;; This function is called from "modules.c". If you change it, be
3845 ;; sure to update "modules.c" as well.
3847 (define (module-export! m names)
3848 (let ((public-i (module-public-interface m)))
3849 (for-each (lambda (name)
3850 (let* ((internal-name (if (pair? name) (car name) name))
3851 (external-name (if (pair? name) (cdr name) name))
3852 (var (module-ensure-local-variable! m internal-name)))
3853 (module-add! public-i external-name var)))
3856 (define (module-replace! m names)
3857 (let ((public-i (module-public-interface m)))
3858 (for-each (lambda (name)
3859 (let* ((internal-name (if (pair? name) (car name) name))
3860 (external-name (if (pair? name) (cdr name) name))
3861 (var (module-ensure-local-variable! m internal-name)))
3862 ;; FIXME: use a bit on variables instead of object
3864 (set-object-property! var 'replace #t)
3865 (module-add! public-i external-name var)))
3868 ;; Export all local variables from a module
3870 (define (module-export-all! mod)
3871 (define (fresh-interface!)
3872 (let ((iface (make-module)))
3873 (set-module-name! iface (module-name mod))
3874 (set-module-version! iface (module-version mod))
3875 (set-module-kind! iface 'interface)
3876 (set-module-public-interface! mod iface)
3878 (let ((iface (or (module-public-interface mod)
3879 (fresh-interface!))))
3880 (set-module-obarray! iface (module-obarray mod))))
3882 ;; Re-export a imported variable
3884 (define (module-re-export! m names)
3885 (let ((public-i (module-public-interface m)))
3886 (for-each (lambda (name)
3887 (let* ((internal-name (if (pair? name) (car name) name))
3888 (external-name (if (pair? name) (cdr name) name))
3889 (var (module-variable m internal-name)))
3891 (error "Undefined variable:" internal-name))
3892 ((eq? var (module-local-variable m internal-name))
3893 (error "re-exporting local variable:" internal-name))
3895 (module-add! public-i external-name var)))))
3898 (define-syntax-rule (export name ...)
3899 (eval-when (expand load eval)
3900 (call-with-deferred-observers
3902 (module-export! (current-module) '(name ...))))))
3904 (define-syntax-rule (re-export name ...)
3905 (eval-when (expand load eval)
3906 (call-with-deferred-observers
3908 (module-re-export! (current-module) '(name ...))))))
3910 (define-syntax-rule (export! name ...)
3911 (eval-when (expand load eval)
3912 (call-with-deferred-observers
3914 (module-replace! (current-module) '(name ...))))))
3916 (define-syntax-rule (export-syntax name ...)
3919 (define-syntax-rule (re-export-syntax name ...)
3920 (re-export name ...))
3927 (define* (make-mutable-parameter init #:optional (converter identity))
3928 (let ((fluid (make-fluid (converter init))))
3930 (() (fluid-ref fluid))
3931 ((val) (fluid-set! fluid (converter val))))))
3936 ;;; {Handling of duplicate imported bindings}
3939 ;; Duplicate handlers take the following arguments:
3941 ;; module importing module
3942 ;; name conflicting name
3943 ;; int1 old interface where name occurs
3944 ;; val1 value of binding in old interface
3945 ;; int2 new interface where name occurs
3946 ;; val2 value of binding in new interface
3947 ;; var previous resolution or #f
3948 ;; val value of previous resolution
3950 ;; A duplicate handler can take three alternative actions:
3952 ;; 1. return #f => leave responsibility to next handler
3953 ;; 2. exit with an error
3954 ;; 3. return a variable resolving the conflict
3957 (define duplicate-handlers
3958 (let ((m (make-module 7)))
3960 (define (check module name int1 val1 int2 val2 var val)
3961 (scm-error 'misc-error
3963 "~A: `~A' imported from both ~A and ~A"
3964 (list (module-name module)
3970 (define (warn module name int1 val1 int2 val2 var val)
3971 (format (current-warning-port)
3972 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3973 (module-name module)
3979 (define (replace module name int1 val1 int2 val2 var val)
3980 (let ((old (or (and var (object-property var 'replace) var)
3981 (module-variable int1 name)))
3982 (new (module-variable int2 name)))
3983 (if (object-property old 'replace)
3984 (and (or (eq? old new)
3985 (not (object-property new 'replace)))
3987 (and (object-property new 'replace)
3990 (define (warn-override-core module name int1 val1 int2 val2 var val)
3991 (and (eq? int1 the-scm-module)
3993 (format (current-warning-port)
3994 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3995 (module-name module)
3998 (module-local-variable int2 name))))
4000 (define (first module name int1 val1 int2 val2 var val)
4001 (or var (module-local-variable int1 name)))
4003 (define (last module name int1 val1 int2 val2 var val)
4004 (module-local-variable int2 name))
4006 (define (noop module name int1 val1 int2 val2 var val)
4009 (set-module-name! m 'duplicate-handlers)
4010 (set-module-kind! m 'interface)
4011 (module-define! m 'check check)
4012 (module-define! m 'warn warn)
4013 (module-define! m 'replace replace)
4014 (module-define! m 'warn-override-core warn-override-core)
4015 (module-define! m 'first first)
4016 (module-define! m 'last last)
4017 (module-define! m 'merge-generics noop)
4018 (module-define! m 'merge-accessors noop)
4021 (define (lookup-duplicates-handlers handler-names)
4023 (map (lambda (handler-name)
4024 (or (module-symbol-local-binding
4025 duplicate-handlers handler-name #f)
4026 (error "invalid duplicate handler name:"
4028 (if (list? handler-names)
4030 (list handler-names)))))
4032 (define default-duplicate-binding-procedures
4033 (make-mutable-parameter #f))
4035 (define default-duplicate-binding-handler
4036 (make-mutable-parameter '(replace warn-override-core warn last)
4037 (lambda (handler-names)
4038 (default-duplicate-binding-procedures
4039 (lookup-duplicates-handlers handler-names))
4046 ;;; Load is tricky when combined with relative file names, compilation,
4047 ;;; and the file system. If a file name is relative, what is it
4048 ;;; relative to? The name of the source file at the time it was
4049 ;;; compiled? The name of the compiled file? What if both or either
4050 ;;; were installed? And how do you get that information? Tricky, I
4053 ;;; To get around all of this, we're going to do something nasty, and
4054 ;;; turn `load' into a macro. That way it can know the name of the
4055 ;;; source file with respect to which it was invoked, so it can resolve
4056 ;;; relative file names with respect to the original source file.
4058 ;;; There is an exception, and that is that if the source file was in
4059 ;;; the load path when it was compiled, instead of looking up against
4060 ;;; the absolute source location, we load-from-path against the relative
4061 ;;; source location.
4064 (define %auto-compilation-options
4065 ;; Default `compile-file' option when auto-compiling.
4066 '(#:warnings (unbound-variable arity-mismatch format
4067 duplicate-case-datum bad-case-datum)))
4069 (define* (load-in-vicinity dir file-name #:optional reader)
4070 "Load source file FILE-NAME in vicinity of directory DIR. Use a
4071 pre-compiled version of FILE-NAME when available, and auto-compile one
4072 when none is available, reading FILE-NAME with READER."
4074 ;; The auto-compilation code will residualize a .go file in the cache
4075 ;; dir: by default, $HOME/.cache/guile/2.0/ccache/PATH.go. This
4076 ;; function determines the PATH to use as a key into the compilation
4078 (define (canonical->suffix canon)
4080 ((and (not (string-null? canon))
4081 (file-name-separator? (string-ref canon 0)))
4083 ((and (eq? (system-file-name-convention) 'windows)
4084 (absolute-file-name? canon))
4085 ;; An absolute file name that doesn't start with a separator
4086 ;; starts with a drive component. Transform the drive component
4087 ;; to a file name element: c:\foo -> \c\foo.
4088 (string-append file-name-separator-string
4089 (substring canon 0 1)
4090 (substring canon 2)))
4093 (define compiled-extension
4094 ;; File name extension of compiled files.
4095 (cond ((or (null? %load-compiled-extensions)
4096 (string-null? (car %load-compiled-extensions)))
4097 (warn "invalid %load-compiled-extensions"
4098 %load-compiled-extensions)
4100 (else (car %load-compiled-extensions))))
4102 (define (more-recent? stat1 stat2)
4103 ;; Return #t when STAT1 has an mtime greater than that of STAT2.
4104 (or (> (stat:mtime stat1) (stat:mtime stat2))
4105 (and (= (stat:mtime stat1) (stat:mtime stat2))
4106 (>= (stat:mtimensec stat1)
4107 (stat:mtimensec stat2)))))
4109 (define (fallback-file-name canon-file-name)
4110 ;; Return the in-cache compiled file name for source file
4113 ;; FIXME: would probably be better just to append
4114 ;; SHA1(canon-file-name) to the %compile-fallback-path, to avoid
4115 ;; deep directory stats.
4116 (and %compile-fallback-path
4117 (string-append %compile-fallback-path
4118 (canonical->suffix canon-file-name)
4119 compiled-extension)))
4121 (define (compile file)
4122 ;; Compile source FILE, lazily loading the compiler.
4123 ((module-ref (resolve-interface '(system base compile))
4126 #:opts %auto-compilation-options
4127 #:env (current-module)))
4129 ;; Returns the .go file corresponding to `name'. Does not search load
4130 ;; paths, only the fallback path. If the .go file is missing or out
4131 ;; of date, and auto-compilation is enabled, will try
4132 ;; auto-compilation, just as primitive-load-path does internally.
4133 ;; primitive-load is unaffected. Returns #f if auto-compilation
4134 ;; failed or was disabled.
4136 ;; NB: Unless we need to compile the file, this function should not
4137 ;; cause (system base compile) to be loaded up. For that reason
4138 ;; compiled-file-name partially duplicates functionality from (system
4141 (define (fresh-compiled-file-name name scmstat go-file-name)
4142 ;; Return GO-FILE-NAME after making sure that it contains a freshly
4143 ;; compiled version of source file NAME with stat SCMSTAT; return #f
4146 (let ((gostat (and (not %fresh-auto-compile)
4147 (stat go-file-name #f))))
4148 (if (and gostat (more-recent? gostat scmstat))
4152 (format (current-warning-port)
4153 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
4156 (%load-should-auto-compile
4157 (%warn-auto-compilation-enabled)
4158 (format (current-warning-port) ";;; compiling ~a\n" name)
4159 (let ((cfn (compile name)))
4160 (format (current-warning-port) ";;; compiled ~a\n" cfn)
4163 #:warning "WARNING: compilation of ~a failed:\n" name))
4165 (define (sans-extension file)
4166 (let ((dot (string-rindex file #\.)))
4168 (substring file 0 dot)
4171 (define (load-absolute abs-file-name)
4172 ;; Load from ABS-FILE-NAME, using a compiled file or auto-compiling
4176 (stat abs-file-name)
4177 #:warning "Stat of ~a failed:\n" abs-file-name))
4179 (define (pre-compiled)
4180 (and=> (search-path %load-compiled-path (sans-extension file-name)
4181 %load-compiled-extensions #t)
4182 (lambda (go-file-name)
4183 (let ((gostat (stat go-file-name #f)))
4184 (and gostat (more-recent? gostat scmstat)
4188 (and=> (false-if-exception (canonicalize-path abs-file-name))
4190 (and=> (fallback-file-name canon)
4191 (lambda (go-file-name)
4192 (fresh-compiled-file-name abs-file-name
4196 (let ((compiled (and scmstat (or (pre-compiled) (fallback)))))
4200 (%load-hook abs-file-name))
4201 (load-compiled compiled))
4202 (start-stack 'load-stack
4203 (primitive-load abs-file-name)))))
4205 (save-module-excursion
4207 (with-fluids ((current-reader reader)
4208 (%file-port-name-canonicalization 'relative))
4210 ((absolute-file-name? file-name)
4211 (load-absolute file-name))
4212 ((absolute-file-name? dir)
4213 (load-absolute (in-vicinity dir file-name)))
4215 (load-from-path (in-vicinity dir file-name))))))))
4218 (make-variable-transformer
4220 (let* ((src (syntax-source x))
4221 (file (and src (assq-ref src 'filename)))
4222 (dir (and (string? file) (dirname file))))
4225 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
4229 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
4233 ;;; {`cond-expand' for SRFI-0 support.}
4235 ;;; This syntactic form expands into different commands or
4236 ;;; definitions, depending on the features provided by the Scheme
4242 ;;; --> (cond-expand <cond-expand-clause>+)
4243 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
4244 ;;; <cond-expand-clause>
4245 ;;; --> (<feature-requirement> <command-or-definition>*)
4246 ;;; <feature-requirement>
4247 ;;; --> <feature-identifier>
4248 ;;; | (and <feature-requirement>*)
4249 ;;; | (or <feature-requirement>*)
4250 ;;; | (not <feature-requirement>)
4251 ;;; <feature-identifier>
4252 ;;; --> <a symbol which is the name or alias of a SRFI>
4254 ;;; Additionally, this implementation provides the
4255 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
4256 ;;; determine the implementation type and the supported standard.
4258 ;;; Remember to update the features list when adding more SRFIs.
4261 (define %cond-expand-features
4262 ;; This should contain only features that are present in core Guile,
4263 ;; before loading any modules. Modular features are handled by
4264 ;; placing 'cond-expand-provide' in the relevant module.
4269 srfi-0 ;; cond-expand itself
4270 srfi-4 ;; homogeneous numeric vectors
4271 srfi-6 ;; string ports
4272 srfi-13 ;; string library
4273 srfi-14 ;; character sets
4274 srfi-16 ;; case-lambda
4275 srfi-23 ;; `error` procedure
4276 srfi-30 ;; nested multi-line comments
4277 srfi-39 ;; parameterize
4278 srfi-46 ;; basic syntax-rules extensions
4279 srfi-55 ;; require-extension
4280 srfi-61 ;; general cond clause
4281 srfi-62 ;; s-expression comments
4282 srfi-87 ;; => in case clauses
4283 srfi-105 ;; curly infix expressions
4286 ;; This table maps module public interfaces to the list of features.
4288 (define %cond-expand-table (make-hash-table 31))
4290 ;; Add one or more features to the `cond-expand' feature list of the
4293 (define (cond-expand-provide module features)
4294 (let ((mod (module-public-interface module)))
4296 (hashq-set! %cond-expand-table mod
4297 (append (hashq-ref %cond-expand-table mod '())
4300 (define-syntax cond-expand
4302 (define (module-has-feature? mod sym)
4303 (or-map (lambda (mod)
4304 (memq sym (hashq-ref %cond-expand-table mod '())))
4307 (define (condition-matches? condition)
4308 (syntax-case condition (and or not)
4310 (and-map condition-matches? #'(c ...)))
4312 (or-map condition-matches? #'(c ...)))
4314 (if (condition-matches? #'c) #f #t))
4317 (let ((sym (syntax->datum #'c)))
4318 (if (memq sym %cond-expand-features)
4320 (module-has-feature? (current-module) sym))))))
4322 (define (match clauses alternate)
4323 (syntax-case clauses ()
4324 (((condition form ...) . rest)
4325 (if (condition-matches? #'condition)
4327 (match #'rest alternate)))
4330 (syntax-case x (else)
4331 ((_ clause ... (else form ...))
4332 (match #'(clause ...)
4334 #'(begin form ...))))
4336 (match #'(clause ...)
4338 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
4340 ;; This procedure gets called from the startup code with a list of
4341 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
4343 (define (use-srfis srfis)
4344 (process-use-modules
4346 (list (list 'srfi (string->symbol
4347 (string-append "srfi-" (number->string num))))))
4352 ;;; srfi-55: require-extension
4355 (define-syntax require-extension
4357 (syntax-case x (srfi)
4359 (and-map integer? (syntax->datum #'(n ...)))
4363 (datum->syntax x (symbol-append 'srfi- n)))
4365 (map number->string (syntax->datum #'(n ...)))))))
4366 #'(use-modules (srfi srfi-n) ...)))
4368 (identifier? #'type)
4369 (syntax-violation 'require-extension "Not a recognized extension type"
4373 ;;; Defining transparently inlinable procedures
4376 (define-syntax define-inlinable
4377 ;; Define a macro and a procedure such that direct calls are inlined, via
4378 ;; the macro expansion, whereas references in non-call contexts refer to
4379 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
4381 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
4383 (define prefix (string->symbol "% "))
4384 (define (make-procedure-name name)
4386 (symbol-append prefix (syntax->datum name)
4390 ((_ (name formals ...) body ...)
4391 (identifier? #'name)
4392 (with-syntax ((proc-name (make-procedure-name #'name))
4393 ((args ...) (generate-temporaries #'(formals ...))))
4395 (define (proc-name formals ...)
4396 (syntax-parameterize ((name (identifier-syntax proc-name)))
4398 (define-syntax-parameter name
4402 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
4403 (lambda (formals ...)
4407 (syntax-violation 'name "Wrong number of arguments" x))
4410 #'proc-name))))))))))
4414 (define using-readline?
4415 (let ((using-readline? (make-fluid)))
4416 (make-procedure-with-setter
4417 (lambda () (fluid-ref using-readline?))
4418 (lambda (v) (fluid-set! using-readline? v)))))
4422 ;;; {Deprecated stuff}
4426 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
4430 ;;; SRFI-4 in the default environment. FIXME: we should figure out how
4431 ;;; to deprecate this.
4435 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
4439 ;;; A few identifiers that need to be defined in this file are really
4440 ;;; internal implementation details. We shove them off into internal
4441 ;;; modules, removing them from the (guile) module.
4444 (define-module (system syntax))
4447 (define (steal-bindings! from to ids)
4450 (let ((v (module-local-variable from sym)))
4451 (module-remove! from sym)
4452 (module-add! to sym v)))
4454 (module-export! to ids))
4456 (steal-bindings! the-root-module (resolve-module '(system syntax))
4457 '(syntax-local-binding
4459 syntax-locally-bound-identifiers
4460 syntax-session-id)))
4465 ;;; Place the user in the guile-user module.
4468 ;; Set filename to #f to prevent reload.
4469 (define-module (guile-user)
4470 #:autoload (system base compile) (compile compile-file)
4473 ;; Remain in the `(guile)' module at compilation-time so that the
4474 ;; `-Wunused-toplevel' warning works as expected.
4475 (eval-when (compile) (set-current-module the-root-module))
4477 ;;; boot-9.scm ends here