1 ;;; -*- mode: scheme; coding: utf-8; -*-
3 ;;;; Copyright (C) 1995-2014 Free Software Foundation, Inc.
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 ;;; This file is the first thing loaded into Guile. It adds many mundane
25 ;;; definitions and a few that are interesting.
27 ;;; The module system (hence the hierarchical namespace) are defined in this
35 ;; Before compiling, make sure any symbols are resolved in the (guile)
36 ;; module, the primary location of those symbols, rather than in
37 ;; (guile-user), the default module that we compile in.
40 (set-current-module (resolve-module '(guile))))
44 ;;; {Language primitives}
47 ;; These are are the procedural wrappers around the primitives of
48 ;; Guile's language: apply, call-with-current-continuation, etc.
50 ;; Usually, a call to a primitive is compiled specially. The compiler
51 ;; knows about all these kinds of expressions. But the primitives may
52 ;; be referenced not only as operators, but as values as well. These
53 ;; stub procedures are the "values" of apply, dynamic-wind, and other
59 ((@@ primitive apply) fun args))
61 (letrec ((append* (lambda (tail)
62 (let ((tail (car tail))
66 (cons tail (append* tail*)))))))
67 (apply fun (cons arg1 (append* args)))))))
68 (define (call-with-current-continuation proc)
69 ((@@ primitive call-with-current-continuation) proc))
70 (define (call-with-values producer consumer)
71 ((@@ primitive call-with-values) producer consumer))
72 (define (dynamic-wind in thunk out)
73 "All three arguments must be 0-argument procedures.
74 Guard @var{in} is called, then @var{thunk}, then
77 If, any time during the execution of @var{thunk}, the
78 continuation of the @code{dynamic_wind} expression is escaped
79 non-locally, @var{out} is called. If the continuation of
80 the dynamic-wind is re-entered, @var{in} is called. Thus
81 @var{in} and @var{out} may be called any number of
84 (define x 'normal-binding)
87 (call-with-current-continuation
93 (lambda () (set! x 'special-binding))
97 (lambda () (display x) (newline)
98 (call-with-current-continuation escape)
104 (lambda () (set! x old-x)))))))
111 @result{} normal-binding
116 @result{} a-cont ;; the value of the (define a-cont...)
118 @result{} normal-binding
120 @result{} special-binding
122 ;; FIXME: Here we don't check that the out procedure is a thunk before
123 ;; calling the in-guard, as dynamic-wind is called as part of loading
124 ;; modules, but thunk? requires loading (system vm debug). This is in
125 ;; contrast to the open-coded version of dynamic-wind, which does
126 ;; currently insert an eager thunk? check (but often optimizes it
127 ;; out). Not sure what the right thing to do is here -- make thunk?
128 ;; callable before modules are loaded, live with this inconsistency,
129 ;; or remove the thunk? check from the compiler? Questions,
133 (scm-error 'wrong-type-arg "dynamic-wind" "Not a thunk: ~S"
136 ((@@ primitive wind) in out)
137 (call-with-values thunk
139 ((@@ primitive unwind))
141 (apply values vals))))
143 (define (with-fluid* fluid val thunk)
144 "Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
145 @var{thunk} must be a procedure of no arguments."
146 ((@@ primitive push-fluid) fluid val)
147 (call-with-values thunk
149 ((@@ primitive pop-fluid))
150 (apply values vals))))
154 ;;; {Low-Level Port Code}
157 ;; These are used to request the proper mode to open files in.
159 (define OPEN_READ "r")
160 (define OPEN_WRITE "w")
161 (define OPEN_BOTH "r+")
163 (define *null-device* "/dev/null")
165 ;; NOTE: Later in this file, this is redefined to support keywords
166 (define (open-input-file str)
167 "Takes a string naming an existing file and returns an input port
168 capable of delivering characters from the file. If the file
169 cannot be opened, an error is signalled."
170 (open-file str OPEN_READ))
172 ;; NOTE: Later in this file, this is redefined to support keywords
173 (define (open-output-file str)
174 "Takes a string naming an output file to be created and returns an
175 output port capable of writing characters to a new file by that
176 name. If the file cannot be opened, an error is signalled. If a
177 file with the given name already exists, the effect is unspecified."
178 (open-file str OPEN_WRITE))
180 (define (open-io-file str)
181 "Open file with name STR for both input and output."
182 (open-file str OPEN_BOTH))
186 ;;; {Simple Debugging Tools}
189 ;; peek takes any number of arguments, writes them to the
190 ;; current ouput port, and returns the last argument.
191 ;; It is handy to wrap around an expression to look at
192 ;; a value each time is evaluated, e.g.:
194 ;; (+ 10 (troublesome-fn))
195 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
198 (define (peek . stuff)
203 (car (last-pair stuff)))
207 (define (warn . stuff)
208 (newline (current-warning-port))
209 (display ";;; WARNING " (current-warning-port))
210 (display stuff (current-warning-port))
211 (newline (current-warning-port))
212 (car (last-pair stuff)))
219 (define (provide sym)
220 (if (not (memq sym *features*))
221 (set! *features* (cons sym *features*))))
223 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
224 ;; provided? also checks to see if the module is available. We should do that
227 (define (provided? feature)
228 (and (memq feature *features*) #t))
235 (define (make-struct/no-tail vtable . args)
236 (apply make-struct vtable 0 args))
240 ;;; {map and for-each}
247 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
251 (cons (f (car l)) (map1 (cdr l)))
255 (if (not (= (length l1) (length l2)))
256 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
259 (let map2 ((l1 l1) (l2 l2))
261 (cons (f (car l1) (car l2))
262 (map2 (cdr l1) (cdr l2)))
266 (let ((len (length l1)))
267 (let mapn ((rest rest))
269 (if (= (length (car rest)) len)
271 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
272 (list (car rest)) #f)))))
273 (let mapn ((l1 l1) (rest rest))
275 (cons (apply f (car l1) (map car rest))
276 (mapn (cdr l1) (map cdr rest)))
279 (define map-in-order map)
285 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S" (list l) #f))
286 (let for-each1 ((l l))
290 (for-each1 (cdr l))))))
293 (if (not (= (length l1) (length l2)))
294 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
296 (let for-each2 ((l1 l1) (l2 l2))
299 (f (car l1) (car l2))
300 (for-each2 (cdr l1) (cdr l2))))))
303 (let ((len (length l1)))
304 (let for-eachn ((rest rest))
306 (if (= (length (car rest)) len)
307 (for-eachn (cdr rest))
308 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
309 (list (car rest)) #f)))))
311 (let for-eachn ((l1 l1) (rest rest))
314 (apply f (car l1) (map car rest))
315 (for-eachn (cdr l1) (map cdr rest))))))))
318 ;; Temporary definition used in the include-from-path expansion;
321 (define (absolute-file-name? file-name)
324 ;;; {and-map and or-map}
326 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
327 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
332 ;; Apply f to successive elements of l until exhaustion or f returns #f.
333 ;; If returning early, return #f. Otherwise, return the last value returned
334 ;; by f. If f has never been called because l is empty, return #t.
336 (define (and-map f lst)
337 (let loop ((result #t)
342 (loop (f (car l)) (cdr l))))))
346 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
347 ;; If returning early, return the return value of f.
349 (define (or-map f lst)
350 (let loop ((result #f)
354 (loop (f (car l)) (cdr l))))))
358 ;; let format alias simple-format until the more complete version is loaded
360 (define format simple-format)
362 ;; this is scheme wrapping the C code so the final pred call is a tail call,
365 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
366 (if (and (procedure? char_pred)
368 (<= end (string-length s))) ;; let c-code handle range error
369 (or (string-any-c-code char_pred s start (1- end))
370 (char_pred (string-ref s (1- end))))
371 (string-any-c-code char_pred s start end))))
373 ;; this is scheme wrapping the C code so the final pred call is a tail call,
376 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
377 (if (and (procedure? char_pred)
379 (<= end (string-length s))) ;; let c-code handle range error
380 (and (string-every-c-code char_pred s start (1- end))
381 (char_pred (string-ref s (1- end))))
382 (string-every-c-code char_pred s start end))))
384 ;; A variant of string-fill! that we keep for compatability
386 (define (substring-fill! str start end fill)
387 (string-fill! str fill start end))
391 ;; Define a minimal stub of the module API for psyntax, before modules
393 (define (module-name x)
395 (define (module-add! module sym var)
396 (hashq-set! (%get-pre-modules-obarray) sym var))
397 (define (module-define! module sym val)
398 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
400 (variable-set! v val)
401 (module-add! (current-module) sym (make-variable val)))))
402 (define (module-ref module sym)
403 (let ((v (module-variable module sym)))
404 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
405 (define (resolve-module . args)
408 ;; API provided by psyntax
409 (define syntax-violation #f)
410 (define datum->syntax #f)
411 (define syntax->datum #f)
412 (define syntax-source #f)
413 (define identifier? #f)
414 (define generate-temporaries #f)
415 (define bound-identifier=? #f)
416 (define free-identifier=? #f)
418 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
419 ;; expanded macros, to dispatch an input against a set of patterns.
420 (define $sc-dispatch #f)
423 (primitive-load-path "ice-9/psyntax-pp")
424 ;; The binding for `macroexpand' has now been overridden, making psyntax the
431 ;; Avoid ellipsis, which would lead to quadratic expansion time.
432 ((_ x . y) (if x (and . y) #f))))
438 ;; Avoid ellipsis, which would lead to quadratic expansion time.
439 ((_ x . y) (let ((t x)) (if t t (or . y))))))
441 (include-from-path "ice-9/quasisyntax")
443 (define-syntax-rule (when test stmt stmt* ...)
444 (if test (begin stmt stmt* ...)))
446 (define-syntax-rule (unless test stmt stmt* ...)
447 (if (not test) (begin stmt stmt* ...)))
451 (define (fold f seed xs)
452 (let loop ((xs xs) (seed seed))
454 (loop (cdr xs) (f (car xs) seed)))))
455 (define (reverse-map f xs)
456 (fold (lambda (x seed) (cons (f x) seed))
458 (syntax-case whole-expr ()
459 ((_ clause clauses ...)
461 #,@(fold (lambda (clause-builder tail)
462 (clause-builder tail))
466 (define* (bad-clause #:optional (msg "invalid clause"))
467 (syntax-violation 'cond msg whole-expr clause))
468 (syntax-case clause (=> else)
473 (bad-clause "else must be the last clause"))))
474 ((else . _) (bad-clause))
481 ((test => receiver ...)
482 (bad-clause "wrong number of receiver expressions"))
483 ((generator guard => receiver)
485 #`((call-with-values (lambda () generator)
487 (if (apply guard vals)
488 (apply receiver vals)
490 ((generator guard => receiver ...)
491 (bad-clause "wrong number of receiver expressions"))
502 #'(clause clauses ...))))))))
506 (define (fold f seed xs)
507 (let loop ((xs xs) (seed seed))
509 (loop (cdr xs) (f (car xs) seed)))))
510 (define (fold2 f a b xs)
511 (let loop ((xs xs) (a a) (b b))
512 (if (null? xs) (values a b)
514 (lambda () (f (car xs) a b))
516 (loop (cdr xs) a b))))))
517 (define (reverse-map-with-seed f seed xs)
518 (fold2 (lambda (x ys seed)
520 (lambda () (f x seed))
522 (values (cons y ys) seed))))
524 (syntax-case whole-expr ()
525 ((_ expr clause clauses ...)
526 (with-syntax ((key #'key))
529 (lambda (clause-builder tail)
530 (clause-builder tail))
532 (reverse-map-with-seed
533 (lambda (clause seen)
534 (define* (bad-clause #:optional (msg "invalid clause"))
535 (syntax-violation 'case msg whole-expr clause))
536 (syntax-case clause ()
540 (syntax-case #'rest (=>)
541 ((=> receiver) #'(receiver key))
544 "wrong number of receiver expressions"))
545 ((e e* ...) #'(begin e e* ...))
547 (syntax-case #'test (else)
552 (define (warn-datum type)
553 ((@ (system base message)
556 (append (source-properties datum)
558 (syntax->datum #'test)))
560 (syntax->datum clause)
561 (syntax->datum whole-expr)))
562 (when (memv datum seen)
563 (warn-datum 'duplicate-case-datum))
564 (when (or (pair? datum) (array? datum))
565 (warn-datum 'bad-case-datum))
568 (map syntax->datum #'(datums ...)))))
569 (values (lambda (tail)
570 #`((if (memv key '(datums ...))
574 (else (values (lambda (tail)
578 "else must be the last clause")))
582 '() #'(clause clauses ...)))))))))
586 ((do ((var init step ...) ...)
599 (loop (do "step" var step ...)
607 (define-syntax define-values
609 (syntax-case orig-form ()
611 ;; XXX Work around the lack of hygienic top-level identifiers
612 (with-syntax (((dummy) (generate-temporaries '(dummy))))
614 (call-with-values (lambda () expr)
619 (call-with-values (lambda () expr)
621 ((_ (var0 ... varn) expr)
622 (and-map identifier? #'(var0 ... varn))
623 ;; XXX Work around the lack of hygienic toplevel identifiers
624 (with-syntax (((dummy) (generate-temporaries '(dummy))))
626 ;; Avoid mutating the user-visible variables
628 (call-with-values (lambda () expr)
629 (lambda (var0 ... varn)
630 (list var0 ... varn))))
632 (let ((v (car dummy)))
633 (set! dummy (cdr dummy))
637 (let ((v (car dummy)))
638 (set! dummy #f) ; blackhole dummy
643 (call-with-values (lambda () expr)
645 ((_ (var0 ... . varn) expr)
646 (and-map identifier? #'(var0 ... varn))
647 ;; XXX Work around the lack of hygienic toplevel identifiers
648 (with-syntax (((dummy) (generate-temporaries '(dummy))))
650 ;; Avoid mutating the user-visible variables
652 (call-with-values (lambda () expr)
653 (lambda (var0 ... . varn)
654 (list var0 ... varn))))
656 (let ((v (car dummy)))
657 (set! dummy (cdr dummy))
661 (let ((v (car dummy)))
662 (set! dummy #f) ; blackhole dummy
665 (define-syntax-rule (delay exp)
666 (make-promise (lambda () exp)))
668 (define-syntax with-fluids
670 (define (emit-with-fluids bindings body)
671 (syntax-case bindings ()
677 #,(emit-with-fluids #'bindings body))))))
679 ((_ ((fluid val) ...) exp exp* ...)
680 (with-syntax (((fluid-tmp ...) (generate-temporaries #'(fluid ...)))
681 ((val-tmp ...) (generate-temporaries #'(val ...))))
682 #`(let ((fluid-tmp fluid) ...)
683 (let ((val-tmp val) ...)
684 #,(emit-with-fluids #'((fluid-tmp val-tmp) ...)
685 #'(begin exp exp* ...)))))))))
687 (define-syntax current-source-location
691 (with-syntax ((s (datum->syntax x (syntax-source x))))
694 ;; We provide this accessor out of convenience. current-line and
695 ;; current-column aren't so interesting, because they distort what they
696 ;; are measuring; better to use syntax-source from a macro.
698 (define-syntax current-filename
700 "A macro that expands to the current filename: the filename that
701 the (current-filename) form appears in. Expands to #f if this
702 information is unavailable."
704 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
706 (define-syntax-rule (define-once sym val)
708 (if (module-locally-bound? (current-module) 'sym) sym val)))
716 ;; Define delimited continuation operators, and implement catch and throw in
719 (define make-prompt-tag
720 (lambda* (#:optional (stem "prompt"))
721 ;; The only property that prompt tags need have is uniqueness in the
722 ;; sense of eq?. A one-element list will serve nicely.
725 (define default-prompt-tag
726 ;; Redefined later to be a parameter.
727 (let ((%default-prompt-tag (make-prompt-tag)))
729 %default-prompt-tag)))
731 (define (call-with-prompt tag thunk handler)
732 ((@@ primitive call-with-prompt) tag thunk handler))
733 (define (abort-to-prompt tag . args)
734 (abort-to-prompt* tag args))
736 ;; Define catch and with-throw-handler, using some common helper routines and a
737 ;; shared fluid. Hide the helpers in a lexical contour.
739 (define with-throw-handler #f)
740 (let ((%eh (module-ref (current-module) '%exception-handler)))
741 (define (make-exception-handler catch-key prompt-tag pre-unwind)
742 (vector (fluid-ref %eh) catch-key prompt-tag pre-unwind))
743 (define (exception-handler-prev handler) (vector-ref handler 0))
744 (define (exception-handler-catch-key handler) (vector-ref handler 1))
745 (define (exception-handler-prompt-tag handler) (vector-ref handler 2))
746 (define (exception-handler-pre-unwind handler) (vector-ref handler 3))
748 (define %running-pre-unwind (make-fluid '()))
750 (define (dispatch-exception handler key args)
752 (when (eq? key 'quit)
753 (primitive-exit (cond
754 ((not (pair? args)) 0)
755 ((integer? (car args)) (car args))
758 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" key args)
761 (let ((catch-key (exception-handler-catch-key handler))
762 (prev (exception-handler-prev handler)))
763 (if (or (eqv? catch-key #t) (eq? catch-key key))
764 (let ((prompt-tag (exception-handler-prompt-tag handler))
765 (pre-unwind (exception-handler-pre-unwind handler)))
767 ;; Instead of using a "running" set, it would be a lot
768 ;; cleaner semantically to roll back the exception
769 ;; handler binding to the one that was in place when the
770 ;; pre-unwind handler was installed, and keep it like
771 ;; that for the rest of the dispatch. Unfortunately
772 ;; that is incompatible with existing semantics. We'll
773 ;; see if we can change that later on.
774 (let ((running (fluid-ref %running-pre-unwind)))
775 (with-fluid* %running-pre-unwind (cons handler running)
777 (unless (memq handler running)
778 (apply pre-unwind key args))
780 (apply abort-to-prompt prompt-tag key args)
781 (dispatch-exception prev key args)))))
782 (apply abort-to-prompt prompt-tag key args)))
783 (dispatch-exception prev key args))))
785 (define (throw key . args)
786 "Invoke the catch form matching @var{key}, passing @var{args} to the
789 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
791 If there is no handler at all, Guile prints an error and then exits."
792 (unless (symbol? key)
793 (throw 'wrong-type-arg "throw" "Wrong type argument in position ~a: ~a"
794 (list 1 key) (list key)))
795 (dispatch-exception (fluid-ref %eh) key args))
797 (define* (catch k thunk handler #:optional pre-unwind-handler)
798 "Invoke @var{thunk} in the dynamic context of @var{handler} for
799 exceptions matching @var{key}. If thunk throws to the symbol
800 @var{key}, then @var{handler} is invoked this way:
802 (handler key args ...)
805 @var{key} is a symbol or @code{#t}.
807 @var{thunk} takes no arguments. If @var{thunk} returns
808 normally, that is the return value of @code{catch}.
810 Handler is invoked outside the scope of its own @code{catch}.
811 If @var{handler} again throws to the same key, a new handler
812 from further up the call chain is invoked.
814 If the key is @code{#t}, then a throw to @emph{any} symbol will
815 match this call to @code{catch}.
817 If a @var{pre-unwind-handler} is given and @var{thunk} throws
818 an exception that matches @var{key}, Guile calls the
819 @var{pre-unwind-handler} before unwinding the dynamic state and
820 invoking the main @var{handler}. @var{pre-unwind-handler} should
821 be a procedure with the same signature as @var{handler}, that
822 is @code{(lambda (key . args))}. It is typically used to save
823 the stack at the point where the exception occurred, but can also
824 query other parts of the dynamic state at that point, such as
827 A @var{pre-unwind-handler} can exit either normally or non-locally.
828 If it exits normally, Guile unwinds the stack and dynamic context
829 and then calls the normal (third argument) handler. If it exits
830 non-locally, that exit determines the continuation."
831 (define (wrong-type-arg n val)
832 (scm-error 'wrong-type-arg "catch"
833 "Wrong type argument in position ~a: ~a"
834 (list n val) (list val)))
835 (unless (or (symbol? k) (eqv? k #t))
836 (wrong-type-arg 1 k))
837 (unless (procedure? handler)
838 (wrong-type-arg 3 handler))
839 (unless (or (not pre-unwind-handler) (procedure? pre-unwind-handler))
840 (wrong-type-arg 4 pre-unwind-handler))
841 (let ((tag (make-prompt-tag "catch")))
845 (with-fluid* %eh (make-exception-handler k tag pre-unwind-handler)
847 (lambda (cont k . args)
848 (apply handler k args)))))
850 (define (with-throw-handler k thunk pre-unwind-handler)
851 "Add @var{handler} to the dynamic context as a throw handler
852 for key @var{k}, then invoke @var{thunk}."
853 (if (not (or (symbol? k) (eqv? k #t)))
854 (scm-error 'wrong-type-arg "with-throw-handler"
855 "Wrong type argument in position ~a: ~a"
856 (list 1 k) (list k)))
857 (with-fluid* %eh (make-exception-handler k #f pre-unwind-handler)
860 (hashq-remove! (%get-pre-modules-obarray) '%exception-handler)
861 (define! 'catch catch)
862 (define! 'with-throw-handler with-throw-handler)
863 (define! 'throw throw))
869 ;;; Extensible exception printing.
872 (define set-exception-printer! #f)
873 ;; There is already a definition of print-exception from backtrace.c
874 ;; that we will override.
876 (let ((exception-printers '()))
877 (define (print-location frame port)
878 (let ((source (and=> frame frame-source)))
879 ;; source := (addr . (filename . (line . column)))
881 (let ((filename (or (cadr source) "<unnamed port>"))
882 (line (caddr source))
883 (col (cdddr source)))
884 (format port "~a:~a:~a: " filename (1+ line) col))
885 (format port "ERROR: "))))
887 (set! set-exception-printer!
889 (set! exception-printers (acons key proc exception-printers))))
891 (set! print-exception
892 (lambda (port frame key args)
893 (define (default-printer)
894 (format port "Throw to key `~a' with args `~s'." key args))
897 (let ((proc (frame-procedure frame)))
898 (print-location frame port)
899 (format port "In procedure ~a:\n"
900 (or (false-if-exception (procedure-name proc))
903 (print-location frame port)
906 (let ((printer (assq-ref exception-printers key)))
908 (printer port key args default-printer)
911 (format port "Error while printing exception.")))
913 (force-output port))))
916 ;;; Printers for those keys thrown by Guile.
919 (define (scm-error-printer port key args default-printer)
920 ;; Abuse case-lambda as a pattern matcher, given that we don't have
921 ;; ice-9 match at this point.
923 ((subr msg args . rest)
925 (format port "In procedure ~a: " subr))
926 (apply format port msg (or args '())))
927 (_ (default-printer)))
930 (define (syntax-error-printer port key args default-printer)
932 ((who what where form subform . extra)
933 (format port "Syntax error:\n")
935 (let ((file (or (assq-ref where 'filename) "unknown file"))
936 (line (and=> (assq-ref where 'line) 1+))
937 (col (assq-ref where 'column)))
938 (format port "~a:~a:~a: " file line col))
939 (format port "unknown location: "))
941 (format port "~a: " who))
942 (format port "~a" what)
944 (format port " in subform ~s of ~s" subform form)
946 (format port " in form ~s" form))))
947 (_ (default-printer)))
950 (define (keyword-error-printer port key args default-printer)
951 (let ((message (cadr args))
952 (faulty (car (cadddr args)))) ; I won't do it again, I promise.
953 (format port "~a: ~s" message faulty)))
955 (define (getaddrinfo-error-printer port key args default-printer)
956 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
958 (set-exception-printer! 'goops-error scm-error-printer)
959 (set-exception-printer! 'host-not-found scm-error-printer)
960 (set-exception-printer! 'keyword-argument-error keyword-error-printer)
961 (set-exception-printer! 'misc-error scm-error-printer)
962 (set-exception-printer! 'no-data scm-error-printer)
963 (set-exception-printer! 'no-recovery scm-error-printer)
964 (set-exception-printer! 'null-pointer-error scm-error-printer)
965 (set-exception-printer! 'out-of-memory scm-error-printer)
966 (set-exception-printer! 'out-of-range scm-error-printer)
967 (set-exception-printer! 'program-error scm-error-printer)
968 (set-exception-printer! 'read-error scm-error-printer)
969 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
970 (set-exception-printer! 'signal scm-error-printer)
971 (set-exception-printer! 'stack-overflow scm-error-printer)
972 (set-exception-printer! 'system-error scm-error-printer)
973 (set-exception-printer! 'try-again scm-error-printer)
974 (set-exception-printer! 'unbound-variable scm-error-printer)
975 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
976 (set-exception-printer! 'wrong-type-arg scm-error-printer)
978 (set-exception-printer! 'syntax-error syntax-error-printer)
980 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
988 (define-syntax define-macro
992 ((_ (macro . args) doc body1 body ...)
993 (string? (syntax->datum #'doc))
994 #'(define-macro macro doc (lambda args body1 body ...)))
995 ((_ (macro . args) body ...)
996 #'(define-macro macro #f (lambda args body ...)))
997 ((_ macro transformer)
998 #'(define-macro macro #f transformer))
999 ((_ macro doc transformer)
1000 (or (string? (syntax->datum #'doc))
1001 (not (syntax->datum #'doc)))
1002 #'(define-syntax macro
1005 #((macro-type . defmacro)
1006 (defmacro-args args))
1009 (let ((v (syntax->datum #'args)))
1010 (datum->syntax y (apply transformer v)))))))))))
1012 (define-syntax defmacro
1014 "Define a defmacro, with the old lispy defun syntax."
1016 ((_ macro args doc body1 body ...)
1017 (string? (syntax->datum #'doc))
1018 #'(define-macro macro doc (lambda args body1 body ...)))
1019 ((_ macro args body ...)
1020 #'(define-macro macro #f (lambda args body ...))))))
1029 (define-syntax begin-deprecated
1033 (if (include-deprecated-features)
1034 #'(begin form form* ...)
1039 ;;; {Trivial Functions}
1042 (define (identity x) x)
1044 (define (compose proc . rest)
1045 "Compose PROC with the procedures in REST, such that the last one in
1046 REST is applied first and PROC last, and return the resulting procedure.
1047 The given procedures must have compatible arity."
1050 (let ((g (apply compose rest)))
1052 (call-with-values (lambda () (apply g args)) proc)))))
1054 (define (negate proc)
1055 "Return a procedure with the same arity as PROC that returns the `not'
1058 (not (apply proc args))))
1060 (define (const value)
1061 "Return a procedure that accepts any number of arguments and returns
1066 (define (and=> value procedure)
1067 "When VALUE is #f, return #f. Otherwise, return (PROC VALUE)."
1068 (and value (procedure value)))
1070 (define call/cc call-with-current-continuation)
1072 (define-syntax false-if-exception
1074 ((false-if-exception expr)
1078 ((false-if-exception expr #:warning template arg ...)
1081 (lambda (key . args)
1082 (for-each (lambda (s)
1083 (if (not (string-null? s))
1084 (format (current-warning-port) ";;; ~a\n" s)))
1086 (call-with-output-string
1088 (format port template arg ...)
1089 (print-exception port #f key args)))
1095 ;;; {General Properties}
1098 ;; Properties are a lispy way to associate random info with random objects.
1099 ;; Traditionally properties are implemented as an alist or a plist actually
1100 ;; pertaining to the object in question.
1102 ;; These "object properties" have the advantage that they can be associated with
1103 ;; any object, even if the object has no plist. Object properties are good when
1104 ;; you are extending pre-existing objects in unexpected ways. They also present
1105 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
1106 ;; type that always has properties, it's often still best to store those
1107 ;; properties within the object itself.
1109 (define (make-object-property)
1110 ;; Weak tables are thread-safe.
1111 (let ((prop (make-weak-key-hash-table)))
1112 (make-procedure-with-setter
1113 (lambda (obj) (hashq-ref prop obj))
1114 (lambda (obj val) (hashq-set! prop obj val)))))
1119 ;;; {Symbol Properties}
1122 ;;; Symbol properties are something you see in old Lisp code. In most current
1123 ;;; Guile code, symbols are not used as a data structure -- they are used as
1124 ;;; keys into other data structures.
1126 (define (symbol-property sym prop)
1127 (let ((pair (assoc prop (symbol-pref sym))))
1128 (and pair (cdr pair))))
1130 (define (set-symbol-property! sym prop val)
1131 (let ((pair (assoc prop (symbol-pref sym))))
1134 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
1136 (define (symbol-property-remove! sym prop)
1137 (let ((pair (assoc prop (symbol-pref sym))))
1139 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
1146 (define (array-shape a)
1147 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1148 (array-dimensions a)))
1155 ;;; It's much better if you can use lambda* / define*, of course.
1157 (define (kw-arg-ref args kw)
1158 (let ((rem (member kw args)))
1159 (and rem (pair? (cdr rem)) (cadr rem))))
1163 ;;; {IOTA functions: generating lists of numbers}
1167 (let loop ((count (1- n)) (result '()))
1168 (if (< count 0) result
1169 (loop (1- count) (cons count result)))))
1176 (define (struct-layout s)
1177 (struct-ref (struct-vtable s) vtable-index-layout))
1184 ;; Printing records: by default, records are printed as
1186 ;; #<type-name field1: val1 field2: val2 ...>
1188 ;; You can change that by giving a custom printing function to
1189 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1190 ;; will be called like
1192 ;; (<printer> object port)
1194 ;; It should print OBJECT to PORT.
1196 (define (inherit-print-state old-port new-port)
1197 (if (get-print-state old-port)
1198 (port-with-print-state new-port (get-print-state old-port))
1201 ;; 0: type-name, 1: fields, 2: constructor
1202 (define record-type-vtable
1203 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1205 (display "#<record-type " p)
1206 (display (record-type-name s) p)
1208 (set-struct-vtable-name! s 'record-type)
1211 (define (record-type? obj)
1212 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1214 (define* (make-record-type type-name fields #:optional printer)
1215 ;; Pre-generate constructors for nfields < 20.
1216 (define-syntax make-constructor
1218 (define *max-static-argument-count* 20)
1219 (define (make-formals n)
1222 (cons (datum->syntax
1225 (string (integer->char (+ (char->integer #\a) i)))))
1229 ((_ rtd exp) (not (identifier? #'exp))
1231 (make-constructor rtd n)))
1235 (if (< n *max-static-argument-count*)
1236 (cons (with-syntax (((formal ...) (make-formals n))
1237 ((idx ...) (iota n))
1240 (lambda (formal ...)
1241 (let ((s (allocate-struct rtd n)))
1242 (struct-set! s idx formal)
1249 (if (= (length args) nfields)
1250 (apply make-struct rtd 0 args)
1251 (scm-error 'wrong-number-of-args
1252 (format #f "make-~a" type-name)
1253 "Wrong number of arguments" '() #f)))))))))
1255 (define (default-record-printer s p)
1257 (display (record-type-name (record-type-descriptor s)) p)
1258 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1261 ((not (null? fields))
1263 (display (car fields) p)
1265 (display (struct-ref s off) p)
1266 (loop (cdr fields) (+ 1 off)))))
1269 (let ((rtd (make-struct record-type-vtable 0
1271 (apply string-append
1272 (map (lambda (f) "pw") fields)))
1273 (or printer default-record-printer)
1275 (copy-tree fields))))
1276 (struct-set! rtd (+ vtable-offset-user 2)
1277 (make-constructor rtd (length fields)))
1278 ;; Temporary solution: Associate a name to the record type descriptor
1279 ;; so that the object system can create a wrapper class for it.
1280 (set-struct-vtable-name! rtd (if (symbol? type-name)
1282 (string->symbol type-name)))
1285 (define (record-type-name obj)
1286 (if (record-type? obj)
1287 (struct-ref obj vtable-offset-user)
1288 (error 'not-a-record-type obj)))
1290 (define (record-type-fields obj)
1291 (if (record-type? obj)
1292 (struct-ref obj (+ 1 vtable-offset-user))
1293 (error 'not-a-record-type obj)))
1295 (define* (record-constructor rtd #:optional field-names)
1296 (if (not field-names)
1297 (struct-ref rtd (+ 2 vtable-offset-user))
1299 `(lambda ,field-names
1300 (make-struct ',rtd 0 ,@(map (lambda (f)
1301 (if (memq f field-names)
1304 (record-type-fields rtd)))))))
1306 (define (record-predicate rtd)
1307 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1309 (define (%record-type-error rtd obj) ;; private helper
1310 (or (eq? rtd (record-type-descriptor obj))
1311 (scm-error 'wrong-type-arg "%record-type-check"
1312 "Wrong type record (want `~S'): ~S"
1313 (list (record-type-name rtd) obj)
1316 (define (record-accessor rtd field-name)
1317 (let ((pos (list-index (record-type-fields rtd) field-name)))
1319 (error 'no-such-field field-name))
1321 (if (eq? (struct-vtable obj) rtd)
1322 (struct-ref obj pos)
1323 (%record-type-error rtd obj)))))
1325 (define (record-modifier rtd field-name)
1326 (let ((pos (list-index (record-type-fields rtd) field-name)))
1328 (error 'no-such-field field-name))
1330 (if (eq? (struct-vtable obj) rtd)
1331 (struct-set! obj pos val)
1332 (%record-type-error rtd obj)))))
1334 (define (record? obj)
1335 (and (struct? obj) (record-type? (struct-vtable obj))))
1337 (define (record-type-descriptor obj)
1340 (error 'not-a-record obj)))
1350 ;; Three fields: the procedure itself, the fluid, and the converter.
1351 (make-struct <applicable-struct-vtable> 0 'pwprpr))
1352 (set-struct-vtable-name! <parameter> '<parameter>)
1354 (define* (make-parameter init #:optional (conv (lambda (x) x)))
1355 "Make a new parameter.
1357 A parameter is a dynamically bound value, accessed through a procedure.
1358 To access the current value, apply the procedure with no arguments:
1360 (define p (make-parameter 10))
1363 To provide a new value for the parameter in a dynamic extent, use
1366 (parameterize ((p 20))
1370 The value outside of the dynamic extent of the body is unaffected. To
1371 update the current value, apply it to one argument:
1376 As you can see, the call that updates a parameter returns its previous
1379 All values for the parameter are first run through the CONV procedure,
1380 including INIT, the initial value. The default CONV procedure is the
1381 identity procedure. CONV is commonly used to ensure some set of
1382 invariants on the values that a parameter may have."
1383 (let ((fluid (make-fluid (conv init))))
1384 (make-struct <parameter> 0
1386 (() (fluid-ref fluid))
1387 ((x) (let ((prev (fluid-ref fluid)))
1388 (fluid-set! fluid (conv x))
1392 (define (parameter? x)
1393 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
1395 (define (parameter-fluid p)
1398 (scm-error 'wrong-type-arg "parameter-fluid"
1399 "Not a parameter: ~S" (list p) #f)))
1401 (define (parameter-converter p)
1404 (scm-error 'wrong-type-arg "parameter-fluid"
1405 "Not a parameter: ~S" (list p) #f)))
1407 (define-syntax parameterize
1410 ((_ ((param value) ...) body body* ...)
1411 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
1412 #'(let ((p param) ...)
1413 (if (not (parameter? p))
1414 (scm-error 'wrong-type-arg "parameterize"
1415 "Not a parameter: ~S" (list p) #f))
1417 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
1419 body body* ...)))))))
1421 (define* (fluid->parameter fluid #:optional (conv (lambda (x) x)))
1422 "Make a parameter that wraps a fluid.
1424 The value of the parameter will be the same as the value of the fluid.
1425 If the parameter is rebound in some dynamic extent, perhaps via
1426 `parameterize', the new value will be run through the optional CONV
1427 procedure, as with any parameter. Note that unlike `make-parameter',
1428 CONV is not applied to the initial value."
1429 (make-struct <parameter> 0
1431 (() (fluid-ref fluid))
1432 ((x) (let ((prev (fluid-ref fluid)))
1433 (fluid-set! fluid (conv x))
1439 ;;; Once parameters have booted, define the default prompt tag as being
1443 (set! default-prompt-tag (make-parameter (default-prompt-tag)))
1447 ;;; Current ports as parameters.
1451 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
1453 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
1457 (hashq-remove! (%get-pre-modules-obarray) 'fluid)))
1459 (port-parameterize! current-input-port %current-input-port-fluid
1460 input-port? "expected an input port")
1461 (port-parameterize! current-output-port %current-output-port-fluid
1462 output-port? "expected an output port")
1463 (port-parameterize! current-error-port %current-error-port-fluid
1464 output-port? "expected an output port")
1465 (port-parameterize! current-warning-port %current-warning-port-fluid
1466 output-port? "expected an output port"))
1473 ;; The language can be a symbolic name or a <language> object from
1474 ;; (system base language).
1476 (define current-language (make-parameter 'scheme))
1481 ;;; {High-Level Port Routines}
1484 (define* (open-input-file
1485 file #:key (binary #f) (encoding #f) (guess-encoding #f))
1486 "Takes a string naming an existing file and returns an input port
1487 capable of delivering characters from the file. If the file
1488 cannot be opened, an error is signalled."
1489 (open-file file (if binary "rb" "r")
1491 #:guess-encoding guess-encoding))
1493 (define* (open-output-file file #:key (binary #f) (encoding #f))
1494 "Takes a string naming an output file to be created and returns an
1495 output port capable of writing characters to a new file by that
1496 name. If the file cannot be opened, an error is signalled. If a
1497 file with the given name already exists, the effect is unspecified."
1498 (open-file file (if binary "wb" "w")
1499 #:encoding encoding))
1501 (define* (call-with-input-file
1502 file proc #:key (binary #f) (encoding #f) (guess-encoding #f))
1503 "PROC should be a procedure of one argument, and FILE should be a
1504 string naming a file. The file must
1505 already exist. These procedures call PROC
1506 with one argument: the port obtained by opening the named file for
1507 input or output. If the file cannot be opened, an error is
1508 signalled. If the procedure returns, then the port is closed
1509 automatically and the values yielded by the procedure are returned.
1510 If the procedure does not return, then the port will not be closed
1511 automatically unless it is possible to prove that the port will
1512 never again be used for a read or write operation."
1513 (let ((p (open-input-file file
1516 #:guess-encoding guess-encoding)))
1518 (lambda () (proc p))
1520 (close-input-port p)
1521 (apply values vals)))))
1523 (define* (call-with-output-file file proc #:key (binary #f) (encoding #f))
1524 "PROC should be a procedure of one argument, and FILE should be a
1525 string naming a file. The behaviour is unspecified if the file
1526 already exists. These procedures call PROC
1527 with one argument: the port obtained by opening the named file for
1528 input or output. If the file cannot be opened, an error is
1529 signalled. If the procedure returns, then the port is closed
1530 automatically and the values yielded by the procedure are returned.
1531 If the procedure does not return, then the port will not be closed
1532 automatically unless it is possible to prove that the port will
1533 never again be used for a read or write operation."
1534 (let ((p (open-output-file file #:binary binary #:encoding encoding)))
1536 (lambda () (proc p))
1538 (close-output-port p)
1539 (apply values vals)))))
1541 (define (with-input-from-port port thunk)
1542 (parameterize ((current-input-port port))
1545 (define (with-output-to-port port thunk)
1546 (parameterize ((current-output-port port))
1549 (define (with-error-to-port port thunk)
1550 (parameterize ((current-error-port port))
1553 (define* (with-input-from-file
1554 file thunk #:key (binary #f) (encoding #f) (guess-encoding #f))
1555 "THUNK must be a procedure of no arguments, and FILE must be a
1556 string naming a file. The file must already exist. The file is opened for
1557 input, an input port connected to it is made
1558 the default value returned by `current-input-port',
1559 and the THUNK is called with no arguments.
1560 When the THUNK returns, the port is closed and the previous
1561 default is restored. Returns the values yielded by THUNK. If an
1562 escape procedure is used to escape from the continuation of these
1563 procedures, their behavior is implementation dependent."
1564 (call-with-input-file file
1565 (lambda (p) (with-input-from-port p thunk))
1568 #:guess-encoding guess-encoding))
1570 (define* (with-output-to-file file thunk #:key (binary #f) (encoding #f))
1571 "THUNK must be a procedure of no arguments, and FILE must be a
1572 string naming a file. The effect is unspecified if the file already exists.
1573 The file is opened for output, an output port connected to it is made
1574 the default value returned by `current-output-port',
1575 and the THUNK is called with no arguments.
1576 When the THUNK returns, the port is closed and the previous
1577 default is restored. Returns the values yielded by THUNK. If an
1578 escape procedure is used to escape from the continuation of these
1579 procedures, their behavior is implementation dependent."
1580 (call-with-output-file file
1581 (lambda (p) (with-output-to-port p thunk))
1583 #:encoding encoding))
1585 (define* (with-error-to-file file thunk #:key (binary #f) (encoding #f))
1586 "THUNK must be a procedure of no arguments, and FILE must be a
1587 string naming a file. The effect is unspecified if the file already exists.
1588 The file is opened for output, an output port connected to it is made
1589 the default value returned by `current-error-port',
1590 and the THUNK is called with no arguments.
1591 When the THUNK returns, the port is closed and the previous
1592 default is restored. Returns the values yielded by THUNK. If an
1593 escape procedure is used to escape from the continuation of these
1594 procedures, their behavior is implementation dependent."
1595 (call-with-output-file file
1596 (lambda (p) (with-error-to-port p thunk))
1598 #:encoding encoding))
1600 (define (call-with-input-string string proc)
1601 "Calls the one-argument procedure @var{proc} with a newly created
1602 input port from which @var{string}'s contents may be read. The value
1603 yielded by the @var{proc} is returned."
1604 (proc (open-input-string string)))
1606 (define (with-input-from-string string thunk)
1607 "THUNK must be a procedure of no arguments.
1608 The test of STRING is opened for
1609 input, an input port connected to it is made,
1610 and the THUNK is called with no arguments.
1611 When the THUNK returns, the port is closed.
1612 Returns the values yielded by THUNK. If an
1613 escape procedure is used to escape from the continuation of these
1614 procedures, their behavior is implementation dependent."
1615 (call-with-input-string string
1616 (lambda (p) (with-input-from-port p thunk))))
1618 (define (call-with-output-string proc)
1619 "Calls the one-argument procedure @var{proc} with a newly created output
1620 port. When the function returns, the string composed of the characters
1621 written into the port is returned."
1622 (let ((port (open-output-string)))
1624 (get-output-string port)))
1626 (define (with-output-to-string thunk)
1627 "Calls THUNK and returns its output as a string."
1628 (call-with-output-string
1629 (lambda (p) (with-output-to-port p thunk))))
1631 (define (with-error-to-string thunk)
1632 "Calls THUNK and returns its error output as a string."
1633 (call-with-output-string
1634 (lambda (p) (with-error-to-port p thunk))))
1636 (define the-eof-object (call-with-input-string "" (lambda (p) (read-char p))))
1643 (define (->bool x) (not (not x)))
1650 (define (symbol-append . args)
1651 (string->symbol (apply string-append (map symbol->string args))))
1653 (define (list->symbol . args)
1654 (string->symbol (apply list->string args)))
1656 (define (symbol . args)
1657 (string->symbol (apply string args)))
1664 (define (list-index l k)
1667 (and (not (null? l))
1670 (loop (+ n 1) (cdr l))))))
1674 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1675 ;; `stat' accessors.
1676 (primitive-load-path "ice-9/posix")
1678 (if (provided? 'socket)
1679 (primitive-load-path "ice-9/networking"))
1681 ;; For reference, Emacs file-exists-p uses stat in this same way.
1682 (define file-exists?
1683 (if (provided? 'posix)
1685 (->bool (stat str #f)))
1687 (let ((port (catch 'system-error (lambda () (open-input-file str))
1689 (if port (begin (close-port port) #t)
1692 (define file-is-directory?
1693 (if (provided? 'posix)
1695 (eq? (stat:type (stat str)) 'directory))
1697 (let ((port (catch 'system-error
1699 (open-input-file (string-append str "/.")))
1701 (if port (begin (close-port port) #t)
1704 (define (system-error-errno args)
1705 (if (eq? (car args) 'system-error)
1706 (car (list-ref args 4))
1711 ;;; {Error Handling}
1717 (scm-error 'misc-error #f "?" #f #f))
1719 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1720 (scm-error 'misc-error #f msg (cons message args) #f)))))
1724 ;;; {Time Structures}
1727 (define (tm:sec obj) (vector-ref obj 0))
1728 (define (tm:min obj) (vector-ref obj 1))
1729 (define (tm:hour obj) (vector-ref obj 2))
1730 (define (tm:mday obj) (vector-ref obj 3))
1731 (define (tm:mon obj) (vector-ref obj 4))
1732 (define (tm:year obj) (vector-ref obj 5))
1733 (define (tm:wday obj) (vector-ref obj 6))
1734 (define (tm:yday obj) (vector-ref obj 7))
1735 (define (tm:isdst obj) (vector-ref obj 8))
1736 (define (tm:gmtoff obj) (vector-ref obj 9))
1737 (define (tm:zone obj) (vector-ref obj 10))
1739 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1740 (define (set-tm:min obj val) (vector-set! obj 1 val))
1741 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1742 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1743 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1744 (define (set-tm:year obj val) (vector-set! obj 5 val))
1745 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1746 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1747 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1748 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1749 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1751 (define (tms:clock obj) (vector-ref obj 0))
1752 (define (tms:utime obj) (vector-ref obj 1))
1753 (define (tms:stime obj) (vector-ref obj 2))
1754 (define (tms:cutime obj) (vector-ref obj 3))
1755 (define (tms:cstime obj) (vector-ref obj 4))
1759 ;;; {File Descriptors and Ports}
1762 (define file-position ftell)
1763 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1764 (seek port offset whence))
1766 (define (move->fdes fd/port fd)
1767 (cond ((integer? fd/port)
1768 (dup->fdes fd/port fd)
1772 (primitive-move->fdes fd/port fd)
1773 (set-port-revealed! fd/port 1)
1776 (define (release-port-handle port)
1777 (let ((revealed (port-revealed port)))
1779 (set-port-revealed! port (- revealed 1)))))
1784 (fdopen (dup->fdes port/fd) mode))
1785 ((port/fd mode new-fd)
1786 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1787 (set-port-revealed! port 1)
1793 (dup->port port/fd "r"))
1795 (dup->port port/fd "r" new-fd))))
1797 (define dup->outport
1800 (dup->port port/fd "w"))
1802 (dup->port port/fd "w" new-fd))))
1807 (if (integer? port/fd)
1809 (dup->port port/fd (port-mode port/fd))))
1811 (if (integer? port/fd)
1812 (dup->fdes port/fd new-fd)
1813 (dup->port port/fd (port-mode port/fd) new-fd)))))
1815 (define (duplicate-port port modes)
1816 (dup->port port modes))
1818 (define (fdes->inport fdes)
1819 (let loop ((rest-ports (fdes->ports fdes)))
1820 (cond ((null? rest-ports)
1821 (let ((result (fdopen fdes "r")))
1822 (set-port-revealed! result 1)
1824 ((input-port? (car rest-ports))
1825 (set-port-revealed! (car rest-ports)
1826 (+ (port-revealed (car rest-ports)) 1))
1829 (loop (cdr rest-ports))))))
1831 (define (fdes->outport fdes)
1832 (let loop ((rest-ports (fdes->ports fdes)))
1833 (cond ((null? rest-ports)
1834 (let ((result (fdopen fdes "w")))
1835 (set-port-revealed! result 1)
1837 ((output-port? (car rest-ports))
1838 (set-port-revealed! (car rest-ports)
1839 (+ (port-revealed (car rest-ports)) 1))
1842 (loop (cdr rest-ports))))))
1844 (define (port->fdes port)
1845 (set-port-revealed! port (+ (port-revealed port) 1))
1848 (define (setenv name value)
1850 (putenv (string-append name "=" value))
1853 (define (unsetenv name)
1854 "Remove the entry for NAME from the environment."
1862 (let-syntax ((compile-time-case
1865 ((_ exp clauses ...)
1866 (let ((val (primitive-eval (syntax->datum #'exp))))
1867 (let next-clause ((clauses #'(clauses ...)))
1868 (syntax-case clauses (else)
1870 (syntax-violation 'compile-time-case
1871 "all clauses failed to match" stx))
1874 ((((k ...) form ...) clauses ...)
1875 (if (memv val (syntax->datum #'(k ...)))
1877 (next-clause #'(clauses ...))))))))))))
1878 ;; emacs: (put 'compile-time-case 'scheme-indent-function 1)
1879 (compile-time-case (system-file-name-convention)
1881 (define (file-name-separator? c)
1884 (define file-name-separator-string "/")
1886 (define (absolute-file-name? file-name)
1887 (string-prefix? "/" file-name)))
1890 (define (file-name-separator? c)
1894 (define file-name-separator-string "/")
1896 (define (absolute-file-name? file-name)
1897 (define (file-name-separator-at-index? idx)
1898 (and (> (string-length file-name) idx)
1899 (file-name-separator? (string-ref file-name idx))))
1900 (define (unc-file-name?)
1901 ;; Universal Naming Convention (UNC) file-names start with \\,
1902 ;; and are always absolute. See:
1903 ;; http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
1904 (and (file-name-separator-at-index? 0)
1905 (file-name-separator-at-index? 1)))
1906 (define (has-drive-specifier?)
1907 (and (>= (string-length file-name) 2)
1908 (let ((drive (string-ref file-name 0)))
1909 (or (char<=? #\a drive #\z)
1910 (char<=? #\A drive #\Z)))
1911 (eqv? (string-ref file-name 1) #\:)))
1912 (or (unc-file-name?)
1913 (if (has-drive-specifier?)
1914 (file-name-separator-at-index? 2)
1915 (file-name-separator-at-index? 0)))))))
1917 (define (in-vicinity vicinity file)
1918 (let ((tail (let ((len (string-length vicinity)))
1921 (string-ref vicinity (- len 1))))))
1922 (string-append vicinity
1923 (if (or (not tail) (file-name-separator? tail))
1925 file-name-separator-string)
1930 ;;; {Help for scm_shell}
1932 ;;; The argument-processing code used by Guile-based shells generates
1933 ;;; Scheme code based on the argument list. This page contains help
1934 ;;; functions for the code it generates.
1937 (define (command-line) (program-arguments))
1939 ;; This is mostly for the internal use of the code generated by
1940 ;; scm_compile_shell_switches.
1942 (define (load-user-init)
1943 (let* ((home (or (getenv "HOME")
1944 (false-if-exception (passwd:dir (getpwuid (getuid))))
1945 file-name-separator-string)) ;; fallback for cygwin etc.
1946 (init-file (in-vicinity home ".guile")))
1947 (if (file-exists? init-file)
1948 (primitive-load init-file))))
1952 ;;; {The interpreter stack}
1955 ;; %stacks defined in stacks.c
1956 (define (%start-stack tag thunk)
1957 (let ((prompt-tag (make-prompt-tag "start-stack")))
1961 (with-fluids ((%stacks (acons tag prompt-tag
1962 (or (fluid-ref %stacks) '()))))
1965 (%start-stack tag (lambda () (apply k args)))))))
1967 (define-syntax-rule (start-stack tag exp)
1968 (%start-stack tag (lambda () exp)))
1972 ;;; {Loading by paths}
1975 ;;; Load a Scheme source file named NAME, searching for it in the
1976 ;;; directories listed in %load-path, and applying each of the file
1977 ;;; name extensions listed in %load-extensions.
1978 (define (load-from-path name)
1979 (start-stack 'load-stack
1980 (primitive-load-path name)))
1982 (define-syntax-rule (add-to-load-path elt)
1983 "Add ELT to Guile's load path, at compile-time and at run-time."
1984 (eval-when (expand load eval)
1985 (set! %load-path (cons elt (delete elt %load-path)))))
1987 (define %load-verbosely #f)
1988 (define (assert-load-verbosity v) (set! %load-verbosely v))
1990 (define (%load-announce file)
1992 (with-output-to-port (current-warning-port)
1995 (display "loading ")
2000 (set! %load-hook %load-announce)
2004 ;;; {Reader Extensions}
2006 ;;; Reader code for various "#c" forms.
2009 (define read-eval? (make-fluid #f))
2010 (read-hash-extend #\.
2012 (if (fluid-ref read-eval?)
2013 (eval (read port) (interaction-environment))
2015 "#. read expansion found and read-eval? is #f."))))
2019 ;;; {Low Level Modules}
2021 ;;; These are the low level data structures for modules.
2023 ;;; Every module object is of the type 'module-type', which is a record
2024 ;;; consisting of the following members:
2026 ;;; - eval-closure: A deprecated field, to be removed in Guile 2.2.
2028 ;;; - obarray: a hash table that maps symbols to variable objects. In this
2029 ;;; hash table, the definitions are found that are local to the module (that
2030 ;;; is, not imported from other modules). When looking up bindings in the
2031 ;;; module, this hash table is searched first.
2033 ;;; - binder: either #f or a function taking a module and a symbol argument.
2034 ;;; If it is a function it is called after the obarray has been
2035 ;;; unsuccessfully searched for a binding. It then can provide bindings
2036 ;;; that would otherwise not be found locally in the module.
2038 ;;; - uses: a list of modules from which non-local bindings can be inherited.
2039 ;;; These modules are the third place queried for bindings after the obarray
2040 ;;; has been unsuccessfully searched and the binder function did not deliver
2041 ;;; a result either.
2043 ;;; - transformer: either #f or a function taking a scheme expression as
2044 ;;; delivered by read. If it is a function, it will be called to perform
2045 ;;; syntax transformations (e. g. makro expansion) on the given scheme
2046 ;;; expression. The output of the transformer function will then be passed
2047 ;;; to Guile's internal memoizer. This means that the output must be valid
2048 ;;; scheme code. The only exception is, that the output may make use of the
2049 ;;; syntax extensions provided to identify the modules that a binding
2052 ;;; - name: the name of the module. This is used for all kinds of printing
2053 ;;; outputs. In certain places the module name also serves as a way of
2054 ;;; identification. When adding a module to the uses list of another
2055 ;;; module, it is made sure that the new uses list will not contain two
2056 ;;; modules of the same name.
2058 ;;; - kind: classification of the kind of module. The value is (currently?)
2059 ;;; only used for printing. It has no influence on how a module is treated.
2060 ;;; Currently the following values are used when setting the module kind:
2061 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
2062 ;;; is set, it defaults to 'module.
2064 ;;; - duplicates-handlers: a list of procedures that get called to make a
2065 ;;; choice between two duplicate bindings when name clashes occur. See the
2066 ;;; `duplicate-handlers' global variable below.
2068 ;;; - observers: a list of procedures that get called when the module is
2071 ;;; - weak-observers: a weak-key hash table of procedures that get called
2072 ;;; when the module is modified. See `module-observe-weak' for details.
2074 ;;; In addition, the module may (must?) contain a binding for
2075 ;;; `%module-public-interface'. This variable should be bound to a module
2076 ;;; representing the exported interface of a module. See the
2077 ;;; `module-public-interface' and `module-export!' procedures.
2079 ;;; !!! warning: The interface to lazy binder procedures is going
2080 ;;; to be changed in an incompatible way to permit all the basic
2081 ;;; module ops to be virtualized.
2083 ;;; (make-module size use-list lazy-binding-proc) => module
2084 ;;; module-{obarray,uses,binder}[|-set!]
2085 ;;; (module? obj) => [#t|#f]
2086 ;;; (module-locally-bound? module symbol) => [#t|#f]
2087 ;;; (module-bound? module symbol) => [#t|#f]
2088 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
2089 ;;; (module-symbol-interned? module symbol) => [#t|#f]
2090 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
2091 ;;; (module-variable module symbol) => [#<variable ...> | #f]
2092 ;;; (module-symbol-binding module symbol opt-value)
2093 ;;; => [ <obj> | opt-value | an error occurs ]
2094 ;;; (module-make-local-var! module symbol) => #<variable...>
2095 ;;; (module-add! module symbol var) => unspecified
2096 ;;; (module-remove! module symbol) => unspecified
2097 ;;; (module-for-each proc module) => unspecified
2098 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
2099 ;;; (set-current-module module) => unspecified
2100 ;;; (current-module) => #<module...>
2106 ;;; {Printing Modules}
2109 ;; This is how modules are printed. You can re-define it.
2110 (define (%print-module mod port)
2112 (display (or (module-kind mod) "module") port)
2114 (display (module-name mod) port)
2116 (display (number->string (object-address mod) 16) port)
2120 ;; Locally extend the syntax to allow record accessors to be defined at
2121 ;; compile-time. Cache the rtd locally to the constructor, the getters and
2122 ;; the setters, in order to allow for redefinition of the record type; not
2123 ;; relevant in the case of modules, but perhaps if we make this public, it
2126 ((define-record-type
2128 (define (make-id scope . fragments)
2129 (datum->syntax scope
2130 (apply symbol-append
2132 (if (symbol? x) x (syntax->datum x)))
2135 (define (getter rtd type-name field slot)
2136 #`(define #,(make-id rtd type-name '- field)
2138 (lambda (#,type-name)
2139 (if (eq? (struct-vtable #,type-name) rtd)
2140 (struct-ref #,type-name #,slot)
2141 (%record-type-error rtd #,type-name))))))
2143 (define (setter rtd type-name field slot)
2144 #`(define #,(make-id rtd 'set- type-name '- field '!)
2146 (lambda (#,type-name val)
2147 (if (eq? (struct-vtable #,type-name) rtd)
2148 (struct-set! #,type-name #,slot val)
2149 (%record-type-error rtd #,type-name))))))
2151 (define (accessors rtd type-name fields n exp)
2152 (syntax-case fields ()
2154 (((field #:no-accessors) field* ...) (identifier? #'field)
2155 (accessors rtd type-name #'(field* ...) (1+ n)
2157 (((field #:no-setter) field* ...) (identifier? #'field)
2158 (accessors rtd type-name #'(field* ...) (1+ n)
2160 #,(getter rtd type-name #'field n))))
2161 (((field #:no-getter) field* ...) (identifier? #'field)
2162 (accessors rtd type-name #'(field* ...) (1+ n)
2164 #,(setter rtd type-name #'field n))))
2165 ((field field* ...) (identifier? #'field)
2166 (accessors rtd type-name #'(field* ...) (1+ n)
2168 #,(getter rtd type-name #'field n)
2169 #,(setter rtd type-name #'field n))))))
2171 (define (predicate rtd type-name fields exp)
2173 rtd type-name fields 0
2176 (define (#,(make-id rtd type-name '?) obj)
2177 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
2179 (define (field-list fields)
2180 (syntax-case fields ()
2182 (((f . opts) . rest) (identifier? #'f)
2183 (cons #'f (field-list #'rest)))
2184 ((f . rest) (identifier? #'f)
2185 (cons #'f (field-list #'rest)))))
2187 (define (constructor rtd type-name fields exp)
2188 (let* ((ctor (make-id rtd type-name '-constructor))
2189 (args (field-list fields))
2192 (predicate rtd type-name fields
2197 (let ((s (allocate-struct rtd #,n)))
2200 #`(struct-set! s #,slot #,arg))
2203 (struct-set! #,rtd (+ vtable-offset-user 2)
2206 (define (type type-name printer fields)
2207 (define (make-layout)
2208 (let lp ((fields fields) (slots '()))
2209 (syntax-case fields ()
2210 (() (datum->syntax #'here
2212 (apply string-append slots))))
2213 ((_ . rest) (lp #'rest (cons "pw" slots))))))
2215 (let ((rtd (make-id type-name type-name '-type)))
2216 (constructor rtd type-name fields
2219 (make-struct record-type-vtable 0
2223 '#,(field-list fields)))
2224 (set-struct-vtable-name! #,rtd '#,type-name)))))
2227 ((_ type-name printer (field ...))
2228 (type #'type-name #'printer #'(field ...)))))))
2232 ;; A module is characterized by an obarray in which local symbols
2233 ;; are interned, a list of modules, "uses", from which non-local
2234 ;; bindings can be inherited, and an optional lazy-binder which
2235 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
2236 ;; bindings that would otherwise not be found locally in the module.
2238 ;; NOTE: If you change the set of fields or their order, you also need to
2239 ;; change the constants in libguile/modules.h.
2241 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
2242 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
2243 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
2245 (define-record-type module
2246 (lambda (obj port) (%print-module obj port))
2251 (transformer #:no-getter)
2255 (import-obarray #:no-setter)
2257 (weak-observers #:no-setter)
2265 ;; make-module &opt size uses binder
2267 ;; Create a new module, perhaps with a particular size of obarray,
2268 ;; initial uses list, or binding procedure.
2270 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
2271 (if (not (integer? size))
2272 (error "Illegal size to make-module." size))
2273 (if (not (and (list? uses)
2274 (and-map module? uses)))
2275 (error "Incorrect use list." uses))
2276 (if (and binder (not (procedure? binder)))
2278 "Lazy-binder expected to be a procedure or #f." binder))
2280 (module-constructor (make-hash-table size)
2281 uses binder #f macroexpand
2285 (make-weak-key-hash-table 31) #f
2286 (make-hash-table 7) #f #f #f))
2291 ;;; {Observer protocol}
2294 (define (module-observe module proc)
2295 (set-module-observers! module (cons proc (module-observers module)))
2298 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
2299 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
2300 ;; be any Scheme object). PROC is invoked and passed MODULE any time
2301 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
2302 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
2305 ;; The two-argument version is kept for backward compatibility: when called
2306 ;; with two arguments, the observer gets unregistered when closure PROC
2307 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
2308 (hashq-set! (module-weak-observers module) observer-id proc))
2310 (define (module-unobserve token)
2311 (let ((module (car token))
2314 (hash-remove! (module-weak-observers module) id)
2315 (set-module-observers! module (delq1! id (module-observers module)))))
2318 (define module-defer-observers #f)
2319 (define module-defer-observers-mutex (make-mutex 'recursive))
2320 (define module-defer-observers-table (make-hash-table))
2322 (define (module-modified m)
2323 (if module-defer-observers
2324 (hash-set! module-defer-observers-table m #t)
2325 (module-call-observers m)))
2327 ;;; This function can be used to delay calls to observers so that they
2328 ;;; can be called once only in the face of massive updating of modules.
2330 (define (call-with-deferred-observers thunk)
2333 (lock-mutex module-defer-observers-mutex)
2334 (set! module-defer-observers #t))
2337 (set! module-defer-observers #f)
2338 (hash-for-each (lambda (m dummy)
2339 (module-call-observers m))
2340 module-defer-observers-table)
2341 (hash-clear! module-defer-observers-table)
2342 (unlock-mutex module-defer-observers-mutex))))
2344 (define (module-call-observers m)
2345 (for-each (lambda (proc) (proc m)) (module-observers m))
2347 ;; We assume that weak observers don't (un)register themselves as they are
2348 ;; called since this would preclude proper iteration over the hash table
2350 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
2354 ;;; {Module Searching in General}
2356 ;;; We sometimes want to look for properties of a symbol
2357 ;;; just within the obarray of one module. If the property
2358 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
2359 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
2362 ;;; Other times, we want to test for a symbol property in the obarray
2363 ;;; of M and, if it is not found there, try each of the modules in the
2364 ;;; uses list of M. This is the normal way of testing for some
2365 ;;; property, so we state these properties without qualification as
2366 ;;; in: ``The symbol 'fnord is interned in module M because it is
2367 ;;; interned locally in module M2 which is a member of the uses list
2371 ;; module-search fn m
2373 ;; return the first non-#f result of FN applied to M and then to
2374 ;; the modules in the uses of m, and so on recursively. If all applications
2375 ;; return #f, then so does this function.
2377 (define (module-search fn m v)
2380 (or (module-search fn (car pos) v)
2383 (loop (module-uses m))))
2386 ;;; {Is a symbol bound in a module?}
2388 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
2389 ;;; of S in M has been set to some well-defined value.
2392 ;; module-locally-bound? module symbol
2394 ;; Is a symbol bound (interned and defined) locally in a given module?
2396 (define (module-locally-bound? m v)
2397 (let ((var (module-local-variable m v)))
2399 (variable-bound? var))))
2401 ;; module-bound? module symbol
2403 ;; Is a symbol bound (interned and defined) anywhere in a given module
2406 (define (module-bound? m v)
2407 (let ((var (module-variable m v)))
2409 (variable-bound? var))))
2411 ;;; {Is a symbol interned in a module?}
2413 ;;; Symbol S in Module M is interned if S occurs in
2414 ;;; of S in M has been set to some well-defined value.
2416 ;;; It is possible to intern a symbol in a module without providing
2417 ;;; an initial binding for the corresponding variable. This is done
2419 ;;; (module-add! module symbol (make-undefined-variable))
2421 ;;; In that case, the symbol is interned in the module, but not
2422 ;;; bound there. The unbound symbol shadows any binding for that
2423 ;;; symbol that might otherwise be inherited from a member of the uses list.
2426 (define (module-obarray-get-handle ob key)
2427 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
2429 (define (module-obarray-ref ob key)
2430 ((if (symbol? key) hashq-ref hash-ref) ob key))
2432 (define (module-obarray-set! ob key val)
2433 ((if (symbol? key) hashq-set! hash-set!) ob key val))
2435 (define (module-obarray-remove! ob key)
2436 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
2438 ;; module-symbol-locally-interned? module symbol
2440 ;; is a symbol interned (not neccessarily defined) locally in a given module
2441 ;; or its uses? Interned symbols shadow inherited bindings even if
2442 ;; they are not themselves bound to a defined value.
2444 (define (module-symbol-locally-interned? m v)
2445 (not (not (module-obarray-get-handle (module-obarray m) v))))
2447 ;; module-symbol-interned? module symbol
2449 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
2450 ;; or its uses? Interned symbols shadow inherited bindings even if
2451 ;; they are not themselves bound to a defined value.
2453 (define (module-symbol-interned? m v)
2454 (module-search module-symbol-locally-interned? m v))
2457 ;;; {Mapping modules x symbols --> variables}
2460 ;; module-local-variable module symbol
2461 ;; return the local variable associated with a MODULE and SYMBOL.
2463 ;;; This function is very important. It is the only function that can
2464 ;;; return a variable from a module other than the mutators that store
2465 ;;; new variables in modules. Therefore, this function is the location
2466 ;;; of the "lazy binder" hack.
2468 ;;; If symbol is defined in MODULE, and if the definition binds symbol
2469 ;;; to a variable, return that variable object.
2471 ;;; If the symbols is not found at first, but the module has a lazy binder,
2472 ;;; then try the binder.
2474 ;;; If the symbol is not found at all, return #f.
2476 ;;; (This is now written in C, see `modules.c'.)
2479 ;;; {Mapping modules x symbols --> bindings}
2481 ;;; These are similar to the mapping to variables, except that the
2482 ;;; variable is dereferenced.
2485 ;; module-symbol-binding module symbol opt-value
2487 ;; return the binding of a variable specified by name within
2488 ;; a given module, signalling an error if the variable is unbound.
2489 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2490 ;; return OPT-VALUE.
2492 (define (module-symbol-local-binding m v . opt-val)
2493 (let ((var (module-local-variable m v)))
2494 (if (and var (variable-bound? var))
2496 (if (not (null? opt-val))
2498 (error "Locally unbound variable." v)))))
2500 ;; module-symbol-binding module symbol opt-value
2502 ;; return the binding of a variable specified by name within
2503 ;; a given module, signalling an error if the variable is unbound.
2504 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2505 ;; return OPT-VALUE.
2507 (define (module-symbol-binding m v . opt-val)
2508 (let ((var (module-variable m v)))
2509 (if (and var (variable-bound? var))
2511 (if (not (null? opt-val))
2513 (error "Unbound variable." v)))))
2518 ;;; {Adding Variables to Modules}
2521 ;; module-make-local-var! module symbol
2523 ;; ensure a variable for V in the local namespace of M.
2524 ;; If no variable was already there, then create a new and uninitialzied
2527 ;; This function is used in modules.c.
2529 (define (module-make-local-var! m v)
2530 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2533 ;; Mark as modified since this function is called when
2534 ;; the standard eval closure defines a binding
2538 ;; Create a new local variable.
2539 (let ((local-var (make-undefined-variable)))
2540 (module-add! m v local-var)
2543 ;; module-ensure-local-variable! module symbol
2545 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2546 ;; there is no binding for SYMBOL, create a new uninitialized
2547 ;; variable. Return the local variable.
2549 (define (module-ensure-local-variable! module symbol)
2550 (or (module-local-variable module symbol)
2551 (let ((var (make-undefined-variable)))
2552 (module-add! module symbol var)
2555 ;; module-add! module symbol var
2557 ;; ensure a particular variable for V in the local namespace of M.
2559 (define (module-add! m v var)
2560 (if (not (variable? var))
2561 (error "Bad variable to module-add!" var))
2562 (if (not (symbol? v))
2563 (error "Bad symbol to module-add!" v))
2564 (module-obarray-set! (module-obarray m) v var)
2565 (module-modified m))
2569 ;; make sure that a symbol is undefined in the local namespace of M.
2571 (define (module-remove! m v)
2572 (module-obarray-remove! (module-obarray m) v)
2573 (module-modified m))
2575 (define (module-clear! m)
2576 (hash-clear! (module-obarray m))
2577 (module-modified m))
2579 ;; MODULE-FOR-EACH -- exported
2581 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2583 (define (module-for-each proc module)
2584 (hash-for-each proc (module-obarray module)))
2586 (define (module-map proc module)
2587 (hash-map->list proc (module-obarray module)))
2591 ;; Modules exist in a separate namespace from values, because you generally do
2592 ;; not want the name of a submodule, which you might not even use, to collide
2593 ;; with local variables that happen to be named the same as the submodule.
2595 (define (module-ref-submodule module name)
2596 (or (hashq-ref (module-submodules module) name)
2597 (and (module-submodule-binder module)
2598 ((module-submodule-binder module) module name))))
2600 (define (module-define-submodule! module name submodule)
2601 (hashq-set! (module-submodules module) name submodule))
2605 ;;; {Module-based Loading}
2608 (define (save-module-excursion thunk)
2609 (let ((inner-module (current-module))
2611 (dynamic-wind (lambda ()
2612 (set! outer-module (current-module))
2613 (set-current-module inner-module)
2614 (set! inner-module #f))
2617 (set! inner-module (current-module))
2618 (set-current-module outer-module)
2619 (set! outer-module #f)))))
2623 ;;; {MODULE-REF -- exported}
2626 ;; Returns the value of a variable called NAME in MODULE or any of its
2627 ;; used modules. If there is no such variable, then if the optional third
2628 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2630 (define (module-ref module name . rest)
2631 (let ((variable (module-variable module name)))
2632 (if (and variable (variable-bound? variable))
2633 (variable-ref variable)
2635 (error "No variable named" name 'in module)
2636 (car rest) ; default value
2639 ;; MODULE-SET! -- exported
2641 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2642 ;; to VALUE; if there is no such variable, an error is signaled.
2644 (define (module-set! module name value)
2645 (let ((variable (module-variable module name)))
2647 (variable-set! variable value)
2648 (error "No variable named" name 'in module))))
2650 ;; MODULE-DEFINE! -- exported
2652 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2653 ;; variable, it is added first.
2655 (define (module-define! module name value)
2656 (let ((variable (module-local-variable module name)))
2659 (variable-set! variable value)
2660 (module-modified module))
2661 (let ((variable (make-variable value)))
2662 (module-add! module name variable)))))
2664 ;; MODULE-DEFINED? -- exported
2666 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2669 (define (module-defined? module name)
2670 (let ((variable (module-variable module name)))
2671 (and variable (variable-bound? variable))))
2673 ;; MODULE-USE! module interface
2675 ;; Add INTERFACE to the list of interfaces used by MODULE.
2677 (define (module-use! module interface)
2678 (if (not (or (eq? module interface)
2679 (memq interface (module-uses module))))
2681 ;; Newly used modules must be appended rather than consed, so that
2682 ;; `module-variable' traverses the use list starting from the first
2684 (set-module-uses! module (append (module-uses module)
2686 (hash-clear! (module-import-obarray module))
2687 (module-modified module))))
2689 ;; MODULE-USE-INTERFACES! module interfaces
2691 ;; Same as MODULE-USE!, but only notifies module observers after all
2692 ;; interfaces are added to the inports list.
2694 (define (module-use-interfaces! module interfaces)
2695 (let* ((cur (module-uses module))
2696 (new (let lp ((in interfaces) (out '()))
2700 (let ((iface (car in)))
2701 (if (or (memq iface cur) (memq iface out))
2703 (cons iface out))))))))
2704 (set-module-uses! module (append cur new))
2705 (hash-clear! (module-import-obarray module))
2706 (module-modified module)))
2710 ;;; {Recursive Namespaces}
2712 ;;; A hierarchical namespace emerges if we consider some module to be
2713 ;;; root, and submodules of that module to be nested namespaces.
2715 ;;; The routines here manage variable names in hierarchical namespace.
2716 ;;; Each variable name is a list of elements, looked up in successively nested
2719 ;;; (nested-ref some-root-module '(foo bar baz))
2720 ;;; => <value of a variable named baz in the submodule bar of
2721 ;;; the submodule foo of some-root-module>
2726 ;;; ;; a-root is a module
2727 ;;; ;; name is a list of symbols
2729 ;;; nested-ref a-root name
2730 ;;; nested-set! a-root name val
2731 ;;; nested-define! a-root name val
2732 ;;; nested-remove! a-root name
2734 ;;; These functions manipulate values in namespaces. For referencing the
2735 ;;; namespaces themselves, use the following:
2737 ;;; nested-ref-module a-root name
2738 ;;; nested-define-module! a-root name mod
2740 ;;; (current-module) is a natural choice for a root so for convenience there are
2743 ;;; local-ref name == nested-ref (current-module) name
2744 ;;; local-set! name val == nested-set! (current-module) name val
2745 ;;; local-define name val == nested-define! (current-module) name val
2746 ;;; local-remove name == nested-remove! (current-module) name
2747 ;;; local-ref-module name == nested-ref-module (current-module) name
2748 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2752 (define (nested-ref root names)
2755 (let loop ((cur root)
2759 (module-ref cur head #f)
2760 (let ((cur (module-ref-submodule cur head)))
2762 (loop cur (car tail) (cdr tail))))))))
2764 (define (nested-set! root names val)
2765 (let loop ((cur root)
2769 (module-set! cur head val)
2770 (let ((cur (module-ref-submodule cur head)))
2772 (error "failed to resolve module" names)
2773 (loop cur (car tail) (cdr tail)))))))
2775 (define (nested-define! root names val)
2776 (let loop ((cur root)
2780 (module-define! cur head val)
2781 (let ((cur (module-ref-submodule cur head)))
2783 (error "failed to resolve module" names)
2784 (loop cur (car tail) (cdr tail)))))))
2786 (define (nested-remove! root names)
2787 (let loop ((cur root)
2791 (module-remove! cur head)
2792 (let ((cur (module-ref-submodule cur head)))
2794 (error "failed to resolve module" names)
2795 (loop cur (car tail) (cdr tail)))))))
2798 (define (nested-ref-module root names)
2799 (let loop ((cur root)
2803 (let ((cur (module-ref-submodule cur (car names))))
2805 (loop cur (cdr names)))))))
2807 (define (nested-define-module! root names module)
2809 (error "can't redefine root module" root module)
2810 (let loop ((cur root)
2814 (module-define-submodule! cur head module)
2815 (let ((cur (or (module-ref-submodule cur head)
2816 (let ((m (make-module 31)))
2817 (set-module-kind! m 'directory)
2818 (set-module-name! m (append (module-name cur)
2820 (module-define-submodule! cur head m)
2822 (loop cur (car tail) (cdr tail)))))))
2825 (define (local-ref names)
2826 (nested-ref (current-module) names))
2828 (define (local-set! names val)
2829 (nested-set! (current-module) names val))
2831 (define (local-define names val)
2832 (nested-define! (current-module) names val))
2834 (define (local-remove names)
2835 (nested-remove! (current-module) names))
2837 (define (local-ref-module names)
2838 (nested-ref-module (current-module) names))
2840 (define (local-define-module names mod)
2841 (nested-define-module! (current-module) names mod))
2847 ;;; {The (guile) module}
2849 ;;; The standard module, which has the core Guile bindings. Also called the
2850 ;;; "root module", as it is imported by many other modules, but it is not
2851 ;;; necessarily the root of anything; and indeed, the module named '() might be
2852 ;;; better thought of as a root.
2855 ;; The root module uses the pre-modules-obarray as its obarray. This
2856 ;; special obarray accumulates all bindings that have been established
2857 ;; before the module system is fully booted.
2859 ;; (The obarray continues to be used by code that has been closed over
2860 ;; before the module system has been booted.)
2862 (define the-root-module
2863 (let ((m (make-module 0)))
2864 (set-module-obarray! m (%get-pre-modules-obarray))
2865 (set-module-name! m '(guile))
2868 ;; The root interface is a module that uses the same obarray as the
2869 ;; root module. It does not allow new definitions, tho.
2871 (define the-scm-module
2872 (let ((m (make-module 0)))
2873 (set-module-obarray! m (%get-pre-modules-obarray))
2874 (set-module-name! m '(guile))
2875 (set-module-kind! m 'interface)
2877 ;; In Guile 1.8 and earlier M was its own public interface.
2878 (set-module-public-interface! m m)
2882 (set-module-public-interface! the-root-module the-scm-module)
2886 ;; Now that we have a root module, even though modules aren't fully booted,
2887 ;; expand the definition of resolve-module.
2889 (define (resolve-module name . args)
2890 (if (equal? name '(guile))
2892 (error "unexpected module to resolve during module boot" name)))
2894 ;; Cheat. These bindings are needed by modules.c, but we don't want
2895 ;; to move their real definition here because that would be unnatural.
2897 (define define-module* #f)
2898 (define process-use-modules #f)
2899 (define module-export! #f)
2900 (define default-duplicate-binding-procedures #f)
2902 ;; This boots the module system. All bindings needed by modules.c
2903 ;; must have been defined by now.
2905 (set-current-module the-root-module)
2910 ;; Now that modules are booted, give module-name its final definition.
2913 (let ((accessor (record-accessor module-type 'name)))
2916 (let ((name (list (gensym))))
2917 ;; Name MOD and bind it in the module root so that it's visible to
2918 ;; `resolve-module'. This is important as `psyntax' stores module
2919 ;; names and relies on being able to `resolve-module' them.
2920 (set-module-name! mod name)
2921 (nested-define-module! (resolve-module '() #f) name mod)
2924 (define (make-modules-in module name)
2925 (or (nested-ref-module module name)
2926 (let ((m (make-module 31)))
2927 (set-module-kind! m 'directory)
2928 (set-module-name! m (append (module-name module) name))
2929 (nested-define-module! module name m)
2932 (define (beautify-user-module! module)
2933 (let ((interface (module-public-interface module)))
2934 (if (or (not interface)
2935 (eq? interface module))
2936 (let ((interface (make-module 31)))
2937 (set-module-name! interface (module-name module))
2938 (set-module-version! interface (module-version module))
2939 (set-module-kind! interface 'interface)
2940 (set-module-public-interface! module interface))))
2941 (if (and (not (memq the-scm-module (module-uses module)))
2942 (not (eq? module the-root-module)))
2943 ;; Import the default set of bindings (from the SCM module) in MODULE.
2944 (module-use! module the-scm-module)))
2946 (define (version-matches? version-ref target)
2947 (define (sub-versions-match? v-refs t)
2948 (define (sub-version-matches? v-ref t)
2949 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2951 ((number? v-ref) (eqv? v-ref t))
2954 ((>=) (>= t (cadr v-ref)))
2955 ((<=) (<= t (cadr v-ref)))
2956 ((and) (and-map matches? (cdr v-ref)))
2957 ((or) (or-map matches? (cdr v-ref)))
2958 ((not) (not (matches? (cadr v-ref))))
2959 (else (error "Invalid sub-version reference" v-ref))))
2960 (else (error "Invalid sub-version reference" v-ref)))))
2962 (and (not (null? t))
2963 (sub-version-matches? (car v-refs) (car t))
2964 (sub-versions-match? (cdr v-refs) (cdr t)))))
2966 (let ((matches? (lambda (v) (version-matches? v target))))
2967 (or (null? version-ref)
2968 (case (car version-ref)
2969 ((and) (and-map matches? (cdr version-ref)))
2970 ((or) (or-map matches? (cdr version-ref)))
2971 ((not) (not (matches? (cadr version-ref))))
2972 (else (sub-versions-match? version-ref target))))))
2974 (define (make-fresh-user-module)
2975 (let ((m (make-module)))
2976 (beautify-user-module! m)
2979 ;; NOTE: This binding is used in libguile/modules.c.
2981 (define resolve-module
2982 (let ((root (make-module)))
2983 (set-module-name! root '())
2984 ;; Define the-root-module as '(guile).
2985 (module-define-submodule! root 'guile the-root-module)
2987 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2988 (let ((already (nested-ref-module root name)))
2991 (or (not autoload) (module-public-interface already)))
2992 ;; A hit, a palpable hit.
2994 (not (version-matches? version (module-version already))))
2995 (error "incompatible module version already loaded" name))
2998 ;; Try to autoload the module, and recurse.
2999 (try-load-module name version)
3000 (resolve-module name #f #:ensure ensure))
3002 ;; No module found (or if one was, it had no public interface), and
3003 ;; we're not autoloading. Make an empty module if #:ensure is true.
3006 (make-modules-in root name)))))))))
3009 (define (try-load-module name version)
3010 (try-module-autoload name version))
3012 (define (reload-module m)
3013 "Revisit the source file corresponding to the module @var{m}."
3014 (let ((f (module-filename m)))
3016 (save-module-excursion
3018 ;; Re-set the initial environment, as in try-module-autoload.
3019 (set-current-module (make-fresh-user-module))
3020 (primitive-load-path f)
3022 ;; Though we could guess, we *should* know it.
3023 (error "unknown file name for module" m))))
3025 (define (purify-module! module)
3026 "Removes bindings in MODULE which are inherited from the (guile) module."
3027 (let ((use-list (module-uses module)))
3028 (if (and (pair? use-list)
3029 (eq? (car (last-pair use-list)) the-scm-module))
3030 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
3032 ;; Return a module that is an interface to the module designated by
3035 ;; `resolve-interface' takes four keyword arguments:
3037 ;; #:select SELECTION
3039 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
3040 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
3041 ;; is the name in the used module and SEEN is the name in the using
3042 ;; module. Note that SEEN is also passed through RENAMER, below. The
3043 ;; default is to select all bindings. If you specify no selection but
3044 ;; a renamer, only the bindings that already exist in the used module
3045 ;; are made available in the interface. Bindings that are added later
3046 ;; are not picked up.
3050 ;; BINDINGS is a list of bindings which should not be imported.
3054 ;; PREFIX is a symbol that will be appended to each exported name.
3055 ;; The default is to not perform any renaming.
3057 ;; #:renamer RENAMER
3059 ;; RENAMER is a procedure that takes a symbol and returns its new
3060 ;; name. The default is not perform any renaming.
3062 ;; Signal "no code for module" error if module name is not resolvable
3063 ;; or its public interface is not available. Signal "no binding"
3064 ;; error if selected binding does not exist in the used module.
3066 (define* (resolve-interface name #:key
3071 (symbol-prefix-proc prefix)
3074 (let* ((module (resolve-module name #t version #:ensure #f))
3075 (public-i (and module (module-public-interface module))))
3077 (error "no code for module" name))
3078 (if (and (not select) (null? hide) (eq? renamer identity))
3080 (let ((selection (or select (module-map (lambda (sym var) sym)
3082 (custom-i (make-module 31)))
3083 (set-module-kind! custom-i 'custom-interface)
3084 (set-module-name! custom-i name)
3085 ;; XXX - should use a lazy binder so that changes to the
3086 ;; used module are picked up automatically.
3087 (for-each (lambda (bspec)
3088 (let* ((direct? (symbol? bspec))
3089 (orig (if direct? bspec (car bspec)))
3090 (seen (if direct? bspec (cdr bspec)))
3091 (var (or (module-local-variable public-i orig)
3092 (module-local-variable module orig)
3094 ;; fixme: format manually for now
3096 #f "no binding `~A' in module ~A"
3098 (if (memq orig hide)
3099 (set! hide (delq! orig hide))
3100 (module-add! custom-i
3104 ;; Check that we are not hiding bindings which don't exist
3105 (for-each (lambda (binding)
3106 (if (not (module-local-variable public-i binding))
3109 #f "no binding `~A' to hide in module ~A"
3114 (define (symbol-prefix-proc prefix)
3116 (symbol-append prefix symbol)))
3118 ;; This function is called from "modules.c". If you change it, be
3119 ;; sure to update "modules.c" as well.
3121 (define* (define-module* name
3122 #:key filename pure version (duplicates '())
3123 (imports '()) (exports '()) (replacements '())
3124 (re-exports '()) (autoloads '()) transformer)
3125 (define (list-of pred l)
3127 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
3128 (define (valid-export? x)
3129 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
3130 (define (valid-autoload? x)
3131 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
3133 (define (resolve-imports imports)
3134 (define (resolve-import import-spec)
3135 (if (list? import-spec)
3136 (apply resolve-interface import-spec)
3137 (error "unexpected use-module specification" import-spec)))
3138 (let lp ((imports imports) (out '()))
3140 ((null? imports) (reverse! out))
3143 (cons (resolve-import (car imports)) out)))
3144 (else (error "unexpected tail of imports list" imports)))))
3146 ;; We could add a #:no-check arg, set by the define-module macro, if
3147 ;; these checks are taking too much time.
3149 (let ((module (resolve-module name #f)))
3150 (beautify-user-module! module)
3152 (set-module-filename! module filename))
3154 (purify-module! module))
3157 (if (not (list-of integer? version))
3158 (error "expected list of integers for version"))
3159 (set-module-version! module version)
3160 (set-module-version! (module-public-interface module) version)))
3161 (let ((imports (resolve-imports imports)))
3162 (call-with-deferred-observers
3165 (module-use-interfaces! module imports))
3166 (if (list-of valid-export? exports)
3168 (module-export! module exports))
3169 (error "expected exports to be a list of symbols or symbol pairs"))
3170 (if (list-of valid-export? replacements)
3171 (if (pair? replacements)
3172 (module-replace! module replacements))
3173 (error "expected replacements to be a list of symbols or symbol pairs"))
3174 (if (list-of valid-export? re-exports)
3175 (if (pair? re-exports)
3176 (module-re-export! module re-exports))
3177 (error "expected re-exports to be a list of symbols or symbol pairs"))
3179 (if (not (null? autoloads))
3180 (apply module-autoload! module autoloads))
3181 ;; Wait until modules have been loaded to resolve duplicates
3183 (if (pair? duplicates)
3184 (let ((handlers (lookup-duplicates-handlers duplicates)))
3185 (set-module-duplicates-handlers! module handlers))))))
3188 (if (and (pair? transformer) (list-of symbol? transformer))
3189 (let ((iface (resolve-interface transformer))
3190 (sym (car (last-pair transformer))))
3191 (set-module-transformer! module (module-ref iface sym)))
3192 (error "expected transformer to be a module name" transformer)))
3194 (run-hook module-defined-hook module)
3197 ;; `module-defined-hook' is a hook that is run whenever a new module
3198 ;; is defined. Its members are called with one argument, the new
3200 (define module-defined-hook (make-hook 1))
3207 (define (make-autoload-interface module name bindings)
3208 (let ((b (lambda (a sym definep)
3210 (and (memq sym bindings)
3211 (let ((i (module-public-interface (resolve-module name))))
3213 (error "missing interface for module" name))
3214 (let ((autoload (memq a (module-uses module))))
3215 ;; Replace autoload-interface with actual interface if
3216 ;; that has not happened yet.
3217 (if (pair? autoload)
3218 (set-car! autoload i)))
3219 (module-local-variable i sym)))
3220 #:warning "Failed to autoload ~a in ~a:\n" sym name))))
3221 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
3222 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
3223 (make-hash-table 0) #f #f #f)))
3225 (define (module-autoload! module . args)
3226 "Have @var{module} automatically load the module named @var{name} when one
3227 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
3228 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
3229 module '(ice-9 q) '(make-q q-length))}."
3230 (let loop ((args args))
3234 (error "invalid name+binding autoload list" args))
3236 (let ((name (car args))
3237 (bindings (cadr args)))
3238 (module-use! module (make-autoload-interface module
3240 (loop (cddr args)))))))
3245 ;;; {Autoloading modules}
3248 ;;; XXX FIXME autoloads-in-progress and autoloads-done
3249 ;;; are not handled in a thread-safe way.
3251 (define autoloads-in-progress '())
3253 ;; This function is called from scm_load_scheme_module in
3254 ;; "deprecated.c". Please do not change its interface.
3256 (define* (try-module-autoload module-name #:optional version)
3257 "Try to load a module of the given name. If it is not found, return
3258 #f. Otherwise return #t. May raise an exception if a file is found,
3259 but it fails to load."
3260 (let* ((reverse-name (reverse module-name))
3261 (name (symbol->string (car reverse-name)))
3262 (dir-hint-module-name (reverse (cdr reverse-name)))
3263 (dir-hint (apply string-append
3265 (string-append (symbol->string elt)
3266 file-name-separator-string))
3267 dir-hint-module-name))))
3268 (resolve-module dir-hint-module-name #f)
3269 (and (not (autoload-done-or-in-progress? dir-hint name))
3272 (lambda () (autoload-in-progress! dir-hint name))
3274 (with-fluids ((current-reader #f))
3275 (save-module-excursion
3277 (define (call/ec proc)
3278 (let ((tag (make-prompt-tag)))
3282 (proc (lambda () (abort-to-prompt tag))))
3283 (lambda (k) (values)))))
3284 ;; The initial environment when loading a module is a fresh
3286 (set-current-module (make-fresh-user-module))
3287 ;; Here we could allow some other search strategy (other than
3288 ;; primitive-load-path), for example using versions encoded
3289 ;; into the file system -- but then we would have to figure
3290 ;; out how to locate the compiled file, do auto-compilation,
3291 ;; etc. Punt for now, and don't use versions when locating
3295 (primitive-load-path (in-vicinity dir-hint name)
3297 (set! didit #t)))))))
3298 (lambda () (set-autoloaded! dir-hint name didit)))
3303 ;;; {Dynamic linking of modules}
3306 (define autoloads-done '((guile . guile)))
3308 (define (autoload-done-or-in-progress? p m)
3309 (let ((n (cons p m)))
3310 (->bool (or (member n autoloads-done)
3311 (member n autoloads-in-progress)))))
3313 (define (autoload-done! p m)
3314 (let ((n (cons p m)))
3315 (set! autoloads-in-progress
3316 (delete! n autoloads-in-progress))
3317 (or (member n autoloads-done)
3318 (set! autoloads-done (cons n autoloads-done)))))
3320 (define (autoload-in-progress! p m)
3321 (let ((n (cons p m)))
3322 (set! autoloads-done
3323 (delete! n autoloads-done))
3324 (set! autoloads-in-progress (cons n autoloads-in-progress))))
3326 (define (set-autoloaded! p m done?)
3328 (autoload-done! p m)
3329 (let ((n (cons p m)))
3330 (set! autoloads-done (delete! n autoloads-done))
3331 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
3335 ;;; {Run-time options}
3338 (define-syntax define-option-interface
3340 ((_ (interface (options enable disable) (option-set!)))
3347 (begin (interface arg) (interface))
3350 (apply (lambda (name value documentation)
3352 (let ((len (string-length (symbol->string name))))
3360 (display documentation)
3364 (define (enable . flags)
3365 (interface (append flags (interface)))
3367 (define (disable . flags)
3368 (let ((options (interface)))
3369 (for-each (lambda (flag) (set! options (delq! flag options)))
3373 (define-syntax-rule (option-set! opt val)
3374 (eval-when (expand load eval)
3375 (options (append (options) (list 'opt val)))))))))
3377 (define-option-interface
3378 (debug-options-interface
3379 (debug-options debug-enable debug-disable)
3382 (define-option-interface
3383 (read-options-interface
3384 (read-options read-enable read-disable)
3387 (define-option-interface
3388 (print-options-interface
3389 (print-options print-enable print-disable)
3394 ;;; {The Unspecified Value}
3396 ;;; Currently Guile represents unspecified values via one particular value,
3397 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
3398 ;;; future if we could replace this with a return of 0 values, though.
3401 (define-syntax *unspecified*
3402 (identifier-syntax (if #f #f)))
3404 (define (unspecified? v) (eq? v *unspecified*))
3412 (define *repl-stack* (make-fluid '()))
3414 ;; Programs can call `batch-mode?' to see if they are running as part of a
3415 ;; script or if they are running interactively. REPL implementations ensure that
3416 ;; `batch-mode?' returns #f during their extent.
3418 (define (batch-mode?)
3419 (null? (fluid-ref *repl-stack*)))
3421 ;; Programs can re-enter batch mode, for example after a fork, by calling
3422 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3423 ;; to abort to the outermost prompt, and call a thunk there.
3425 (define (ensure-batch-mode!)
3426 (set! batch-mode? (lambda () #t)))
3428 (define (quit . args)
3429 (apply throw 'quit args))
3433 (define (gc-run-time)
3434 (cdr (assq 'gc-time-taken (gc-stats))))
3436 (define abort-hook (make-hook))
3437 (define before-error-hook (make-hook))
3438 (define after-error-hook (make-hook))
3439 (define before-backtrace-hook (make-hook))
3440 (define after-backtrace-hook (make-hook))
3442 (define before-read-hook (make-hook))
3443 (define after-read-hook (make-hook))
3444 (define before-eval-hook (make-hook 1))
3445 (define after-eval-hook (make-hook 1))
3446 (define before-print-hook (make-hook 1))
3447 (define after-print-hook (make-hook 1))
3449 ;;; This hook is run at the very end of an interactive session.
3451 (define exit-hook (make-hook))
3453 ;;; The default repl-reader function. We may override this if we've
3454 ;;; the readline library.
3456 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3457 (if (not (char-ready?))
3459 (display (if (string? prompt) prompt (prompt)))
3460 ;; An interesting situation. The printer resets the column to
3461 ;; 0 by printing a newline, but we then advance it by printing
3462 ;; the prompt. However the port-column of the output port
3463 ;; does not typically correspond with the actual column on the
3464 ;; screen, because the input is echoed back! Since the
3465 ;; input is line-buffered and thus ends with a newline, the
3466 ;; output will really start on column zero. So, here we zero
3467 ;; it out. See bug 9664.
3469 ;; Note that for similar reasons, the output-line will not
3470 ;; reflect the actual line on the screen. But given the
3471 ;; possibility of multiline input, the fix is not as
3472 ;; straightforward, so we don't bother.
3474 ;; Also note that the readline implementation papers over
3475 ;; these concerns, because it's readline itself printing the
3476 ;; prompt, and not Guile.
3477 (set-port-column! (current-output-port) 0)))
3479 (run-hook before-read-hook)
3480 ((or reader read) (current-input-port))))
3487 ;;; with `continue' and `break'.
3490 ;; The inliner will remove the prompts at compile-time if it finds that
3491 ;; `continue' or `break' are not used.
3493 (define-syntax while
3496 ((while cond body ...)
3497 #`(let ((break-tag (make-prompt-tag "break"))
3498 (continue-tag (make-prompt-tag "continue")))
3502 (define-syntax #,(datum->syntax #'while 'break)
3506 #'(abort-to-prompt break-tag arg (... ...)))
3509 (apply abort-to-prompt break-tag args))))))
3514 (define-syntax #,(datum->syntax #'while 'continue)
3518 #'(abort-to-prompt continue-tag))
3520 (syntax-violation 'continue "too many arguments" x))
3523 (abort-to-prompt continue-tag))))))
3524 (do () ((not cond) #f) body ...))
3525 (lambda (k) (lp)))))
3529 (apply values args)))))))))
3534 ;;; {Module System Macros}
3537 ;; Return a list of expressions that evaluate to the appropriate
3538 ;; arguments for resolve-interface according to SPEC.
3541 (if (memq 'prefix (read-options))
3542 (error "boot-9 must be compiled with #:kw, not :kw")))
3544 (define (keyword-like-symbol->keyword sym)
3545 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3547 (define-syntax define-module
3549 (define (keyword-like? stx)
3550 (let ((dat (syntax->datum stx)))
3552 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3553 (define (->keyword sym)
3554 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3556 (define (parse-iface args)
3557 (let loop ((in args) (out '()))
3560 ;; The user wanted #:foo, but wrote :foo. Fix it.
3561 ((sym . in) (keyword-like? #'sym)
3562 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3563 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3564 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3565 ((#:renamer renamer . in)
3566 (loop #'in (cons* #',renamer #:renamer out)))
3568 (loop #'in (cons* #'val #'kw out))))))
3570 (define (parse args imp exp rex rep aut)
3571 ;; Just quote everything except #:use-module and #:use-syntax. We
3572 ;; need to know about all arguments regardless since we want to turn
3573 ;; symbols that look like keywords into real keywords, and the
3574 ;; keyword args in a define-module form are not regular
3575 ;; (i.e. no-backtrace doesn't take a value).
3576 (syntax-case args ()
3578 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3579 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3580 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3581 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3582 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3583 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3584 ;; The user wanted #:foo, but wrote :foo. Fix it.
3585 ((sym . args) (keyword-like? #'sym)
3586 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3587 imp exp rex rep aut))
3588 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3589 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3590 ((#:no-backtrace . args)
3592 (parse #'args imp exp rex rep aut))
3594 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3596 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3597 ((#:version (v ...) . args)
3598 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3599 ((#:duplicates (d ...) . args)
3600 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3601 ((#:filename f . args)
3602 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3603 ((#:use-module (name name* ...) . args)
3604 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3605 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3606 ((#:use-syntax (name name* ...) . args)
3607 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3608 #`(#:transformer '(name name* ...)
3609 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3610 ((#:use-module ((name name* ...) arg ...) . args)
3611 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3613 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3615 ((#:export (ex ...) . args)
3616 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3617 ((#:export-syntax (ex ...) . args)
3618 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3619 ((#:re-export (re ...) . args)
3620 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3621 ((#:re-export-syntax (re ...) . args)
3622 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3623 ((#:replace (r ...) . args)
3624 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3625 ((#:replace-syntax (r ...) . args)
3626 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3627 ((#:autoload name bindings . args)
3628 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3630 (syntax-violation 'define-module "unknown keyword or bad argument"
3634 ((_ (name name* ...) arg ...)
3635 (and-map symbol? (syntax->datum #'(name name* ...)))
3636 (with-syntax (((quoted-arg ...)
3637 (parse #'(arg ...) '() '() '() '() '()))
3638 ;; Ideally the filename is either a string or #f;
3639 ;; this hack is to work around a case in which
3640 ;; port-filename returns a symbol (`socket') for
3642 (filename (let ((f (assq-ref (or (syntax-source x) '())
3644 (and (string? f) f))))
3645 #'(eval-when (expand load eval)
3646 (let ((m (define-module* '(name name* ...)
3647 #:filename filename quoted-arg ...)))
3648 (set-current-module m)
3651 ;; The guts of the use-modules macro. Add the interfaces of the named
3652 ;; modules to the use-list of the current module, in order.
3654 ;; This function is called by "modules.c". If you change it, be sure
3655 ;; to change scm_c_use_module as well.
3657 (define (process-use-modules module-interface-args)
3658 (let ((interfaces (map (lambda (mif-args)
3659 (or (apply resolve-interface mif-args)
3660 (error "no such module" mif-args)))
3661 module-interface-args)))
3662 (call-with-deferred-observers
3664 (module-use-interfaces! (current-module) interfaces)))))
3666 (define-syntax use-modules
3668 (define (keyword-like? stx)
3669 (let ((dat (syntax->datum stx)))
3671 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3672 (define (->keyword sym)
3673 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3675 (define (quotify-iface args)
3676 (let loop ((in args) (out '()))
3679 ;; The user wanted #:foo, but wrote :foo. Fix it.
3680 ((sym . in) (keyword-like? #'sym)
3681 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3682 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3683 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3684 ((#:renamer renamer . in)
3685 (loop #'in (cons* #'renamer #:renamer out)))
3687 (loop #'in (cons* #''val #'kw out))))))
3689 (define (quotify specs)
3690 (let lp ((in specs) (out '()))
3693 (((name name* ...) . in)
3694 (and-map symbol? (syntax->datum #'(name name* ...)))
3695 (lp #'in (cons #''((name name* ...)) out)))
3696 ((((name name* ...) arg ...) . in)
3697 (and-map symbol? (syntax->datum #'(name name* ...)))
3698 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3699 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3704 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3705 #'(eval-when (expand load eval)
3706 (process-use-modules (list quoted-args ...))
3709 (include-from-path "ice-9/r6rs-libraries")
3711 (define-syntax-rule (define-private foo bar)
3714 (define-syntax define-public
3716 ((_ (name . args) . body)
3718 (define (name . args) . body)
3725 (define-syntax-rule (defmacro-public name args body ...)
3727 (defmacro name args body ...)
3728 (export-syntax name)))
3730 ;; And now for the most important macro.
3731 (define-syntax-rule (λ formals body ...)
3732 (lambda formals body ...))
3735 ;; Export a local variable
3737 ;; This function is called from "modules.c". If you change it, be
3738 ;; sure to update "modules.c" as well.
3740 (define (module-export! m names)
3741 (let ((public-i (module-public-interface m)))
3742 (for-each (lambda (name)
3743 (let* ((internal-name (if (pair? name) (car name) name))
3744 (external-name (if (pair? name) (cdr name) name))
3745 (var (module-ensure-local-variable! m internal-name)))
3746 (module-add! public-i external-name var)))
3749 (define (module-replace! m names)
3750 (let ((public-i (module-public-interface m)))
3751 (for-each (lambda (name)
3752 (let* ((internal-name (if (pair? name) (car name) name))
3753 (external-name (if (pair? name) (cdr name) name))
3754 (var (module-ensure-local-variable! m internal-name)))
3755 ;; FIXME: use a bit on variables instead of object
3757 (set-object-property! var 'replace #t)
3758 (module-add! public-i external-name var)))
3761 ;; Export all local variables from a module
3763 (define (module-export-all! mod)
3764 (define (fresh-interface!)
3765 (let ((iface (make-module)))
3766 (set-module-name! iface (module-name mod))
3767 (set-module-version! iface (module-version mod))
3768 (set-module-kind! iface 'interface)
3769 (set-module-public-interface! mod iface)
3771 (let ((iface (or (module-public-interface mod)
3772 (fresh-interface!))))
3773 (set-module-obarray! iface (module-obarray mod))))
3775 ;; Re-export a imported variable
3777 (define (module-re-export! m names)
3778 (let ((public-i (module-public-interface m)))
3779 (for-each (lambda (name)
3780 (let* ((internal-name (if (pair? name) (car name) name))
3781 (external-name (if (pair? name) (cdr name) name))
3782 (var (module-variable m internal-name)))
3784 (error "Undefined variable:" internal-name))
3785 ((eq? var (module-local-variable m internal-name))
3786 (error "re-exporting local variable:" internal-name))
3788 (module-add! public-i external-name var)))))
3791 (define-syntax-rule (export name ...)
3792 (eval-when (expand load eval)
3793 (call-with-deferred-observers
3795 (module-export! (current-module) '(name ...))))))
3797 (define-syntax-rule (re-export name ...)
3798 (eval-when (expand load eval)
3799 (call-with-deferred-observers
3801 (module-re-export! (current-module) '(name ...))))))
3803 (define-syntax-rule (export! name ...)
3804 (eval-when (expand load eval)
3805 (call-with-deferred-observers
3807 (module-replace! (current-module) '(name ...))))))
3809 (define-syntax-rule (export-syntax name ...)
3812 (define-syntax-rule (re-export-syntax name ...)
3813 (re-export name ...))
3820 (define* (make-mutable-parameter init #:optional (converter identity))
3821 (let ((fluid (make-fluid (converter init))))
3823 (() (fluid-ref fluid))
3824 ((val) (fluid-set! fluid (converter val))))))
3829 ;;; {Handling of duplicate imported bindings}
3832 ;; Duplicate handlers take the following arguments:
3834 ;; module importing module
3835 ;; name conflicting name
3836 ;; int1 old interface where name occurs
3837 ;; val1 value of binding in old interface
3838 ;; int2 new interface where name occurs
3839 ;; val2 value of binding in new interface
3840 ;; var previous resolution or #f
3841 ;; val value of previous resolution
3843 ;; A duplicate handler can take three alternative actions:
3845 ;; 1. return #f => leave responsibility to next handler
3846 ;; 2. exit with an error
3847 ;; 3. return a variable resolving the conflict
3850 (define duplicate-handlers
3851 (let ((m (make-module 7)))
3853 (define (check module name int1 val1 int2 val2 var val)
3854 (scm-error 'misc-error
3856 "~A: `~A' imported from both ~A and ~A"
3857 (list (module-name module)
3863 (define (warn module name int1 val1 int2 val2 var val)
3864 (format (current-warning-port)
3865 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3866 (module-name module)
3872 (define (replace module name int1 val1 int2 val2 var val)
3873 (let ((old (or (and var (object-property var 'replace) var)
3874 (module-variable int1 name)))
3875 (new (module-variable int2 name)))
3876 (if (object-property old 'replace)
3877 (and (or (eq? old new)
3878 (not (object-property new 'replace)))
3880 (and (object-property new 'replace)
3883 (define (warn-override-core module name int1 val1 int2 val2 var val)
3884 (and (eq? int1 the-scm-module)
3886 (format (current-warning-port)
3887 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3888 (module-name module)
3891 (module-local-variable int2 name))))
3893 (define (first module name int1 val1 int2 val2 var val)
3894 (or var (module-local-variable int1 name)))
3896 (define (last module name int1 val1 int2 val2 var val)
3897 (module-local-variable int2 name))
3899 (define (noop module name int1 val1 int2 val2 var val)
3902 (set-module-name! m 'duplicate-handlers)
3903 (set-module-kind! m 'interface)
3904 (module-define! m 'check check)
3905 (module-define! m 'warn warn)
3906 (module-define! m 'replace replace)
3907 (module-define! m 'warn-override-core warn-override-core)
3908 (module-define! m 'first first)
3909 (module-define! m 'last last)
3910 (module-define! m 'merge-generics noop)
3911 (module-define! m 'merge-accessors noop)
3914 (define (lookup-duplicates-handlers handler-names)
3916 (map (lambda (handler-name)
3917 (or (module-symbol-local-binding
3918 duplicate-handlers handler-name #f)
3919 (error "invalid duplicate handler name:"
3921 (if (list? handler-names)
3923 (list handler-names)))))
3925 (define default-duplicate-binding-procedures
3926 (make-mutable-parameter #f))
3928 (define default-duplicate-binding-handler
3929 (make-mutable-parameter '(replace warn-override-core warn last)
3930 (lambda (handler-names)
3931 (default-duplicate-binding-procedures
3932 (lookup-duplicates-handlers handler-names))
3939 ;;; Load is tricky when combined with relative file names, compilation,
3940 ;;; and the file system. If a file name is relative, what is it
3941 ;;; relative to? The name of the source file at the time it was
3942 ;;; compiled? The name of the compiled file? What if both or either
3943 ;;; were installed? And how do you get that information? Tricky, I
3946 ;;; To get around all of this, we're going to do something nasty, and
3947 ;;; turn `load' into a macro. That way it can know the name of the
3948 ;;; source file with respect to which it was invoked, so it can resolve
3949 ;;; relative file names with respect to the original source file.
3951 ;;; There is an exception, and that is that if the source file was in
3952 ;;; the load path when it was compiled, instead of looking up against
3953 ;;; the absolute source location, we load-from-path against the relative
3954 ;;; source location.
3957 (define %auto-compilation-options
3958 ;; Default `compile-file' option when auto-compiling.
3959 '(#:warnings (unbound-variable arity-mismatch format
3960 duplicate-case-datum bad-case-datum)))
3962 (define* (load-in-vicinity dir file-name #:optional reader)
3963 "Load source file FILE-NAME in vicinity of directory DIR. Use a
3964 pre-compiled version of FILE-NAME when available, and auto-compile one
3965 when none is available, reading FILE-NAME with READER."
3967 ;; The auto-compilation code will residualize a .go file in the cache
3968 ;; dir: by default, $HOME/.cache/guile/2.0/ccache/PATH.go. This
3969 ;; function determines the PATH to use as a key into the compilation
3971 (define (canonical->suffix canon)
3973 ((and (not (string-null? canon))
3974 (file-name-separator? (string-ref canon 0)))
3976 ((and (eq? (system-file-name-convention) 'windows)
3977 (absolute-file-name? canon))
3978 ;; An absolute file name that doesn't start with a separator
3979 ;; starts with a drive component. Transform the drive component
3980 ;; to a file name element: c:\foo -> \c\foo.
3981 (string-append file-name-separator-string
3982 (substring canon 0 1)
3983 (substring canon 2)))
3986 (define compiled-extension
3987 ;; File name extension of compiled files.
3988 (cond ((or (null? %load-compiled-extensions)
3989 (string-null? (car %load-compiled-extensions)))
3990 (warn "invalid %load-compiled-extensions"
3991 %load-compiled-extensions)
3993 (else (car %load-compiled-extensions))))
3995 (define (more-recent? stat1 stat2)
3996 ;; Return #t when STAT1 has an mtime greater than that of STAT2.
3997 (or (> (stat:mtime stat1) (stat:mtime stat2))
3998 (and (= (stat:mtime stat1) (stat:mtime stat2))
3999 (>= (stat:mtimensec stat1)
4000 (stat:mtimensec stat2)))))
4002 (define (fallback-file-name canon-file-name)
4003 ;; Return the in-cache compiled file name for source file
4006 ;; FIXME: would probably be better just to append
4007 ;; SHA1(canon-file-name) to the %compile-fallback-path, to avoid
4008 ;; deep directory stats.
4009 (and %compile-fallback-path
4010 (string-append %compile-fallback-path
4011 (canonical->suffix canon-file-name)
4012 compiled-extension)))
4014 (define (compile file)
4015 ;; Compile source FILE, lazily loading the compiler.
4016 ((module-ref (resolve-interface '(system base compile))
4019 #:opts %auto-compilation-options
4020 #:env (current-module)))
4022 ;; Returns the .go file corresponding to `name'. Does not search load
4023 ;; paths, only the fallback path. If the .go file is missing or out
4024 ;; of date, and auto-compilation is enabled, will try
4025 ;; auto-compilation, just as primitive-load-path does internally.
4026 ;; primitive-load is unaffected. Returns #f if auto-compilation
4027 ;; failed or was disabled.
4029 ;; NB: Unless we need to compile the file, this function should not
4030 ;; cause (system base compile) to be loaded up. For that reason
4031 ;; compiled-file-name partially duplicates functionality from (system
4034 (define (fresh-compiled-file-name name scmstat go-file-name)
4035 ;; Return GO-FILE-NAME after making sure that it contains a freshly
4036 ;; compiled version of source file NAME with stat SCMSTAT; return #f
4039 (let ((gostat (and (not %fresh-auto-compile)
4040 (stat go-file-name #f))))
4041 (if (and gostat (more-recent? gostat scmstat))
4045 (format (current-warning-port)
4046 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
4049 (%load-should-auto-compile
4050 (%warn-auto-compilation-enabled)
4051 (format (current-warning-port) ";;; compiling ~a\n" name)
4052 (let ((cfn (compile name)))
4053 (format (current-warning-port) ";;; compiled ~a\n" cfn)
4056 #:warning "WARNING: compilation of ~a failed:\n" name))
4058 (define (sans-extension file)
4059 (let ((dot (string-rindex file #\.)))
4061 (substring file 0 dot)
4064 (define (load-absolute abs-file-name)
4065 ;; Load from ABS-FILE-NAME, using a compiled file or auto-compiling
4069 (stat abs-file-name)
4070 #:warning "Stat of ~a failed:\n" abs-file-name))
4072 (define (pre-compiled)
4073 (and=> (search-path %load-compiled-path (sans-extension file-name)
4074 %load-compiled-extensions #t)
4075 (lambda (go-file-name)
4076 (let ((gostat (stat go-file-name #f)))
4077 (and gostat (more-recent? gostat scmstat)
4081 (and=> (false-if-exception (canonicalize-path abs-file-name))
4083 (and=> (fallback-file-name canon)
4084 (lambda (go-file-name)
4085 (fresh-compiled-file-name abs-file-name
4089 (let ((compiled (and scmstat (or (pre-compiled) (fallback)))))
4093 (%load-hook abs-file-name))
4094 (load-compiled compiled))
4095 (start-stack 'load-stack
4096 (primitive-load abs-file-name)))))
4098 (save-module-excursion
4100 (with-fluids ((current-reader reader)
4101 (%file-port-name-canonicalization 'relative))
4103 ((absolute-file-name? file-name)
4104 (load-absolute file-name))
4105 ((absolute-file-name? dir)
4106 (load-absolute (in-vicinity dir file-name)))
4108 (load-from-path (in-vicinity dir file-name))))))))
4111 (make-variable-transformer
4113 (let* ((src (syntax-source x))
4114 (file (and src (assq-ref src 'filename)))
4115 (dir (and (string? file) (dirname file))))
4118 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
4122 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
4126 ;;; {`cond-expand' for SRFI-0 support.}
4128 ;;; This syntactic form expands into different commands or
4129 ;;; definitions, depending on the features provided by the Scheme
4135 ;;; --> (cond-expand <cond-expand-clause>+)
4136 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
4137 ;;; <cond-expand-clause>
4138 ;;; --> (<feature-requirement> <command-or-definition>*)
4139 ;;; <feature-requirement>
4140 ;;; --> <feature-identifier>
4141 ;;; | (and <feature-requirement>*)
4142 ;;; | (or <feature-requirement>*)
4143 ;;; | (not <feature-requirement>)
4144 ;;; <feature-identifier>
4145 ;;; --> <a symbol which is the name or alias of a SRFI>
4147 ;;; Additionally, this implementation provides the
4148 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
4149 ;;; determine the implementation type and the supported standard.
4151 ;;; Remember to update the features list when adding more SRFIs.
4154 (define %cond-expand-features
4155 ;; This should contain only features that are present in core Guile,
4156 ;; before loading any modules. Modular features are handled by
4157 ;; placing 'cond-expand-provide' in the relevant module.
4162 srfi-0 ;; cond-expand itself
4163 srfi-4 ;; homogeneous numeric vectors
4164 srfi-6 ;; string ports
4165 srfi-13 ;; string library
4166 srfi-14 ;; character sets
4167 srfi-16 ;; case-lambda
4168 srfi-23 ;; `error` procedure
4169 srfi-30 ;; nested multi-line comments
4170 srfi-39 ;; parameterize
4171 srfi-46 ;; basic syntax-rules extensions
4172 srfi-55 ;; require-extension
4173 srfi-61 ;; general cond clause
4174 srfi-62 ;; s-expression comments
4175 srfi-87 ;; => in case clauses
4176 srfi-105 ;; curly infix expressions
4179 ;; This table maps module public interfaces to the list of features.
4181 (define %cond-expand-table (make-hash-table 31))
4183 ;; Add one or more features to the `cond-expand' feature list of the
4186 (define (cond-expand-provide module features)
4187 (let ((mod (module-public-interface module)))
4189 (hashq-set! %cond-expand-table mod
4190 (append (hashq-ref %cond-expand-table mod '())
4193 (define-syntax cond-expand
4195 (define (module-has-feature? mod sym)
4196 (or-map (lambda (mod)
4197 (memq sym (hashq-ref %cond-expand-table mod '())))
4200 (define (condition-matches? condition)
4201 (syntax-case condition (and or not)
4203 (and-map condition-matches? #'(c ...)))
4205 (or-map condition-matches? #'(c ...)))
4207 (if (condition-matches? #'c) #f #t))
4210 (let ((sym (syntax->datum #'c)))
4211 (if (memq sym %cond-expand-features)
4213 (module-has-feature? (current-module) sym))))))
4215 (define (match clauses alternate)
4216 (syntax-case clauses ()
4217 (((condition form ...) . rest)
4218 (if (condition-matches? #'condition)
4220 (match #'rest alternate)))
4223 (syntax-case x (else)
4224 ((_ clause ... (else form ...))
4225 (match #'(clause ...)
4227 #'(begin form ...))))
4229 (match #'(clause ...)
4231 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
4233 ;; This procedure gets called from the startup code with a list of
4234 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
4236 (define (use-srfis srfis)
4237 (process-use-modules
4239 (list (list 'srfi (string->symbol
4240 (string-append "srfi-" (number->string num))))))
4245 ;;; srfi-55: require-extension
4248 (define-syntax require-extension
4250 (syntax-case x (srfi)
4252 (and-map integer? (syntax->datum #'(n ...)))
4256 (datum->syntax x (symbol-append 'srfi- n)))
4258 (map number->string (syntax->datum #'(n ...)))))))
4259 #'(use-modules (srfi srfi-n) ...)))
4261 (identifier? #'type)
4262 (syntax-violation 'require-extension "Not a recognized extension type"
4266 ;;; Defining transparently inlinable procedures
4269 (define-syntax define-inlinable
4270 ;; Define a macro and a procedure such that direct calls are inlined, via
4271 ;; the macro expansion, whereas references in non-call contexts refer to
4272 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
4274 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
4276 (define prefix (string->symbol "% "))
4277 (define (make-procedure-name name)
4279 (symbol-append prefix (syntax->datum name)
4283 ((_ (name formals ...) body ...)
4284 (identifier? #'name)
4285 (with-syntax ((proc-name (make-procedure-name #'name))
4286 ((args ...) (generate-temporaries #'(formals ...))))
4288 (define (proc-name formals ...)
4289 (syntax-parameterize ((name (identifier-syntax proc-name)))
4291 (define-syntax-parameter name
4295 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
4296 (lambda (formals ...)
4300 (syntax-violation 'name "Wrong number of arguments" x))
4303 #'proc-name))))))))))
4307 (define using-readline?
4308 (let ((using-readline? (make-fluid)))
4309 (make-procedure-with-setter
4310 (lambda () (fluid-ref using-readline?))
4311 (lambda (v) (fluid-set! using-readline? v)))))
4315 ;;; {Deprecated stuff}
4319 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
4323 ;;; SRFI-4 in the default environment. FIXME: we should figure out how
4324 ;;; to deprecate this.
4328 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
4332 ;;; A few identifiers that need to be defined in this file are really
4333 ;;; internal implementation details. We shove them off into internal
4334 ;;; modules, removing them from the (guile) module.
4337 (define-module (system syntax))
4340 (define (steal-bindings! from to ids)
4343 (let ((v (module-local-variable from sym)))
4344 (module-remove! from sym)
4345 (module-add! to sym v)))
4347 (module-export! to ids))
4349 (steal-bindings! the-root-module (resolve-module '(system syntax))
4350 '(syntax-local-binding
4352 syntax-locally-bound-identifiers
4353 syntax-session-id)))
4358 ;;; Place the user in the guile-user module.
4361 ;; Set filename to #f to prevent reload.
4362 (define-module (guile-user)
4363 #:autoload (system base compile) (compile compile-file)
4366 ;; Remain in the `(guile)' module at compilation-time so that the
4367 ;; `-Wunused-toplevel' warning works as expected.
4368 (eval-when (compile) (set-current-module the-root-module))
4370 ;;; boot-9.scm ends here