1 ;;; -*- mode: scheme; coding: utf-8; -*-
3 ;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 ;;;; 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
5 ;;;; Free Software Foundation, Inc.
7 ;;;; This library is free software; you can redistribute it and/or
8 ;;;; modify it under the terms of the GNU Lesser General Public
9 ;;;; License as published by the Free Software Foundation; either
10 ;;;; version 3 of the License, or (at your option) any later version.
12 ;;;; This library is distributed in the hope that it will be useful,
13 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 ;;;; Lesser General Public License for more details.
17 ;;;; You should have received a copy of the GNU Lesser General Public
18 ;;;; License along with this library; if not, write to the Free Software
19 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 ;;; This file is the first thing loaded into Guile. It adds many mundane
27 ;;; definitions and a few that are interesting.
29 ;;; The module system (hence the hierarchical namespace) are defined in this
37 ;; Before compiling, make sure any symbols are resolved in the (guile)
38 ;; module, the primary location of those symbols, rather than in
39 ;; (guile-user), the default module that we compile in.
42 (set-current-module (resolve-module '(guile))))
49 ;; Define delimited continuation operators, and implement catch and throw in
52 (define make-prompt-tag
53 (lambda* (#:optional (stem "prompt"))
54 ;; The only property that prompt tags need have is uniqueness in the
55 ;; sense of eq?. A one-element list will serve nicely.
58 (define default-prompt-tag
59 ;; Redefined later to be a parameter.
60 (let ((%default-prompt-tag (make-prompt-tag)))
62 %default-prompt-tag)))
64 (define (call-with-prompt tag thunk handler)
65 ((@@ primitive call-with-prompt) tag thunk handler))
66 (define (abort-to-prompt tag . args)
67 (abort-to-prompt* tag args))
69 (define (with-fluid* fluid val thunk)
70 "Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
71 @var{thunk} must be a procedure of no arguments."
72 ((@@ primitive push-fluid) fluid val)
73 (call-with-values thunk
75 ((@@ primitive pop-fluid))
76 (apply values vals))))
78 ;; Define catch and with-throw-handler, using some common helper routines and a
79 ;; shared fluid. Hide the helpers in a lexical contour.
81 (define with-throw-handler #f)
83 (define (default-exception-handler k . args)
87 ((not (pair? args)) 0)
88 ((integer? (car args)) (car args))
92 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
95 (define %running-exception-handlers (make-fluid '()))
96 (define %exception-handler (make-fluid default-exception-handler))
98 (define (default-throw-handler prompt-tag catch-k)
99 (let ((prev (fluid-ref %exception-handler)))
100 (lambda (thrown-k . args)
101 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
102 (apply abort-to-prompt prompt-tag thrown-k args)
103 (apply prev thrown-k args)))))
105 (define (custom-throw-handler prompt-tag catch-k pre)
106 (let ((prev (fluid-ref %exception-handler)))
107 (lambda (thrown-k . args)
108 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
109 (let ((running (fluid-ref %running-exception-handlers)))
110 (with-fluid* %running-exception-handlers (cons pre running)
112 (if (not (memq pre running))
113 (apply pre thrown-k args))
116 (apply abort-to-prompt prompt-tag thrown-k args)
117 (apply prev thrown-k args)))))
118 (apply prev thrown-k args)))))
121 (lambda* (k thunk handler #:optional pre-unwind-handler)
122 "Invoke @var{thunk} in the dynamic context of @var{handler} for
123 exceptions matching @var{key}. If thunk throws to the symbol
124 @var{key}, then @var{handler} is invoked this way:
126 (handler key args ...)
129 @var{key} is a symbol or @code{#t}.
131 @var{thunk} takes no arguments. If @var{thunk} returns
132 normally, that is the return value of @code{catch}.
134 Handler is invoked outside the scope of its own @code{catch}.
135 If @var{handler} again throws to the same key, a new handler
136 from further up the call chain is invoked.
138 If the key is @code{#t}, then a throw to @emph{any} symbol will
139 match this call to @code{catch}.
141 If a @var{pre-unwind-handler} is given and @var{thunk} throws
142 an exception that matches @var{key}, Guile calls the
143 @var{pre-unwind-handler} before unwinding the dynamic state and
144 invoking the main @var{handler}. @var{pre-unwind-handler} should
145 be a procedure with the same signature as @var{handler}, that
146 is @code{(lambda (key . args))}. It is typically used to save
147 the stack at the point where the exception occurred, but can also
148 query other parts of the dynamic state at that point, such as
151 A @var{pre-unwind-handler} can exit either normally or non-locally.
152 If it exits normally, Guile unwinds the stack and dynamic context
153 and then calls the normal (third argument) handler. If it exits
154 non-locally, that exit determines the continuation."
155 (if (not (or (symbol? k) (eqv? k #t)))
156 (scm-error 'wrong-type-arg "catch"
157 "Wrong type argument in position ~a: ~a"
158 (list 1 k) (list k)))
159 (let ((tag (make-prompt-tag "catch")))
163 (with-fluid* %exception-handler
164 (if pre-unwind-handler
165 (custom-throw-handler tag k pre-unwind-handler)
166 (default-throw-handler tag k))
168 (lambda (cont k . args)
169 (apply handler k args))))))
171 (set! with-throw-handler
172 (lambda (k thunk pre-unwind-handler)
173 "Add @var{handler} to the dynamic context as a throw handler
174 for key @var{k}, then invoke @var{thunk}."
175 (if (not (or (symbol? k) (eqv? k #t)))
176 (scm-error 'wrong-type-arg "with-throw-handler"
177 "Wrong type argument in position ~a: ~a"
178 (list 1 k) (list k)))
179 (with-fluid* %exception-handler
180 (custom-throw-handler #f k pre-unwind-handler)
185 "Invoke the catch form matching @var{key}, passing @var{args} to the
188 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
190 If there is no handler at all, Guile prints an error and then exits."
191 (if (not (symbol? key))
192 ((fluid-ref %exception-handler) 'wrong-type-arg "throw"
193 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
194 (apply (fluid-ref %exception-handler) key args)))))
199 ;;; {Language primitives}
202 ;; These are are the procedural wrappers around the primitives of
203 ;; Guile's language: apply, call-with-current-continuation, etc.
205 ;; Usually, a call to a primitive is compiled specially. The compiler
206 ;; knows about all these kinds of expressions. But the primitives may
207 ;; be referenced not only as operators, but as values as well. These
208 ;; stub procedures are the "values" of apply, dynamic-wind, and other
214 ((@@ primitive apply) fun args))
216 (letrec ((append* (lambda (tail)
217 (let ((tail (car tail))
221 (cons tail (append* tail*)))))))
222 (apply fun (cons arg1 (append* args)))))))
223 (define (call-with-current-continuation proc)
224 ((@@ primitive call-with-current-continuation) proc))
225 (define (call-with-values producer consumer)
226 ((@@ primitive call-with-values) producer consumer))
227 (define (dynamic-wind in thunk out)
228 "All three arguments must be 0-argument procedures.
229 Guard @var{in} is called, then @var{thunk}, then
232 If, any time during the execution of @var{thunk}, the
233 continuation of the @code{dynamic_wind} expression is escaped
234 non-locally, @var{out} is called. If the continuation of
235 the dynamic-wind is re-entered, @var{in} is called. Thus
236 @var{in} and @var{out} may be called any number of
239 (define x 'normal-binding)
242 (call-with-current-continuation
248 (lambda () (set! x 'special-binding))
252 (lambda () (display x) (newline)
253 (call-with-current-continuation escape)
254 (display x) (newline)
259 (lambda () (set! x old-x)))))))
266 @result{} normal-binding
271 @result{} a-cont ;; the value of the (define a-cont...)
273 @result{} normal-binding
275 @result{} special-binding
279 (scm-error 'wrong-type-arg "dynamic-wind" "Not a thunk: ~S"
281 ((@@ primitive wind) in out)
282 (call-with-values thunk
284 ((@@ primitive unwind))
286 (apply values vals))))
290 ;;; {Low-Level Port Code}
293 ;; These are used to request the proper mode to open files in.
295 (define OPEN_READ "r")
296 (define OPEN_WRITE "w")
297 (define OPEN_BOTH "r+")
299 (define *null-device* "/dev/null")
301 ;; NOTE: Later in this file, this is redefined to support keywords
302 (define (open-input-file str)
303 "Takes a string naming an existing file and returns an input port
304 capable of delivering characters from the file. If the file
305 cannot be opened, an error is signalled."
306 (open-file str OPEN_READ))
308 ;; NOTE: Later in this file, this is redefined to support keywords
309 (define (open-output-file str)
310 "Takes a string naming an output file to be created and returns an
311 output port capable of writing characters to a new file by that
312 name. If the file cannot be opened, an error is signalled. If a
313 file with the given name already exists, the effect is unspecified."
314 (open-file str OPEN_WRITE))
316 (define (open-io-file str)
317 "Open file with name STR for both input and output."
318 (open-file str OPEN_BOTH))
322 ;;; {Simple Debugging Tools}
325 ;; peek takes any number of arguments, writes them to the
326 ;; current ouput port, and returns the last argument.
327 ;; It is handy to wrap around an expression to look at
328 ;; a value each time is evaluated, e.g.:
330 ;; (+ 10 (troublesome-fn))
331 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
334 (define (peek . stuff)
339 (car (last-pair stuff)))
343 ;; Temporary definition; replaced later.
344 (define current-warning-port current-error-port)
346 (define (warn . stuff)
347 (newline (current-warning-port))
348 (display ";;; WARNING " (current-warning-port))
349 (display stuff (current-warning-port))
350 (newline (current-warning-port))
351 (car (last-pair stuff)))
358 (define (provide sym)
359 (if (not (memq sym *features*))
360 (set! *features* (cons sym *features*))))
362 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
363 ;; provided? also checks to see if the module is available. We should do that
366 (define (provided? feature)
367 (and (memq feature *features*) #t))
374 (define (make-struct/no-tail vtable . args)
375 (apply make-struct vtable 0 args))
379 ;;; Boot versions of `map' and `for-each', enough to get the expander
388 (cons (f (car l)) (map1 (cdr l))))))
390 (let map2 ((l1 l1) (l2 l2))
393 (cons (f (car l1) (car l2))
394 (map2 (cdr l1) (cdr l2))))))
396 (let lp ((l1 l1) (rest rest))
399 (cons (apply f (car l1) (map car rest))
400 (lp (cdr l1) (map cdr rest))))))))
405 (let for-each1 ((l l))
409 (for-each1 (cdr l))))))
411 (let for-each2 ((l1 l1) (l2 l2))
414 (f (car l1) (car l2))
415 (for-each2 (cdr l1) (cdr l2))))))
417 (let lp ((l1 l1) (rest rest))
420 (apply f (car l1) (map car rest))
421 (lp (cdr l1) (map cdr rest))))))))
423 ;; Temporary definition used in the include-from-path expansion;
426 (define (absolute-file-name? file-name)
429 ;;; {and-map and or-map}
431 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
432 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
437 ;; Apply f to successive elements of l until exhaustion or f returns #f.
438 ;; If returning early, return #f. Otherwise, return the last value returned
439 ;; by f. If f has never been called because l is empty, return #t.
441 (define (and-map f lst)
442 (let loop ((result #t)
447 (loop (f (car l)) (cdr l))))))
451 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
452 ;; If returning early, return the return value of f.
454 (define (or-map f lst)
455 (let loop ((result #f)
459 (loop (f (car l)) (cdr l))))))
463 ;; let format alias simple-format until the more complete version is loaded
465 (define format simple-format)
467 ;; this is scheme wrapping the C code so the final pred call is a tail call,
470 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
471 (if (and (procedure? char_pred)
473 (<= end (string-length s))) ;; let c-code handle range error
474 (or (string-any-c-code char_pred s start (1- end))
475 (char_pred (string-ref s (1- end))))
476 (string-any-c-code char_pred s start end))))
478 ;; this is scheme wrapping the C code so the final pred call is a tail call,
481 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
482 (if (and (procedure? char_pred)
484 (<= end (string-length s))) ;; let c-code handle range error
485 (and (string-every-c-code char_pred s start (1- end))
486 (char_pred (string-ref s (1- end))))
487 (string-every-c-code char_pred s start end))))
489 ;; A variant of string-fill! that we keep for compatability
491 (define (substring-fill! str start end fill)
492 (string-fill! str fill start end))
496 ;; Define a minimal stub of the module API for psyntax, before modules
498 (define (module-name x)
500 (define (module-add! module sym var)
501 (hashq-set! (%get-pre-modules-obarray) sym var))
502 (define (module-define! module sym val)
503 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
505 (variable-set! v val)
506 (module-add! (current-module) sym (make-variable val)))))
507 (define (module-ref module sym)
508 (let ((v (module-variable module sym)))
509 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
510 (define (resolve-module . args)
513 ;; API provided by psyntax
514 (define syntax-violation #f)
515 (define datum->syntax #f)
516 (define syntax->datum #f)
517 (define syntax-source #f)
518 (define identifier? #f)
519 (define generate-temporaries #f)
520 (define bound-identifier=? #f)
521 (define free-identifier=? #f)
523 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
524 ;; expanded macros, to dispatch an input against a set of patterns.
525 (define $sc-dispatch #f)
528 (primitive-load-path "ice-9/psyntax-pp")
529 ;; The binding for `macroexpand' has now been overridden, making psyntax the
536 ((_ x y ...) (if x (and y ...) #f))))
542 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
544 (include-from-path "ice-9/quasisyntax")
546 (define-syntax-rule (when test stmt stmt* ...)
547 (if test (begin stmt stmt* ...)))
549 (define-syntax-rule (unless test stmt stmt* ...)
550 (if (not test) (begin stmt stmt* ...)))
554 (define (fold f seed xs)
555 (let loop ((xs xs) (seed seed))
557 (loop (cdr xs) (f (car xs) seed)))))
558 (define (reverse-map f xs)
559 (fold (lambda (x seed) (cons (f x) seed))
561 (syntax-case whole-expr ()
562 ((_ clause clauses ...)
564 #,@(fold (lambda (clause-builder tail)
565 (clause-builder tail))
569 (define* (bad-clause #:optional (msg "invalid clause"))
570 (syntax-violation 'cond msg whole-expr clause))
571 (syntax-case clause (=> else)
576 (bad-clause "else must be the last clause"))))
577 ((else . _) (bad-clause))
584 ((test => receiver ...)
585 (bad-clause "wrong number of receiver expressions"))
586 ((generator guard => receiver)
588 #`((call-with-values (lambda () generator)
590 (if (apply guard vals)
591 (apply receiver vals)
593 ((generator guard => receiver ...)
594 (bad-clause "wrong number of receiver expressions"))
605 #'(clause clauses ...))))))))
609 (define (fold f seed xs)
610 (let loop ((xs xs) (seed seed))
612 (loop (cdr xs) (f (car xs) seed)))))
613 (define (fold2 f a b xs)
614 (let loop ((xs xs) (a a) (b b))
615 (if (null? xs) (values a b)
617 (lambda () (f (car xs) a b))
619 (loop (cdr xs) a b))))))
620 (define (reverse-map-with-seed f seed xs)
621 (fold2 (lambda (x ys seed)
623 (lambda () (f x seed))
625 (values (cons y ys) seed))))
627 (syntax-case whole-expr ()
628 ((_ expr clause clauses ...)
629 (with-syntax ((key #'key))
632 (lambda (clause-builder tail)
633 (clause-builder tail))
635 (reverse-map-with-seed
636 (lambda (clause seen)
637 (define* (bad-clause #:optional (msg "invalid clause"))
638 (syntax-violation 'case msg whole-expr clause))
639 (syntax-case clause ()
643 (syntax-case #'rest (=>)
644 ((=> receiver) #'(receiver key))
647 "wrong number of receiver expressions"))
648 ((e e* ...) #'(begin e e* ...))
650 (syntax-case #'test (else)
655 (define (warn-datum type)
656 ((@ (system base message)
659 (append (source-properties datum)
661 (syntax->datum #'test)))
663 (syntax->datum clause)
664 (syntax->datum whole-expr)))
665 (when (memv datum seen)
666 (warn-datum 'duplicate-case-datum))
667 (when (or (pair? datum) (array? datum))
668 (warn-datum 'bad-case-datum))
671 (map syntax->datum #'(datums ...)))))
672 (values (lambda (tail)
673 #`((if (memv key '(datums ...))
677 (else (values (lambda (tail)
681 "else must be the last clause")))
685 '() #'(clause clauses ...)))))))))
689 ((do ((var init step ...) ...)
702 (loop (do "step" var step ...)
710 (define-syntax-rule (delay exp)
711 (make-promise (lambda () exp)))
713 (define-syntax with-fluids
715 (define (emit-with-fluids bindings body)
716 (syntax-case bindings ()
722 #,(emit-with-fluids #'bindings body))))))
724 ((_ ((fluid val) ...) exp exp* ...)
725 (with-syntax (((fluid-tmp ...) (generate-temporaries #'(fluid ...)))
726 ((val-tmp ...) (generate-temporaries #'(val ...))))
727 #`(let ((fluid-tmp fluid) ...)
728 (let ((val-tmp val) ...)
729 #,(emit-with-fluids #'((fluid-tmp val-tmp) ...)
730 #'(begin exp exp* ...)))))))))
732 (define-syntax current-source-location
736 (with-syntax ((s (datum->syntax x (syntax-source x))))
739 ;; We provide this accessor out of convenience. current-line and
740 ;; current-column aren't so interesting, because they distort what they
741 ;; are measuring; better to use syntax-source from a macro.
743 (define-syntax current-filename
745 "A macro that expands to the current filename: the filename that
746 the (current-filename) form appears in. Expands to #f if this
747 information is unavailable."
749 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
751 (define-syntax-rule (define-once sym val)
753 (if (module-locally-bound? (current-module) 'sym) sym val)))
755 ;;; The real versions of `map' and `for-each', with cycle detection, and
756 ;;; that use reverse! instead of recursion in the case of `map'.
761 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
764 (if (eq? tortoise hare)
765 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
767 (map1 (cdr hare) (cdr tortoise) #f
768 (cons (f (car hare)) out)))
769 (map1 (cdr hare) tortoise #t
770 (cons (f (car hare)) out)))
773 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
777 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
782 (scm-error 'wrong-type-arg "map"
784 "List of wrong length: ~S"
788 (map2 (cdr h1) (cdr h2) t1 t2 #t
789 (cons (f (car h1) (car h2)) out)))
791 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
794 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
797 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
798 (cons (f (car h1) (car h2)) out)))))
800 ((and (null? h1) (null? h2))
804 (scm-error 'wrong-type-arg "map"
806 "List of wrong length: ~S"
810 (scm-error 'wrong-type-arg "map"
815 (let ((len (length l1)))
816 (let mapn ((rest rest))
818 (if (= (length (car rest)) len)
820 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
821 (list (car rest)) #f)))))
822 (let mapn ((l1 l1) (rest rest) (out '()))
825 (mapn (cdr l1) (map cdr rest)
826 (cons (apply f (car l1) (map car rest)) out)))))))
828 (define map-in-order map)
833 (let for-each1 ((hare l) (tortoise l) (move? #f))
836 (if (eq? tortoise hare)
837 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
841 (for-each1 (cdr hare) (cdr tortoise) #f)))
844 (for-each1 (cdr hare) tortoise #t)))
846 (if (not (null? hare))
847 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
851 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
853 ((and (pair? h1) (pair? h2))
856 (f (car h1) (car h2))
857 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
859 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
862 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
865 (f (car h1) (car h2))
866 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
869 (or (null? h2) (pair? h2))
870 (and (pair? h1) (null? h2)))
874 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
877 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
881 (let ((len (length l1)))
882 (let for-eachn ((rest rest))
884 (if (= (length (car rest)) len)
885 (for-eachn (cdr rest))
886 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
887 (list (car rest)) #f)))))
889 (let for-eachn ((l1 l1) (rest rest))
892 (apply f (car l1) (map car rest))
893 (for-eachn (cdr l1) (map cdr rest))))))))
899 ;;; Extensible exception printing.
902 (define set-exception-printer! #f)
903 ;; There is already a definition of print-exception from backtrace.c
904 ;; that we will override.
906 (let ((exception-printers '()))
907 (define (print-location frame port)
908 (let ((source (and=> frame frame-source)))
909 ;; source := (addr . (filename . (line . column)))
911 (let ((filename (or (cadr source) "<unnamed port>"))
912 (line (caddr source))
913 (col (cdddr source)))
914 (format port "~a:~a:~a: " filename (1+ line) col))
915 (format port "ERROR: "))))
917 (set! set-exception-printer!
919 (set! exception-printers (acons key proc exception-printers))))
921 (set! print-exception
922 (lambda (port frame key args)
923 (define (default-printer)
924 (format port "Throw to key `~a' with args `~s'." key args))
927 (let ((proc (frame-procedure frame)))
928 (print-location frame port)
929 (format port "In procedure ~a:\n"
930 (or (false-if-exception (procedure-name proc))
933 (print-location frame port)
936 (let ((printer (assq-ref exception-printers key)))
938 (printer port key args default-printer)
941 (format port "Error while printing exception.")))
943 (force-output port))))
946 ;;; Printers for those keys thrown by Guile.
949 (define (scm-error-printer port key args default-printer)
950 ;; Abuse case-lambda as a pattern matcher, given that we don't have
951 ;; ice-9 match at this point.
953 ((subr msg args . rest)
955 (format port "In procedure ~a: " subr))
956 (apply format port msg (or args '())))
957 (_ (default-printer)))
960 (define (syntax-error-printer port key args default-printer)
962 ((who what where form subform . extra)
963 (format port "Syntax error:\n")
965 (let ((file (or (assq-ref where 'filename) "unknown file"))
966 (line (and=> (assq-ref where 'line) 1+))
967 (col (assq-ref where 'column)))
968 (format port "~a:~a:~a: " file line col))
969 (format port "unknown location: "))
971 (format port "~a: " who))
972 (format port "~a" what)
974 (format port " in subform ~s of ~s" subform form)
976 (format port " in form ~s" form))))
977 (_ (default-printer)))
980 (define (keyword-error-printer port key args default-printer)
981 (let ((message (cadr args))
982 (faulty (car (cadddr args)))) ; I won't do it again, I promise.
983 (format port "~a: ~s" message faulty)))
985 (define (getaddrinfo-error-printer port key args default-printer)
986 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
988 (set-exception-printer! 'goops-error scm-error-printer)
989 (set-exception-printer! 'host-not-found scm-error-printer)
990 (set-exception-printer! 'keyword-argument-error keyword-error-printer)
991 (set-exception-printer! 'misc-error scm-error-printer)
992 (set-exception-printer! 'no-data scm-error-printer)
993 (set-exception-printer! 'no-recovery scm-error-printer)
994 (set-exception-printer! 'null-pointer-error scm-error-printer)
995 (set-exception-printer! 'out-of-range scm-error-printer)
996 (set-exception-printer! 'program-error scm-error-printer)
997 (set-exception-printer! 'read-error scm-error-printer)
998 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
999 (set-exception-printer! 'signal scm-error-printer)
1000 (set-exception-printer! 'stack-overflow scm-error-printer)
1001 (set-exception-printer! 'system-error scm-error-printer)
1002 (set-exception-printer! 'try-again scm-error-printer)
1003 (set-exception-printer! 'unbound-variable scm-error-printer)
1004 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
1005 (set-exception-printer! 'wrong-type-arg scm-error-printer)
1007 (set-exception-printer! 'syntax-error syntax-error-printer)
1009 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
1017 (define-syntax define-macro
1019 "Define a defmacro."
1021 ((_ (macro . args) doc body1 body ...)
1022 (string? (syntax->datum #'doc))
1023 #'(define-macro macro doc (lambda args body1 body ...)))
1024 ((_ (macro . args) body ...)
1025 #'(define-macro macro #f (lambda args body ...)))
1026 ((_ macro transformer)
1027 #'(define-macro macro #f transformer))
1028 ((_ macro doc transformer)
1029 (or (string? (syntax->datum #'doc))
1030 (not (syntax->datum #'doc)))
1031 #'(define-syntax macro
1034 #((macro-type . defmacro)
1035 (defmacro-args args))
1038 (let ((v (syntax->datum #'args)))
1039 (datum->syntax y (apply transformer v)))))))))))
1041 (define-syntax defmacro
1043 "Define a defmacro, with the old lispy defun syntax."
1045 ((_ macro args doc body1 body ...)
1046 (string? (syntax->datum #'doc))
1047 #'(define-macro macro doc (lambda args body1 body ...)))
1048 ((_ macro args body ...)
1049 #'(define-macro macro #f (lambda args body ...))))))
1058 (define-syntax begin-deprecated
1062 (if (include-deprecated-features)
1063 #'(begin form form* ...)
1068 ;;; {Trivial Functions}
1071 (define (identity x) x)
1073 (define (compose proc . rest)
1074 "Compose PROC with the procedures in REST, such that the last one in
1075 REST is applied first and PROC last, and return the resulting procedure.
1076 The given procedures must have compatible arity."
1079 (let ((g (apply compose rest)))
1081 (call-with-values (lambda () (apply g args)) proc)))))
1083 (define (negate proc)
1084 "Return a procedure with the same arity as PROC that returns the `not'
1087 (not (apply proc args))))
1089 (define (const value)
1090 "Return a procedure that accepts any number of arguments and returns
1095 (define (and=> value procedure)
1096 "When VALUE is #f, return #f. Otherwise, return (PROC VALUE)."
1097 (and value (procedure value)))
1099 (define call/cc call-with-current-continuation)
1101 (define-syntax false-if-exception
1103 ((false-if-exception expr)
1107 ((false-if-exception expr #:warning template arg ...)
1110 (lambda (key . args)
1111 (for-each (lambda (s)
1112 (if (not (string-null? s))
1113 (format (current-warning-port) ";;; ~a\n" s)))
1115 (call-with-output-string
1117 (format port template arg ...)
1118 (print-exception port #f key args)))
1124 ;;; {General Properties}
1127 ;; Properties are a lispy way to associate random info with random objects.
1128 ;; Traditionally properties are implemented as an alist or a plist actually
1129 ;; pertaining to the object in question.
1131 ;; These "object properties" have the advantage that they can be associated with
1132 ;; any object, even if the object has no plist. Object properties are good when
1133 ;; you are extending pre-existing objects in unexpected ways. They also present
1134 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
1135 ;; type that always has properties, it's often still best to store those
1136 ;; properties within the object itself.
1138 (define (make-object-property)
1139 ;; Weak tables are thread-safe.
1140 (let ((prop (make-weak-key-hash-table)))
1141 (make-procedure-with-setter
1142 (lambda (obj) (hashq-ref prop obj))
1143 (lambda (obj val) (hashq-set! prop obj val)))))
1148 ;;; {Symbol Properties}
1151 ;;; Symbol properties are something you see in old Lisp code. In most current
1152 ;;; Guile code, symbols are not used as a data structure -- they are used as
1153 ;;; keys into other data structures.
1155 (define (symbol-property sym prop)
1156 (let ((pair (assoc prop (symbol-pref sym))))
1157 (and pair (cdr pair))))
1159 (define (set-symbol-property! sym prop val)
1160 (let ((pair (assoc prop (symbol-pref sym))))
1163 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
1165 (define (symbol-property-remove! sym prop)
1166 (let ((pair (assoc prop (symbol-pref sym))))
1168 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
1175 (define (array-shape a)
1176 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1177 (array-dimensions a)))
1184 ;;; It's much better if you can use lambda* / define*, of course.
1186 (define (kw-arg-ref args kw)
1187 (let ((rem (member kw args)))
1188 (and rem (pair? (cdr rem)) (cadr rem))))
1192 ;;; {IOTA functions: generating lists of numbers}
1196 (let loop ((count (1- n)) (result '()))
1197 (if (< count 0) result
1198 (loop (1- count) (cons count result)))))
1205 (define (struct-layout s)
1206 (struct-ref (struct-vtable s) vtable-index-layout))
1213 ;; Printing records: by default, records are printed as
1215 ;; #<type-name field1: val1 field2: val2 ...>
1217 ;; You can change that by giving a custom printing function to
1218 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1219 ;; will be called like
1221 ;; (<printer> object port)
1223 ;; It should print OBJECT to PORT.
1225 (define (inherit-print-state old-port new-port)
1226 (if (get-print-state old-port)
1227 (port-with-print-state new-port (get-print-state old-port))
1230 ;; 0: type-name, 1: fields, 2: constructor
1231 (define record-type-vtable
1232 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1234 (display "#<record-type " p)
1235 (display (record-type-name s) p)
1237 (set-struct-vtable-name! s 'record-type)
1240 (define (record-type? obj)
1241 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1243 (define* (make-record-type type-name fields #:optional printer)
1244 ;; Pre-generate constructors for nfields < 20.
1245 (define-syntax make-constructor
1247 (define *max-static-argument-count* 20)
1248 (define (make-formals n)
1251 (cons (datum->syntax
1254 (string (integer->char (+ (char->integer #\a) i)))))
1258 ((_ rtd exp) (not (identifier? #'exp))
1260 (make-constructor rtd n)))
1264 (if (< n *max-static-argument-count*)
1265 (cons (with-syntax (((formal ...) (make-formals n))
1266 ((idx ...) (iota n))
1269 (lambda (formal ...)
1270 (let ((s (allocate-struct rtd n)))
1271 (struct-set! s idx formal)
1278 (if (= (length args) nfields)
1279 (apply make-struct rtd 0 args)
1280 (scm-error 'wrong-number-of-args
1281 (format #f "make-~a" type-name)
1282 "Wrong number of arguments" '() #f)))))))))
1284 (define (default-record-printer s p)
1286 (display (record-type-name (record-type-descriptor s)) p)
1287 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1290 ((not (null? fields))
1292 (display (car fields) p)
1294 (display (struct-ref s off) p)
1295 (loop (cdr fields) (+ 1 off)))))
1298 (let ((rtd (make-struct record-type-vtable 0
1300 (apply string-append
1301 (map (lambda (f) "pw") fields)))
1302 (or printer default-record-printer)
1304 (copy-tree fields))))
1305 (struct-set! rtd (+ vtable-offset-user 2)
1306 (make-constructor rtd (length fields)))
1307 ;; Temporary solution: Associate a name to the record type descriptor
1308 ;; so that the object system can create a wrapper class for it.
1309 (set-struct-vtable-name! rtd (if (symbol? type-name)
1311 (string->symbol type-name)))
1314 (define (record-type-name obj)
1315 (if (record-type? obj)
1316 (struct-ref obj vtable-offset-user)
1317 (error 'not-a-record-type obj)))
1319 (define (record-type-fields obj)
1320 (if (record-type? obj)
1321 (struct-ref obj (+ 1 vtable-offset-user))
1322 (error 'not-a-record-type obj)))
1324 (define* (record-constructor rtd #:optional field-names)
1325 (if (not field-names)
1326 (struct-ref rtd (+ 2 vtable-offset-user))
1328 `(lambda ,field-names
1329 (make-struct ',rtd 0 ,@(map (lambda (f)
1330 (if (memq f field-names)
1333 (record-type-fields rtd)))))))
1335 (define (record-predicate rtd)
1336 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1338 (define (%record-type-error rtd obj) ;; private helper
1339 (or (eq? rtd (record-type-descriptor obj))
1340 (scm-error 'wrong-type-arg "%record-type-check"
1341 "Wrong type record (want `~S'): ~S"
1342 (list (record-type-name rtd) obj)
1345 (define (record-accessor rtd field-name)
1346 (let ((pos (list-index (record-type-fields rtd) field-name)))
1348 (error 'no-such-field field-name))
1350 (if (eq? (struct-vtable obj) rtd)
1351 (struct-ref obj pos)
1352 (%record-type-error rtd obj)))))
1354 (define (record-modifier rtd field-name)
1355 (let ((pos (list-index (record-type-fields rtd) field-name)))
1357 (error 'no-such-field field-name))
1359 (if (eq? (struct-vtable obj) rtd)
1360 (struct-set! obj pos val)
1361 (%record-type-error rtd obj)))))
1363 (define (record? obj)
1364 (and (struct? obj) (record-type? (struct-vtable obj))))
1366 (define (record-type-descriptor obj)
1369 (error 'not-a-record obj)))
1379 ;; Three fields: the procedure itself, the fluid, and the converter.
1380 (make-struct <applicable-struct-vtable> 0 'pwprpr))
1381 (set-struct-vtable-name! <parameter> '<parameter>)
1383 (define* (make-parameter init #:optional (conv (lambda (x) x)))
1384 "Make a new parameter.
1386 A parameter is a dynamically bound value, accessed through a procedure.
1387 To access the current value, apply the procedure with no arguments:
1389 (define p (make-parameter 10))
1392 To provide a new value for the parameter in a dynamic extent, use
1395 (parameterize ((p 20))
1399 The value outside of the dynamic extent of the body is unaffected. To
1400 update the current value, apply it to one argument:
1405 As you can see, the call that updates a parameter returns its previous
1408 All values for the parameter are first run through the CONV procedure,
1409 including INIT, the initial value. The default CONV procedure is the
1410 identity procedure. CONV is commonly used to ensure some set of
1411 invariants on the values that a parameter may have."
1412 (let ((fluid (make-fluid (conv init))))
1413 (make-struct <parameter> 0
1415 (() (fluid-ref fluid))
1416 ((x) (let ((prev (fluid-ref fluid)))
1417 (fluid-set! fluid (conv x))
1421 (define (parameter? x)
1422 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
1424 (define (parameter-fluid p)
1427 (scm-error 'wrong-type-arg "parameter-fluid"
1428 "Not a parameter: ~S" (list p) #f)))
1430 (define (parameter-converter p)
1433 (scm-error 'wrong-type-arg "parameter-fluid"
1434 "Not a parameter: ~S" (list p) #f)))
1436 (define-syntax parameterize
1439 ((_ ((param value) ...) body body* ...)
1440 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
1441 #'(let ((p param) ...)
1442 (if (not (parameter? p))
1443 (scm-error 'wrong-type-arg "parameterize"
1444 "Not a parameter: ~S" (list p) #f))
1446 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
1448 body body* ...)))))))
1450 (define* (fluid->parameter fluid #:optional (conv (lambda (x) x)))
1451 "Make a parameter that wraps a fluid.
1453 The value of the parameter will be the same as the value of the fluid.
1454 If the parameter is rebound in some dynamic extent, perhaps via
1455 `parameterize', the new value will be run through the optional CONV
1456 procedure, as with any parameter. Note that unlike `make-parameter',
1457 CONV is not applied to the initial value."
1458 (make-struct <parameter> 0
1460 (() (fluid-ref fluid))
1461 ((x) (let ((prev (fluid-ref fluid)))
1462 (fluid-set! fluid (conv x))
1468 ;;; Once parameters have booted, define the default prompt tag as being
1472 (set! default-prompt-tag (make-parameter (default-prompt-tag)))
1476 ;;; Current ports as parameters.
1480 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
1482 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
1486 (hashq-remove! (%get-pre-modules-obarray) 'fluid)))
1488 (port-parameterize! current-input-port %current-input-port-fluid
1489 input-port? "expected an input port")
1490 (port-parameterize! current-output-port %current-output-port-fluid
1491 output-port? "expected an output port")
1492 (port-parameterize! current-error-port %current-error-port-fluid
1493 output-port? "expected an output port"))
1500 (define current-warning-port
1501 (make-parameter (current-error-port)
1503 (if (output-port? x)
1505 (error "expected an output port" x)))))
1513 ;; The language can be a symbolic name or a <language> object from
1514 ;; (system base language).
1516 (define current-language (make-parameter 'scheme))
1521 ;;; {High-Level Port Routines}
1524 (define* (open-input-file
1525 file #:key (binary #f) (encoding #f) (guess-encoding #f))
1526 "Takes a string naming an existing file and returns an input port
1527 capable of delivering characters from the file. If the file
1528 cannot be opened, an error is signalled."
1529 (open-file file (if binary "rb" "r")
1531 #:guess-encoding guess-encoding))
1533 (define* (open-output-file file #:key (binary #f) (encoding #f))
1534 "Takes a string naming an output file to be created and returns an
1535 output port capable of writing characters to a new file by that
1536 name. If the file cannot be opened, an error is signalled. If a
1537 file with the given name already exists, the effect is unspecified."
1538 (open-file file (if binary "wb" "w")
1539 #:encoding encoding))
1541 (define* (call-with-input-file
1542 file proc #:key (binary #f) (encoding #f) (guess-encoding #f))
1543 "PROC should be a procedure of one argument, and FILE should be a
1544 string naming a file. The file must
1545 already exist. These procedures call PROC
1546 with one argument: the port obtained by opening the named file for
1547 input or output. If the file cannot be opened, an error is
1548 signalled. If the procedure returns, then the port is closed
1549 automatically and the values yielded by the procedure are returned.
1550 If the procedure does not return, then the port will not be closed
1551 automatically unless it is possible to prove that the port will
1552 never again be used for a read or write operation."
1553 (let ((p (open-input-file file
1556 #:guess-encoding guess-encoding)))
1558 (lambda () (proc p))
1560 (close-input-port p)
1561 (apply values vals)))))
1563 (define* (call-with-output-file file proc #:key (binary #f) (encoding #f))
1564 "PROC should be a procedure of one argument, and FILE should be a
1565 string naming a file. The behaviour is unspecified if the file
1566 already exists. These procedures call PROC
1567 with one argument: the port obtained by opening the named file for
1568 input or output. If the file cannot be opened, an error is
1569 signalled. If the procedure returns, then the port is closed
1570 automatically and the values yielded by the procedure are returned.
1571 If the procedure does not return, then the port will not be closed
1572 automatically unless it is possible to prove that the port will
1573 never again be used for a read or write operation."
1574 (let ((p (open-output-file file #:binary binary #:encoding encoding)))
1576 (lambda () (proc p))
1578 (close-output-port p)
1579 (apply values vals)))))
1581 (define (with-input-from-port port thunk)
1582 (parameterize ((current-input-port port))
1585 (define (with-output-to-port port thunk)
1586 (parameterize ((current-output-port port))
1589 (define (with-error-to-port port thunk)
1590 (parameterize ((current-error-port port))
1593 (define* (with-input-from-file
1594 file thunk #:key (binary #f) (encoding #f) (guess-encoding #f))
1595 "THUNK must be a procedure of no arguments, and FILE must be a
1596 string naming a file. The file must already exist. The file is opened for
1597 input, an input port connected to it is made
1598 the default value returned by `current-input-port',
1599 and the THUNK is called with no arguments.
1600 When the THUNK returns, the port is closed and the previous
1601 default is restored. Returns the values yielded by THUNK. If an
1602 escape procedure is used to escape from the continuation of these
1603 procedures, their behavior is implementation dependent."
1604 (call-with-input-file file
1605 (lambda (p) (with-input-from-port p thunk))
1608 #:guess-encoding guess-encoding))
1610 (define* (with-output-to-file file thunk #:key (binary #f) (encoding #f))
1611 "THUNK must be a procedure of no arguments, and FILE must be a
1612 string naming a file. The effect is unspecified if the file already exists.
1613 The file is opened for output, an output port connected to it is made
1614 the default value returned by `current-output-port',
1615 and the THUNK is called with no arguments.
1616 When the THUNK returns, the port is closed and the previous
1617 default is restored. Returns the values yielded by THUNK. If an
1618 escape procedure is used to escape from the continuation of these
1619 procedures, their behavior is implementation dependent."
1620 (call-with-output-file file
1621 (lambda (p) (with-output-to-port p thunk))
1623 #:encoding encoding))
1625 (define* (with-error-to-file file thunk #:key (binary #f) (encoding #f))
1626 "THUNK must be a procedure of no arguments, and FILE must be a
1627 string naming a file. The effect is unspecified if the file already exists.
1628 The file is opened for output, an output port connected to it is made
1629 the default value returned by `current-error-port',
1630 and the THUNK is called with no arguments.
1631 When the THUNK returns, the port is closed and the previous
1632 default is restored. Returns the values yielded by THUNK. If an
1633 escape procedure is used to escape from the continuation of these
1634 procedures, their behavior is implementation dependent."
1635 (call-with-output-file file
1636 (lambda (p) (with-error-to-port p thunk))
1638 #:encoding encoding))
1640 (define (call-with-input-string string proc)
1641 "Calls the one-argument procedure @var{proc} with a newly created
1642 input port from which @var{string}'s contents may be read. The value
1643 yielded by the @var{proc} is returned."
1644 (proc (open-input-string string)))
1646 (define (with-input-from-string string thunk)
1647 "THUNK must be a procedure of no arguments.
1648 The test of STRING is opened for
1649 input, an input port connected to it is made,
1650 and the THUNK is called with no arguments.
1651 When the THUNK returns, the port is closed.
1652 Returns the values yielded by THUNK. If an
1653 escape procedure is used to escape from the continuation of these
1654 procedures, their behavior is implementation dependent."
1655 (call-with-input-string string
1656 (lambda (p) (with-input-from-port p thunk))))
1658 (define (call-with-output-string proc)
1659 "Calls the one-argument procedure @var{proc} with a newly created output
1660 port. When the function returns, the string composed of the characters
1661 written into the port is returned."
1662 (let ((port (open-output-string)))
1664 (get-output-string port)))
1666 (define (with-output-to-string thunk)
1667 "Calls THUNK and returns its output as a string."
1668 (call-with-output-string
1669 (lambda (p) (with-output-to-port p thunk))))
1671 (define (with-error-to-string thunk)
1672 "Calls THUNK and returns its error output as a string."
1673 (call-with-output-string
1674 (lambda (p) (with-error-to-port p thunk))))
1676 (define the-eof-object (call-with-input-string "" (lambda (p) (read-char p))))
1683 (define (->bool x) (not (not x)))
1690 (define (symbol-append . args)
1691 (string->symbol (apply string-append (map symbol->string args))))
1693 (define (list->symbol . args)
1694 (string->symbol (apply list->string args)))
1696 (define (symbol . args)
1697 (string->symbol (apply string args)))
1704 (define (list-index l k)
1707 (and (not (null? l))
1710 (loop (+ n 1) (cdr l))))))
1714 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1715 ;; `stat' accessors.
1716 (primitive-load-path "ice-9/posix")
1718 (if (provided? 'socket)
1719 (primitive-load-path "ice-9/networking"))
1721 ;; For reference, Emacs file-exists-p uses stat in this same way.
1722 (define file-exists?
1723 (if (provided? 'posix)
1725 (->bool (stat str #f)))
1727 (let ((port (catch 'system-error (lambda () (open-input-file str))
1729 (if port (begin (close-port port) #t)
1732 (define file-is-directory?
1733 (if (provided? 'posix)
1735 (eq? (stat:type (stat str)) 'directory))
1737 (let ((port (catch 'system-error
1739 (open-input-file (string-append str "/.")))
1741 (if port (begin (close-port port) #t)
1744 (define (system-error-errno args)
1745 (if (eq? (car args) 'system-error)
1746 (car (list-ref args 4))
1751 ;;; {Error Handling}
1757 (scm-error 'misc-error #f "?" #f #f))
1759 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1760 (scm-error 'misc-error #f msg (cons message args) #f)))))
1764 ;;; {Time Structures}
1767 (define (tm:sec obj) (vector-ref obj 0))
1768 (define (tm:min obj) (vector-ref obj 1))
1769 (define (tm:hour obj) (vector-ref obj 2))
1770 (define (tm:mday obj) (vector-ref obj 3))
1771 (define (tm:mon obj) (vector-ref obj 4))
1772 (define (tm:year obj) (vector-ref obj 5))
1773 (define (tm:wday obj) (vector-ref obj 6))
1774 (define (tm:yday obj) (vector-ref obj 7))
1775 (define (tm:isdst obj) (vector-ref obj 8))
1776 (define (tm:gmtoff obj) (vector-ref obj 9))
1777 (define (tm:zone obj) (vector-ref obj 10))
1779 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1780 (define (set-tm:min obj val) (vector-set! obj 1 val))
1781 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1782 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1783 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1784 (define (set-tm:year obj val) (vector-set! obj 5 val))
1785 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1786 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1787 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1788 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1789 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1791 (define (tms:clock obj) (vector-ref obj 0))
1792 (define (tms:utime obj) (vector-ref obj 1))
1793 (define (tms:stime obj) (vector-ref obj 2))
1794 (define (tms:cutime obj) (vector-ref obj 3))
1795 (define (tms:cstime obj) (vector-ref obj 4))
1799 ;;; {File Descriptors and Ports}
1802 (define file-position ftell)
1803 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1804 (seek port offset whence))
1806 (define (move->fdes fd/port fd)
1807 (cond ((integer? fd/port)
1808 (dup->fdes fd/port fd)
1812 (primitive-move->fdes fd/port fd)
1813 (set-port-revealed! fd/port 1)
1816 (define (release-port-handle port)
1817 (let ((revealed (port-revealed port)))
1819 (set-port-revealed! port (- revealed 1)))))
1824 (fdopen (dup->fdes port/fd) mode))
1825 ((port/fd mode new-fd)
1826 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1827 (set-port-revealed! port 1)
1833 (dup->port port/fd "r"))
1835 (dup->port port/fd "r" new-fd))))
1837 (define dup->outport
1840 (dup->port port/fd "w"))
1842 (dup->port port/fd "w" new-fd))))
1847 (if (integer? port/fd)
1849 (dup->port port/fd (port-mode port/fd))))
1851 (if (integer? port/fd)
1852 (dup->fdes port/fd new-fd)
1853 (dup->port port/fd (port-mode port/fd) new-fd)))))
1855 (define (duplicate-port port modes)
1856 (dup->port port modes))
1858 (define (fdes->inport fdes)
1859 (let loop ((rest-ports (fdes->ports fdes)))
1860 (cond ((null? rest-ports)
1861 (let ((result (fdopen fdes "r")))
1862 (set-port-revealed! result 1)
1864 ((input-port? (car rest-ports))
1865 (set-port-revealed! (car rest-ports)
1866 (+ (port-revealed (car rest-ports)) 1))
1869 (loop (cdr rest-ports))))))
1871 (define (fdes->outport fdes)
1872 (let loop ((rest-ports (fdes->ports fdes)))
1873 (cond ((null? rest-ports)
1874 (let ((result (fdopen fdes "w")))
1875 (set-port-revealed! result 1)
1877 ((output-port? (car rest-ports))
1878 (set-port-revealed! (car rest-ports)
1879 (+ (port-revealed (car rest-ports)) 1))
1882 (loop (cdr rest-ports))))))
1884 (define (port->fdes port)
1885 (set-port-revealed! port (+ (port-revealed port) 1))
1888 (define (setenv name value)
1890 (putenv (string-append name "=" value))
1893 (define (unsetenv name)
1894 "Remove the entry for NAME from the environment."
1902 (let-syntax ((compile-time-case
1905 ((_ exp clauses ...)
1906 (let ((val (primitive-eval (syntax->datum #'exp))))
1907 (let next-clause ((clauses #'(clauses ...)))
1908 (syntax-case clauses (else)
1910 (syntax-violation 'compile-time-case
1911 "all clauses failed to match" stx))
1914 ((((k ...) form ...) clauses ...)
1915 (if (memv val (syntax->datum #'(k ...)))
1917 (next-clause #'(clauses ...))))))))))))
1918 ;; emacs: (put 'compile-time-case 'scheme-indent-function 1)
1919 (compile-time-case (system-file-name-convention)
1921 (define (file-name-separator? c)
1924 (define file-name-separator-string "/")
1926 (define (absolute-file-name? file-name)
1927 (string-prefix? "/" file-name)))
1930 (define (file-name-separator? c)
1934 (define file-name-separator-string "\\")
1936 (define (absolute-file-name? file-name)
1937 (define (file-name-separator-at-index? idx)
1938 (and (> (string-length file-name) idx)
1939 (file-name-separator? (string-ref file-name idx))))
1940 (define (unc-file-name?)
1941 ;; Universal Naming Convention (UNC) file-names start with \\,
1942 ;; and are always absolute. See:
1943 ;; http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
1944 (and (file-name-separator-at-index? 0)
1945 (file-name-separator-at-index? 1)))
1946 (define (has-drive-specifier?)
1947 (and (>= (string-length file-name) 2)
1948 (let ((drive (string-ref file-name 0)))
1949 (or (char<=? #\a drive #\z)
1950 (char<=? #\A drive #\Z)))
1951 (eqv? (string-ref file-name 1) #\:)))
1952 (or (unc-file-name?)
1953 (if (has-drive-specifier?)
1954 (file-name-separator-at-index? 2)
1955 (file-name-separator-at-index? 0)))))))
1957 (define (in-vicinity vicinity file)
1958 (let ((tail (let ((len (string-length vicinity)))
1961 (string-ref vicinity (- len 1))))))
1962 (string-append vicinity
1963 (if (or (not tail) (file-name-separator? tail))
1965 file-name-separator-string)
1970 ;;; {Help for scm_shell}
1972 ;;; The argument-processing code used by Guile-based shells generates
1973 ;;; Scheme code based on the argument list. This page contains help
1974 ;;; functions for the code it generates.
1977 (define (command-line) (program-arguments))
1979 ;; This is mostly for the internal use of the code generated by
1980 ;; scm_compile_shell_switches.
1982 (define (load-user-init)
1983 (let* ((home (or (getenv "HOME")
1984 (false-if-exception (passwd:dir (getpwuid (getuid))))
1985 file-name-separator-string)) ;; fallback for cygwin etc.
1986 (init-file (in-vicinity home ".guile")))
1987 (if (file-exists? init-file)
1988 (primitive-load init-file))))
1992 ;;; {The interpreter stack}
1995 ;; %stacks defined in stacks.c
1996 (define (%start-stack tag thunk)
1997 (let ((prompt-tag (make-prompt-tag "start-stack")))
2001 (with-fluids ((%stacks (acons tag prompt-tag
2002 (or (fluid-ref %stacks) '()))))
2005 (%start-stack tag (lambda () (apply k args)))))))
2007 (define-syntax-rule (start-stack tag exp)
2008 (%start-stack tag (lambda () exp)))
2012 ;;; {Loading by paths}
2015 ;;; Load a Scheme source file named NAME, searching for it in the
2016 ;;; directories listed in %load-path, and applying each of the file
2017 ;;; name extensions listed in %load-extensions.
2018 (define (load-from-path name)
2019 (start-stack 'load-stack
2020 (primitive-load-path name)))
2022 (define-syntax-rule (add-to-load-path elt)
2023 "Add ELT to Guile's load path, at compile-time and at run-time."
2024 (eval-when (compile load eval)
2025 (set! %load-path (cons elt %load-path))))
2027 (define %load-verbosely #f)
2028 (define (assert-load-verbosity v) (set! %load-verbosely v))
2030 (define (%load-announce file)
2032 (with-output-to-port (current-warning-port)
2035 (display "loading ")
2040 (set! %load-hook %load-announce)
2044 ;;; {Reader Extensions}
2046 ;;; Reader code for various "#c" forms.
2049 (define read-eval? (make-fluid #f))
2050 (read-hash-extend #\.
2052 (if (fluid-ref read-eval?)
2053 (eval (read port) (interaction-environment))
2055 "#. read expansion found and read-eval? is #f."))))
2059 ;;; {Low Level Modules}
2061 ;;; These are the low level data structures for modules.
2063 ;;; Every module object is of the type 'module-type', which is a record
2064 ;;; consisting of the following members:
2066 ;;; - eval-closure: A deprecated field, to be removed in Guile 2.2.
2068 ;;; - obarray: a hash table that maps symbols to variable objects. In this
2069 ;;; hash table, the definitions are found that are local to the module (that
2070 ;;; is, not imported from other modules). When looking up bindings in the
2071 ;;; module, this hash table is searched first.
2073 ;;; - binder: either #f or a function taking a module and a symbol argument.
2074 ;;; If it is a function it is called after the obarray has been
2075 ;;; unsuccessfully searched for a binding. It then can provide bindings
2076 ;;; that would otherwise not be found locally in the module.
2078 ;;; - uses: a list of modules from which non-local bindings can be inherited.
2079 ;;; These modules are the third place queried for bindings after the obarray
2080 ;;; has been unsuccessfully searched and the binder function did not deliver
2081 ;;; a result either.
2083 ;;; - transformer: either #f or a function taking a scheme expression as
2084 ;;; delivered by read. If it is a function, it will be called to perform
2085 ;;; syntax transformations (e. g. makro expansion) on the given scheme
2086 ;;; expression. The output of the transformer function will then be passed
2087 ;;; to Guile's internal memoizer. This means that the output must be valid
2088 ;;; scheme code. The only exception is, that the output may make use of the
2089 ;;; syntax extensions provided to identify the modules that a binding
2092 ;;; - name: the name of the module. This is used for all kinds of printing
2093 ;;; outputs. In certain places the module name also serves as a way of
2094 ;;; identification. When adding a module to the uses list of another
2095 ;;; module, it is made sure that the new uses list will not contain two
2096 ;;; modules of the same name.
2098 ;;; - kind: classification of the kind of module. The value is (currently?)
2099 ;;; only used for printing. It has no influence on how a module is treated.
2100 ;;; Currently the following values are used when setting the module kind:
2101 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
2102 ;;; is set, it defaults to 'module.
2104 ;;; - duplicates-handlers: a list of procedures that get called to make a
2105 ;;; choice between two duplicate bindings when name clashes occur. See the
2106 ;;; `duplicate-handlers' global variable below.
2108 ;;; - observers: a list of procedures that get called when the module is
2111 ;;; - weak-observers: a weak-key hash table of procedures that get called
2112 ;;; when the module is modified. See `module-observe-weak' for details.
2114 ;;; In addition, the module may (must?) contain a binding for
2115 ;;; `%module-public-interface'. This variable should be bound to a module
2116 ;;; representing the exported interface of a module. See the
2117 ;;; `module-public-interface' and `module-export!' procedures.
2119 ;;; !!! warning: The interface to lazy binder procedures is going
2120 ;;; to be changed in an incompatible way to permit all the basic
2121 ;;; module ops to be virtualized.
2123 ;;; (make-module size use-list lazy-binding-proc) => module
2124 ;;; module-{obarray,uses,binder}[|-set!]
2125 ;;; (module? obj) => [#t|#f]
2126 ;;; (module-locally-bound? module symbol) => [#t|#f]
2127 ;;; (module-bound? module symbol) => [#t|#f]
2128 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
2129 ;;; (module-symbol-interned? module symbol) => [#t|#f]
2130 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
2131 ;;; (module-variable module symbol) => [#<variable ...> | #f]
2132 ;;; (module-symbol-binding module symbol opt-value)
2133 ;;; => [ <obj> | opt-value | an error occurs ]
2134 ;;; (module-make-local-var! module symbol) => #<variable...>
2135 ;;; (module-add! module symbol var) => unspecified
2136 ;;; (module-remove! module symbol) => unspecified
2137 ;;; (module-for-each proc module) => unspecified
2138 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
2139 ;;; (set-current-module module) => unspecified
2140 ;;; (current-module) => #<module...>
2146 ;;; {Printing Modules}
2149 ;; This is how modules are printed. You can re-define it.
2150 (define (%print-module mod port)
2152 (display (or (module-kind mod) "module") port)
2154 (display (module-name mod) port)
2156 (display (number->string (object-address mod) 16) port)
2160 ;; Locally extend the syntax to allow record accessors to be defined at
2161 ;; compile-time. Cache the rtd locally to the constructor, the getters and
2162 ;; the setters, in order to allow for redefinition of the record type; not
2163 ;; relevant in the case of modules, but perhaps if we make this public, it
2166 ((define-record-type
2168 (define (make-id scope . fragments)
2169 (datum->syntax scope
2170 (apply symbol-append
2172 (if (symbol? x) x (syntax->datum x)))
2175 (define (getter rtd type-name field slot)
2176 #`(define #,(make-id rtd type-name '- field)
2178 (lambda (#,type-name)
2179 (if (eq? (struct-vtable #,type-name) rtd)
2180 (struct-ref #,type-name #,slot)
2181 (%record-type-error rtd #,type-name))))))
2183 (define (setter rtd type-name field slot)
2184 #`(define #,(make-id rtd 'set- type-name '- field '!)
2186 (lambda (#,type-name val)
2187 (if (eq? (struct-vtable #,type-name) rtd)
2188 (struct-set! #,type-name #,slot val)
2189 (%record-type-error rtd #,type-name))))))
2191 (define (accessors rtd type-name fields n exp)
2192 (syntax-case fields ()
2194 (((field #:no-accessors) field* ...) (identifier? #'field)
2195 (accessors rtd type-name #'(field* ...) (1+ n)
2197 (((field #:no-setter) field* ...) (identifier? #'field)
2198 (accessors rtd type-name #'(field* ...) (1+ n)
2200 #,(getter rtd type-name #'field n))))
2201 (((field #:no-getter) field* ...) (identifier? #'field)
2202 (accessors rtd type-name #'(field* ...) (1+ n)
2204 #,(setter rtd type-name #'field n))))
2205 ((field field* ...) (identifier? #'field)
2206 (accessors rtd type-name #'(field* ...) (1+ n)
2208 #,(getter rtd type-name #'field n)
2209 #,(setter rtd type-name #'field n))))))
2211 (define (predicate rtd type-name fields exp)
2213 rtd type-name fields 0
2216 (define (#,(make-id rtd type-name '?) obj)
2217 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
2219 (define (field-list fields)
2220 (syntax-case fields ()
2222 (((f . opts) . rest) (identifier? #'f)
2223 (cons #'f (field-list #'rest)))
2224 ((f . rest) (identifier? #'f)
2225 (cons #'f (field-list #'rest)))))
2227 (define (constructor rtd type-name fields exp)
2228 (let* ((ctor (make-id rtd type-name '-constructor))
2229 (args (field-list fields))
2232 (predicate rtd type-name fields
2237 (let ((s (allocate-struct rtd #,n)))
2240 #`(struct-set! s #,slot #,arg))
2243 (struct-set! #,rtd (+ vtable-offset-user 2)
2246 (define (type type-name printer fields)
2247 (define (make-layout)
2248 (let lp ((fields fields) (slots '()))
2249 (syntax-case fields ()
2250 (() (datum->syntax #'here
2252 (apply string-append slots))))
2253 ((_ . rest) (lp #'rest (cons "pw" slots))))))
2255 (let ((rtd (make-id type-name type-name '-type)))
2256 (constructor rtd type-name fields
2259 (make-struct record-type-vtable 0
2263 '#,(field-list fields)))
2264 (set-struct-vtable-name! #,rtd '#,type-name)))))
2267 ((_ type-name printer (field ...))
2268 (type #'type-name #'printer #'(field ...)))))))
2272 ;; A module is characterized by an obarray in which local symbols
2273 ;; are interned, a list of modules, "uses", from which non-local
2274 ;; bindings can be inherited, and an optional lazy-binder which
2275 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
2276 ;; bindings that would otherwise not be found locally in the module.
2278 ;; NOTE: If you change the set of fields or their order, you also need to
2279 ;; change the constants in libguile/modules.h.
2281 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
2282 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
2283 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
2285 (define-record-type module
2286 (lambda (obj port) (%print-module obj port))
2291 (transformer #:no-getter)
2295 (import-obarray #:no-setter)
2297 (weak-observers #:no-setter)
2305 ;; make-module &opt size uses binder
2307 ;; Create a new module, perhaps with a particular size of obarray,
2308 ;; initial uses list, or binding procedure.
2310 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
2311 (if (not (integer? size))
2312 (error "Illegal size to make-module." size))
2313 (if (not (and (list? uses)
2314 (and-map module? uses)))
2315 (error "Incorrect use list." uses))
2316 (if (and binder (not (procedure? binder)))
2318 "Lazy-binder expected to be a procedure or #f." binder))
2320 (module-constructor (make-hash-table size)
2321 uses binder #f macroexpand
2325 (make-weak-key-hash-table 31) #f
2326 (make-hash-table 7) #f #f #f))
2331 ;;; {Observer protocol}
2334 (define (module-observe module proc)
2335 (set-module-observers! module (cons proc (module-observers module)))
2338 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
2339 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
2340 ;; be any Scheme object). PROC is invoked and passed MODULE any time
2341 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
2342 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
2345 ;; The two-argument version is kept for backward compatibility: when called
2346 ;; with two arguments, the observer gets unregistered when closure PROC
2347 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
2348 (hashq-set! (module-weak-observers module) observer-id proc))
2350 (define (module-unobserve token)
2351 (let ((module (car token))
2354 (hash-remove! (module-weak-observers module) id)
2355 (set-module-observers! module (delq1! id (module-observers module)))))
2358 (define module-defer-observers #f)
2359 (define module-defer-observers-mutex (make-mutex 'recursive))
2360 (define module-defer-observers-table (make-hash-table))
2362 (define (module-modified m)
2363 (if module-defer-observers
2364 (hash-set! module-defer-observers-table m #t)
2365 (module-call-observers m)))
2367 ;;; This function can be used to delay calls to observers so that they
2368 ;;; can be called once only in the face of massive updating of modules.
2370 (define (call-with-deferred-observers thunk)
2373 (lock-mutex module-defer-observers-mutex)
2374 (set! module-defer-observers #t))
2377 (set! module-defer-observers #f)
2378 (hash-for-each (lambda (m dummy)
2379 (module-call-observers m))
2380 module-defer-observers-table)
2381 (hash-clear! module-defer-observers-table)
2382 (unlock-mutex module-defer-observers-mutex))))
2384 (define (module-call-observers m)
2385 (for-each (lambda (proc) (proc m)) (module-observers m))
2387 ;; We assume that weak observers don't (un)register themselves as they are
2388 ;; called since this would preclude proper iteration over the hash table
2390 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
2394 ;;; {Module Searching in General}
2396 ;;; We sometimes want to look for properties of a symbol
2397 ;;; just within the obarray of one module. If the property
2398 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
2399 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
2402 ;;; Other times, we want to test for a symbol property in the obarray
2403 ;;; of M and, if it is not found there, try each of the modules in the
2404 ;;; uses list of M. This is the normal way of testing for some
2405 ;;; property, so we state these properties without qualification as
2406 ;;; in: ``The symbol 'fnord is interned in module M because it is
2407 ;;; interned locally in module M2 which is a member of the uses list
2411 ;; module-search fn m
2413 ;; return the first non-#f result of FN applied to M and then to
2414 ;; the modules in the uses of m, and so on recursively. If all applications
2415 ;; return #f, then so does this function.
2417 (define (module-search fn m v)
2420 (or (module-search fn (car pos) v)
2423 (loop (module-uses m))))
2426 ;;; {Is a symbol bound in a module?}
2428 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
2429 ;;; of S in M has been set to some well-defined value.
2432 ;; module-locally-bound? module symbol
2434 ;; Is a symbol bound (interned and defined) locally in a given module?
2436 (define (module-locally-bound? m v)
2437 (let ((var (module-local-variable m v)))
2439 (variable-bound? var))))
2441 ;; module-bound? module symbol
2443 ;; Is a symbol bound (interned and defined) anywhere in a given module
2446 (define (module-bound? m v)
2447 (let ((var (module-variable m v)))
2449 (variable-bound? var))))
2451 ;;; {Is a symbol interned in a module?}
2453 ;;; Symbol S in Module M is interned if S occurs in
2454 ;;; of S in M has been set to some well-defined value.
2456 ;;; It is possible to intern a symbol in a module without providing
2457 ;;; an initial binding for the corresponding variable. This is done
2459 ;;; (module-add! module symbol (make-undefined-variable))
2461 ;;; In that case, the symbol is interned in the module, but not
2462 ;;; bound there. The unbound symbol shadows any binding for that
2463 ;;; symbol that might otherwise be inherited from a member of the uses list.
2466 (define (module-obarray-get-handle ob key)
2467 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
2469 (define (module-obarray-ref ob key)
2470 ((if (symbol? key) hashq-ref hash-ref) ob key))
2472 (define (module-obarray-set! ob key val)
2473 ((if (symbol? key) hashq-set! hash-set!) ob key val))
2475 (define (module-obarray-remove! ob key)
2476 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
2478 ;; module-symbol-locally-interned? module symbol
2480 ;; is a symbol interned (not neccessarily defined) locally in a given module
2481 ;; or its uses? Interned symbols shadow inherited bindings even if
2482 ;; they are not themselves bound to a defined value.
2484 (define (module-symbol-locally-interned? m v)
2485 (not (not (module-obarray-get-handle (module-obarray m) v))))
2487 ;; module-symbol-interned? module symbol
2489 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
2490 ;; or its uses? Interned symbols shadow inherited bindings even if
2491 ;; they are not themselves bound to a defined value.
2493 (define (module-symbol-interned? m v)
2494 (module-search module-symbol-locally-interned? m v))
2497 ;;; {Mapping modules x symbols --> variables}
2500 ;; module-local-variable module symbol
2501 ;; return the local variable associated with a MODULE and SYMBOL.
2503 ;;; This function is very important. It is the only function that can
2504 ;;; return a variable from a module other than the mutators that store
2505 ;;; new variables in modules. Therefore, this function is the location
2506 ;;; of the "lazy binder" hack.
2508 ;;; If symbol is defined in MODULE, and if the definition binds symbol
2509 ;;; to a variable, return that variable object.
2511 ;;; If the symbols is not found at first, but the module has a lazy binder,
2512 ;;; then try the binder.
2514 ;;; If the symbol is not found at all, return #f.
2516 ;;; (This is now written in C, see `modules.c'.)
2519 ;;; {Mapping modules x symbols --> bindings}
2521 ;;; These are similar to the mapping to variables, except that the
2522 ;;; variable is dereferenced.
2525 ;; module-symbol-binding module symbol opt-value
2527 ;; return the binding of a variable specified by name within
2528 ;; a given module, signalling an error if the variable is unbound.
2529 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2530 ;; return OPT-VALUE.
2532 (define (module-symbol-local-binding m v . opt-val)
2533 (let ((var (module-local-variable m v)))
2534 (if (and var (variable-bound? var))
2536 (if (not (null? opt-val))
2538 (error "Locally unbound variable." v)))))
2540 ;; module-symbol-binding module symbol opt-value
2542 ;; return the binding of a variable specified by name within
2543 ;; a given module, signalling an error if the variable is unbound.
2544 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2545 ;; return OPT-VALUE.
2547 (define (module-symbol-binding m v . opt-val)
2548 (let ((var (module-variable m v)))
2549 (if (and var (variable-bound? var))
2551 (if (not (null? opt-val))
2553 (error "Unbound variable." v)))))
2558 ;;; {Adding Variables to Modules}
2561 ;; module-make-local-var! module symbol
2563 ;; ensure a variable for V in the local namespace of M.
2564 ;; If no variable was already there, then create a new and uninitialzied
2567 ;; This function is used in modules.c.
2569 (define (module-make-local-var! m v)
2570 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2573 ;; Mark as modified since this function is called when
2574 ;; the standard eval closure defines a binding
2578 ;; Create a new local variable.
2579 (let ((local-var (make-undefined-variable)))
2580 (module-add! m v local-var)
2583 ;; module-ensure-local-variable! module symbol
2585 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2586 ;; there is no binding for SYMBOL, create a new uninitialized
2587 ;; variable. Return the local variable.
2589 (define (module-ensure-local-variable! module symbol)
2590 (or (module-local-variable module symbol)
2591 (let ((var (make-undefined-variable)))
2592 (module-add! module symbol var)
2595 ;; module-add! module symbol var
2597 ;; ensure a particular variable for V in the local namespace of M.
2599 (define (module-add! m v var)
2600 (if (not (variable? var))
2601 (error "Bad variable to module-add!" var))
2602 (if (not (symbol? v))
2603 (error "Bad symbol to module-add!" v))
2604 (module-obarray-set! (module-obarray m) v var)
2605 (module-modified m))
2609 ;; make sure that a symbol is undefined in the local namespace of M.
2611 (define (module-remove! m v)
2612 (module-obarray-remove! (module-obarray m) v)
2613 (module-modified m))
2615 (define (module-clear! m)
2616 (hash-clear! (module-obarray m))
2617 (module-modified m))
2619 ;; MODULE-FOR-EACH -- exported
2621 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2623 (define (module-for-each proc module)
2624 (hash-for-each proc (module-obarray module)))
2626 (define (module-map proc module)
2627 (hash-map->list proc (module-obarray module)))
2631 ;; Modules exist in a separate namespace from values, because you generally do
2632 ;; not want the name of a submodule, which you might not even use, to collide
2633 ;; with local variables that happen to be named the same as the submodule.
2635 (define (module-ref-submodule module name)
2636 (or (hashq-ref (module-submodules module) name)
2637 (and (module-submodule-binder module)
2638 ((module-submodule-binder module) module name))))
2640 (define (module-define-submodule! module name submodule)
2641 (hashq-set! (module-submodules module) name submodule))
2645 ;;; {Module-based Loading}
2648 (define (save-module-excursion thunk)
2649 (let ((inner-module (current-module))
2651 (dynamic-wind (lambda ()
2652 (set! outer-module (current-module))
2653 (set-current-module inner-module)
2654 (set! inner-module #f))
2657 (set! inner-module (current-module))
2658 (set-current-module outer-module)
2659 (set! outer-module #f)))))
2663 ;;; {MODULE-REF -- exported}
2666 ;; Returns the value of a variable called NAME in MODULE or any of its
2667 ;; used modules. If there is no such variable, then if the optional third
2668 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2670 (define (module-ref module name . rest)
2671 (let ((variable (module-variable module name)))
2672 (if (and variable (variable-bound? variable))
2673 (variable-ref variable)
2675 (error "No variable named" name 'in module)
2676 (car rest) ; default value
2679 ;; MODULE-SET! -- exported
2681 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2682 ;; to VALUE; if there is no such variable, an error is signaled.
2684 (define (module-set! module name value)
2685 (let ((variable (module-variable module name)))
2687 (variable-set! variable value)
2688 (error "No variable named" name 'in module))))
2690 ;; MODULE-DEFINE! -- exported
2692 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2693 ;; variable, it is added first.
2695 (define (module-define! module name value)
2696 (let ((variable (module-local-variable module name)))
2699 (variable-set! variable value)
2700 (module-modified module))
2701 (let ((variable (make-variable value)))
2702 (module-add! module name variable)))))
2704 ;; MODULE-DEFINED? -- exported
2706 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2709 (define (module-defined? module name)
2710 (let ((variable (module-variable module name)))
2711 (and variable (variable-bound? variable))))
2713 ;; MODULE-USE! module interface
2715 ;; Add INTERFACE to the list of interfaces used by MODULE.
2717 (define (module-use! module interface)
2718 (if (not (or (eq? module interface)
2719 (memq interface (module-uses module))))
2721 ;; Newly used modules must be appended rather than consed, so that
2722 ;; `module-variable' traverses the use list starting from the first
2724 (set-module-uses! module (append (module-uses module)
2726 (hash-clear! (module-import-obarray module))
2727 (module-modified module))))
2729 ;; MODULE-USE-INTERFACES! module interfaces
2731 ;; Same as MODULE-USE!, but only notifies module observers after all
2732 ;; interfaces are added to the inports list.
2734 (define (module-use-interfaces! module interfaces)
2735 (let* ((cur (module-uses module))
2736 (new (let lp ((in interfaces) (out '()))
2740 (let ((iface (car in)))
2741 (if (or (memq iface cur) (memq iface out))
2743 (cons iface out))))))))
2744 (set-module-uses! module (append cur new))
2745 (hash-clear! (module-import-obarray module))
2746 (module-modified module)))
2750 ;;; {Recursive Namespaces}
2752 ;;; A hierarchical namespace emerges if we consider some module to be
2753 ;;; root, and submodules of that module to be nested namespaces.
2755 ;;; The routines here manage variable names in hierarchical namespace.
2756 ;;; Each variable name is a list of elements, looked up in successively nested
2759 ;;; (nested-ref some-root-module '(foo bar baz))
2760 ;;; => <value of a variable named baz in the submodule bar of
2761 ;;; the submodule foo of some-root-module>
2766 ;;; ;; a-root is a module
2767 ;;; ;; name is a list of symbols
2769 ;;; nested-ref a-root name
2770 ;;; nested-set! a-root name val
2771 ;;; nested-define! a-root name val
2772 ;;; nested-remove! a-root name
2774 ;;; These functions manipulate values in namespaces. For referencing the
2775 ;;; namespaces themselves, use the following:
2777 ;;; nested-ref-module a-root name
2778 ;;; nested-define-module! a-root name mod
2780 ;;; (current-module) is a natural choice for a root so for convenience there are
2783 ;;; local-ref name == nested-ref (current-module) name
2784 ;;; local-set! name val == nested-set! (current-module) name val
2785 ;;; local-define name val == nested-define! (current-module) name val
2786 ;;; local-remove name == nested-remove! (current-module) name
2787 ;;; local-ref-module name == nested-ref-module (current-module) name
2788 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2792 (define (nested-ref root names)
2795 (let loop ((cur root)
2799 (module-ref cur head #f)
2800 (let ((cur (module-ref-submodule cur head)))
2802 (loop cur (car tail) (cdr tail))))))))
2804 (define (nested-set! root names val)
2805 (let loop ((cur root)
2809 (module-set! cur head val)
2810 (let ((cur (module-ref-submodule cur head)))
2812 (error "failed to resolve module" names)
2813 (loop cur (car tail) (cdr tail)))))))
2815 (define (nested-define! root names val)
2816 (let loop ((cur root)
2820 (module-define! cur head val)
2821 (let ((cur (module-ref-submodule cur head)))
2823 (error "failed to resolve module" names)
2824 (loop cur (car tail) (cdr tail)))))))
2826 (define (nested-remove! root names)
2827 (let loop ((cur root)
2831 (module-remove! cur head)
2832 (let ((cur (module-ref-submodule cur head)))
2834 (error "failed to resolve module" names)
2835 (loop cur (car tail) (cdr tail)))))))
2838 (define (nested-ref-module root names)
2839 (let loop ((cur root)
2843 (let ((cur (module-ref-submodule cur (car names))))
2845 (loop cur (cdr names)))))))
2847 (define (nested-define-module! root names module)
2849 (error "can't redefine root module" root module)
2850 (let loop ((cur root)
2854 (module-define-submodule! cur head module)
2855 (let ((cur (or (module-ref-submodule cur head)
2856 (let ((m (make-module 31)))
2857 (set-module-kind! m 'directory)
2858 (set-module-name! m (append (module-name cur)
2860 (module-define-submodule! cur head m)
2862 (loop cur (car tail) (cdr tail)))))))
2865 (define (local-ref names)
2866 (nested-ref (current-module) names))
2868 (define (local-set! names val)
2869 (nested-set! (current-module) names val))
2871 (define (local-define names val)
2872 (nested-define! (current-module) names val))
2874 (define (local-remove names)
2875 (nested-remove! (current-module) names))
2877 (define (local-ref-module names)
2878 (nested-ref-module (current-module) names))
2880 (define (local-define-module names mod)
2881 (nested-define-module! (current-module) names mod))
2887 ;;; {The (guile) module}
2889 ;;; The standard module, which has the core Guile bindings. Also called the
2890 ;;; "root module", as it is imported by many other modules, but it is not
2891 ;;; necessarily the root of anything; and indeed, the module named '() might be
2892 ;;; better thought of as a root.
2895 ;; The root module uses the pre-modules-obarray as its obarray. This
2896 ;; special obarray accumulates all bindings that have been established
2897 ;; before the module system is fully booted.
2899 ;; (The obarray continues to be used by code that has been closed over
2900 ;; before the module system has been booted.)
2902 (define the-root-module
2903 (let ((m (make-module 0)))
2904 (set-module-obarray! m (%get-pre-modules-obarray))
2905 (set-module-name! m '(guile))
2908 ;; The root interface is a module that uses the same obarray as the
2909 ;; root module. It does not allow new definitions, tho.
2911 (define the-scm-module
2912 (let ((m (make-module 0)))
2913 (set-module-obarray! m (%get-pre-modules-obarray))
2914 (set-module-name! m '(guile))
2915 (set-module-kind! m 'interface)
2917 ;; In Guile 1.8 and earlier M was its own public interface.
2918 (set-module-public-interface! m m)
2922 (set-module-public-interface! the-root-module the-scm-module)
2926 ;; Now that we have a root module, even though modules aren't fully booted,
2927 ;; expand the definition of resolve-module.
2929 (define (resolve-module name . args)
2930 (if (equal? name '(guile))
2932 (error "unexpected module to resolve during module boot" name)))
2934 ;; Cheat. These bindings are needed by modules.c, but we don't want
2935 ;; to move their real definition here because that would be unnatural.
2937 (define define-module* #f)
2938 (define process-use-modules #f)
2939 (define module-export! #f)
2940 (define default-duplicate-binding-procedures #f)
2942 ;; This boots the module system. All bindings needed by modules.c
2943 ;; must have been defined by now.
2945 (set-current-module the-root-module)
2950 ;; Now that modules are booted, give module-name its final definition.
2953 (let ((accessor (record-accessor module-type 'name)))
2956 (let ((name (list (gensym))))
2957 ;; Name MOD and bind it in the module root so that it's visible to
2958 ;; `resolve-module'. This is important as `psyntax' stores module
2959 ;; names and relies on being able to `resolve-module' them.
2960 (set-module-name! mod name)
2961 (nested-define-module! (resolve-module '() #f) name mod)
2964 (define (make-modules-in module name)
2965 (or (nested-ref-module module name)
2966 (let ((m (make-module 31)))
2967 (set-module-kind! m 'directory)
2968 (set-module-name! m (append (module-name module) name))
2969 (nested-define-module! module name m)
2972 (define (beautify-user-module! module)
2973 (let ((interface (module-public-interface module)))
2974 (if (or (not interface)
2975 (eq? interface module))
2976 (let ((interface (make-module 31)))
2977 (set-module-name! interface (module-name module))
2978 (set-module-version! interface (module-version module))
2979 (set-module-kind! interface 'interface)
2980 (set-module-public-interface! module interface))))
2981 (if (and (not (memq the-scm-module (module-uses module)))
2982 (not (eq? module the-root-module)))
2983 ;; Import the default set of bindings (from the SCM module) in MODULE.
2984 (module-use! module the-scm-module)))
2986 (define (version-matches? version-ref target)
2987 (define (sub-versions-match? v-refs t)
2988 (define (sub-version-matches? v-ref t)
2989 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2991 ((number? v-ref) (eqv? v-ref t))
2994 ((>=) (>= t (cadr v-ref)))
2995 ((<=) (<= t (cadr v-ref)))
2996 ((and) (and-map matches? (cdr v-ref)))
2997 ((or) (or-map matches? (cdr v-ref)))
2998 ((not) (not (matches? (cadr v-ref))))
2999 (else (error "Invalid sub-version reference" v-ref))))
3000 (else (error "Invalid sub-version reference" v-ref)))))
3002 (and (not (null? t))
3003 (sub-version-matches? (car v-refs) (car t))
3004 (sub-versions-match? (cdr v-refs) (cdr t)))))
3006 (let ((matches? (lambda (v) (version-matches? v target))))
3007 (or (null? version-ref)
3008 (case (car version-ref)
3009 ((and) (and-map matches? (cdr version-ref)))
3010 ((or) (or-map matches? (cdr version-ref)))
3011 ((not) (not (matches? (cadr version-ref))))
3012 (else (sub-versions-match? version-ref target))))))
3014 (define (make-fresh-user-module)
3015 (let ((m (make-module)))
3016 (beautify-user-module! m)
3019 ;; NOTE: This binding is used in libguile/modules.c.
3021 (define resolve-module
3022 (let ((root (make-module)))
3023 (set-module-name! root '())
3024 ;; Define the-root-module as '(guile).
3025 (module-define-submodule! root 'guile the-root-module)
3027 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
3028 (let ((already (nested-ref-module root name)))
3031 (or (not autoload) (module-public-interface already)))
3032 ;; A hit, a palpable hit.
3034 (not (version-matches? version (module-version already))))
3035 (error "incompatible module version already loaded" name))
3038 ;; Try to autoload the module, and recurse.
3039 (try-load-module name version)
3040 (resolve-module name #f #:ensure ensure))
3042 ;; No module found (or if one was, it had no public interface), and
3043 ;; we're not autoloading. Make an empty module if #:ensure is true.
3046 (make-modules-in root name)))))))))
3049 (define (try-load-module name version)
3050 (try-module-autoload name version))
3052 (define (reload-module m)
3053 "Revisit the source file corresponding to the module @var{m}."
3054 (let ((f (module-filename m)))
3056 (save-module-excursion
3058 ;; Re-set the initial environment, as in try-module-autoload.
3059 (set-current-module (make-fresh-user-module))
3060 (primitive-load-path f)
3062 ;; Though we could guess, we *should* know it.
3063 (error "unknown file name for module" m))))
3065 (define (purify-module! module)
3066 "Removes bindings in MODULE which are inherited from the (guile) module."
3067 (let ((use-list (module-uses module)))
3068 (if (and (pair? use-list)
3069 (eq? (car (last-pair use-list)) the-scm-module))
3070 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
3072 ;; Return a module that is an interface to the module designated by
3075 ;; `resolve-interface' takes four keyword arguments:
3077 ;; #:select SELECTION
3079 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
3080 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
3081 ;; is the name in the used module and SEEN is the name in the using
3082 ;; module. Note that SEEN is also passed through RENAMER, below. The
3083 ;; default is to select all bindings. If you specify no selection but
3084 ;; a renamer, only the bindings that already exist in the used module
3085 ;; are made available in the interface. Bindings that are added later
3086 ;; are not picked up.
3090 ;; BINDINGS is a list of bindings which should not be imported.
3094 ;; PREFIX is a symbol that will be appended to each exported name.
3095 ;; The default is to not perform any renaming.
3097 ;; #:renamer RENAMER
3099 ;; RENAMER is a procedure that takes a symbol and returns its new
3100 ;; name. The default is not perform any renaming.
3102 ;; Signal "no code for module" error if module name is not resolvable
3103 ;; or its public interface is not available. Signal "no binding"
3104 ;; error if selected binding does not exist in the used module.
3106 (define* (resolve-interface name #:key
3111 (symbol-prefix-proc prefix)
3114 (let* ((module (resolve-module name #t version #:ensure #f))
3115 (public-i (and module (module-public-interface module))))
3117 (error "no code for module" name))
3118 (if (and (not select) (null? hide) (eq? renamer identity))
3120 (let ((selection (or select (module-map (lambda (sym var) sym)
3122 (custom-i (make-module 31)))
3123 (set-module-kind! custom-i 'custom-interface)
3124 (set-module-name! custom-i name)
3125 ;; XXX - should use a lazy binder so that changes to the
3126 ;; used module are picked up automatically.
3127 (for-each (lambda (bspec)
3128 (let* ((direct? (symbol? bspec))
3129 (orig (if direct? bspec (car bspec)))
3130 (seen (if direct? bspec (cdr bspec)))
3131 (var (or (module-local-variable public-i orig)
3132 (module-local-variable module orig)
3134 ;; fixme: format manually for now
3136 #f "no binding `~A' in module ~A"
3138 (if (memq orig hide)
3139 (set! hide (delq! orig hide))
3140 (module-add! custom-i
3144 ;; Check that we are not hiding bindings which don't exist
3145 (for-each (lambda (binding)
3146 (if (not (module-local-variable public-i binding))
3149 #f "no binding `~A' to hide in module ~A"
3154 (define (symbol-prefix-proc prefix)
3156 (symbol-append prefix symbol)))
3158 ;; This function is called from "modules.c". If you change it, be
3159 ;; sure to update "modules.c" as well.
3161 (define* (define-module* name
3162 #:key filename pure version (duplicates '())
3163 (imports '()) (exports '()) (replacements '())
3164 (re-exports '()) (autoloads '()) transformer)
3165 (define (list-of pred l)
3167 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
3168 (define (valid-export? x)
3169 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
3170 (define (valid-autoload? x)
3171 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
3173 (define (resolve-imports imports)
3174 (define (resolve-import import-spec)
3175 (if (list? import-spec)
3176 (apply resolve-interface import-spec)
3177 (error "unexpected use-module specification" import-spec)))
3178 (let lp ((imports imports) (out '()))
3180 ((null? imports) (reverse! out))
3183 (cons (resolve-import (car imports)) out)))
3184 (else (error "unexpected tail of imports list" imports)))))
3186 ;; We could add a #:no-check arg, set by the define-module macro, if
3187 ;; these checks are taking too much time.
3189 (let ((module (resolve-module name #f)))
3190 (beautify-user-module! module)
3192 (set-module-filename! module filename))
3194 (purify-module! module))
3197 (if (not (list-of integer? version))
3198 (error "expected list of integers for version"))
3199 (set-module-version! module version)
3200 (set-module-version! (module-public-interface module) version)))
3201 (let ((imports (resolve-imports imports)))
3202 (call-with-deferred-observers
3205 (module-use-interfaces! module imports))
3206 (if (list-of valid-export? exports)
3208 (module-export! module exports))
3209 (error "expected exports to be a list of symbols or symbol pairs"))
3210 (if (list-of valid-export? replacements)
3211 (if (pair? replacements)
3212 (module-replace! module replacements))
3213 (error "expected replacements to be a list of symbols or symbol pairs"))
3214 (if (list-of valid-export? re-exports)
3215 (if (pair? re-exports)
3216 (module-re-export! module re-exports))
3217 (error "expected re-exports to be a list of symbols or symbol pairs"))
3219 (if (not (null? autoloads))
3220 (apply module-autoload! module autoloads))
3221 ;; Wait until modules have been loaded to resolve duplicates
3223 (if (pair? duplicates)
3224 (let ((handlers (lookup-duplicates-handlers duplicates)))
3225 (set-module-duplicates-handlers! module handlers))))))
3228 (if (and (pair? transformer) (list-of symbol? transformer))
3229 (let ((iface (resolve-interface transformer))
3230 (sym (car (last-pair transformer))))
3231 (set-module-transformer! module (module-ref iface sym)))
3232 (error "expected transformer to be a module name" transformer)))
3234 (run-hook module-defined-hook module)
3237 ;; `module-defined-hook' is a hook that is run whenever a new module
3238 ;; is defined. Its members are called with one argument, the new
3240 (define module-defined-hook (make-hook 1))
3247 (define (make-autoload-interface module name bindings)
3248 (let ((b (lambda (a sym definep)
3250 (and (memq sym bindings)
3251 (let ((i (module-public-interface (resolve-module name))))
3253 (error "missing interface for module" name))
3254 (let ((autoload (memq a (module-uses module))))
3255 ;; Replace autoload-interface with actual interface if
3256 ;; that has not happened yet.
3257 (if (pair? autoload)
3258 (set-car! autoload i)))
3259 (module-local-variable i sym)))
3260 #:warning "Failed to autoload ~a in ~a:\n" sym name))))
3261 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
3262 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
3263 (make-hash-table 0) #f #f #f)))
3265 (define (module-autoload! module . args)
3266 "Have @var{module} automatically load the module named @var{name} when one
3267 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
3268 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
3269 module '(ice-9 q) '(make-q q-length))}."
3270 (let loop ((args args))
3274 (error "invalid name+binding autoload list" args))
3276 (let ((name (car args))
3277 (bindings (cadr args)))
3278 (module-use! module (make-autoload-interface module
3280 (loop (cddr args)))))))
3285 ;;; {Autoloading modules}
3288 (define autoloads-in-progress '())
3290 ;; This function is called from scm_load_scheme_module in
3291 ;; "deprecated.c". Please do not change its interface.
3293 (define* (try-module-autoload module-name #:optional version)
3294 "Try to load a module of the given name. If it is not found, return
3295 #f. Otherwise return #t. May raise an exception if a file is found,
3296 but it fails to load."
3297 (let* ((reverse-name (reverse module-name))
3298 (name (symbol->string (car reverse-name)))
3299 (dir-hint-module-name (reverse (cdr reverse-name)))
3300 (dir-hint (apply string-append
3302 (string-append (symbol->string elt)
3303 file-name-separator-string))
3304 dir-hint-module-name))))
3305 (resolve-module dir-hint-module-name #f)
3306 (and (not (autoload-done-or-in-progress? dir-hint name))
3309 (lambda () (autoload-in-progress! dir-hint name))
3311 (with-fluids ((current-reader #f))
3312 (save-module-excursion
3314 (define (call/ec proc)
3315 (let ((tag (make-prompt-tag)))
3319 (proc (lambda () (abort-to-prompt tag))))
3320 (lambda (k) (values)))))
3321 ;; The initial environment when loading a module is a fresh
3323 (set-current-module (make-fresh-user-module))
3324 ;; Here we could allow some other search strategy (other than
3325 ;; primitive-load-path), for example using versions encoded
3326 ;; into the file system -- but then we would have to figure
3327 ;; out how to locate the compiled file, do auto-compilation,
3328 ;; etc. Punt for now, and don't use versions when locating
3332 (primitive-load-path (in-vicinity dir-hint name)
3334 (set! didit #t)))))))
3335 (lambda () (set-autoloaded! dir-hint name didit)))
3340 ;;; {Dynamic linking of modules}
3343 (define autoloads-done '((guile . guile)))
3345 (define (autoload-done-or-in-progress? p m)
3346 (let ((n (cons p m)))
3347 (->bool (or (member n autoloads-done)
3348 (member n autoloads-in-progress)))))
3350 (define (autoload-done! p m)
3351 (let ((n (cons p m)))
3352 (set! autoloads-in-progress
3353 (delete! n autoloads-in-progress))
3354 (or (member n autoloads-done)
3355 (set! autoloads-done (cons n autoloads-done)))))
3357 (define (autoload-in-progress! p m)
3358 (let ((n (cons p m)))
3359 (set! autoloads-done
3360 (delete! n autoloads-done))
3361 (set! autoloads-in-progress (cons n autoloads-in-progress))))
3363 (define (set-autoloaded! p m done?)
3365 (autoload-done! p m)
3366 (let ((n (cons p m)))
3367 (set! autoloads-done (delete! n autoloads-done))
3368 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
3372 ;;; {Run-time options}
3375 (define-syntax define-option-interface
3377 ((_ (interface (options enable disable) (option-set!)))
3384 (begin (interface arg) (interface))
3387 (apply (lambda (name value documentation)
3389 (let ((len (string-length (symbol->string name))))
3397 (display documentation)
3401 (define (enable . flags)
3402 (interface (append flags (interface)))
3404 (define (disable . flags)
3405 (let ((options (interface)))
3406 (for-each (lambda (flag) (set! options (delq! flag options)))
3410 (define-syntax-rule (option-set! opt val)
3411 (eval-when (eval load compile expand)
3412 (options (append (options) (list 'opt val)))))))))
3414 (define-option-interface
3415 (debug-options-interface
3416 (debug-options debug-enable debug-disable)
3419 (define-option-interface
3420 (read-options-interface
3421 (read-options read-enable read-disable)
3424 (define-option-interface
3425 (print-options-interface
3426 (print-options print-enable print-disable)
3431 ;;; {The Unspecified Value}
3433 ;;; Currently Guile represents unspecified values via one particular value,
3434 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
3435 ;;; future if we could replace this with a return of 0 values, though.
3438 (define-syntax *unspecified*
3439 (identifier-syntax (if #f #f)))
3441 (define (unspecified? v) (eq? v *unspecified*))
3449 (define *repl-stack* (make-fluid '()))
3451 ;; Programs can call `batch-mode?' to see if they are running as part of a
3452 ;; script or if they are running interactively. REPL implementations ensure that
3453 ;; `batch-mode?' returns #f during their extent.
3455 (define (batch-mode?)
3456 (null? (fluid-ref *repl-stack*)))
3458 ;; Programs can re-enter batch mode, for example after a fork, by calling
3459 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3460 ;; to abort to the outermost prompt, and call a thunk there.
3462 (define (ensure-batch-mode!)
3463 (set! batch-mode? (lambda () #t)))
3465 (define (quit . args)
3466 (apply throw 'quit args))
3470 (define (gc-run-time)
3471 (cdr (assq 'gc-time-taken (gc-stats))))
3473 (define abort-hook (make-hook))
3474 (define before-error-hook (make-hook))
3475 (define after-error-hook (make-hook))
3476 (define before-backtrace-hook (make-hook))
3477 (define after-backtrace-hook (make-hook))
3479 (define before-read-hook (make-hook))
3480 (define after-read-hook (make-hook))
3481 (define before-eval-hook (make-hook 1))
3482 (define after-eval-hook (make-hook 1))
3483 (define before-print-hook (make-hook 1))
3484 (define after-print-hook (make-hook 1))
3486 ;;; This hook is run at the very end of an interactive session.
3488 (define exit-hook (make-hook))
3490 ;;; The default repl-reader function. We may override this if we've
3491 ;;; the readline library.
3493 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3494 (if (not (char-ready?))
3496 (display (if (string? prompt) prompt (prompt)))
3497 ;; An interesting situation. The printer resets the column to
3498 ;; 0 by printing a newline, but we then advance it by printing
3499 ;; the prompt. However the port-column of the output port
3500 ;; does not typically correspond with the actual column on the
3501 ;; screen, because the input is echoed back! Since the
3502 ;; input is line-buffered and thus ends with a newline, the
3503 ;; output will really start on column zero. So, here we zero
3504 ;; it out. See bug 9664.
3506 ;; Note that for similar reasons, the output-line will not
3507 ;; reflect the actual line on the screen. But given the
3508 ;; possibility of multiline input, the fix is not as
3509 ;; straightforward, so we don't bother.
3511 ;; Also note that the readline implementation papers over
3512 ;; these concerns, because it's readline itself printing the
3513 ;; prompt, and not Guile.
3514 (set-port-column! (current-output-port) 0)))
3516 (run-hook before-read-hook)
3517 ((or reader read) (current-input-port))))
3524 ;;; with `continue' and `break'.
3527 ;; The inliner will remove the prompts at compile-time if it finds that
3528 ;; `continue' or `break' are not used.
3530 (define-syntax while
3533 ((while cond body ...)
3534 #`(let ((break-tag (make-prompt-tag "break"))
3535 (continue-tag (make-prompt-tag "continue")))
3539 (define-syntax #,(datum->syntax #'while 'break)
3543 #'(abort-to-prompt break-tag arg (... ...)))
3546 (apply abort-to-prompt break-tag args))))))
3551 (define-syntax #,(datum->syntax #'while 'continue)
3555 #'(abort-to-prompt continue-tag))
3557 (syntax-violation 'continue "too many arguments" x))
3560 (abort-to-prompt continue-tag))))))
3561 (do () ((not cond) #f) body ...))
3562 (lambda (k) (lp)))))
3566 (apply values args)))))))))
3571 ;;; {Module System Macros}
3574 ;; Return a list of expressions that evaluate to the appropriate
3575 ;; arguments for resolve-interface according to SPEC.
3577 (eval-when (compile)
3578 (if (memq 'prefix (read-options))
3579 (error "boot-9 must be compiled with #:kw, not :kw")))
3581 (define (keyword-like-symbol->keyword sym)
3582 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3584 (define-syntax define-module
3586 (define (keyword-like? stx)
3587 (let ((dat (syntax->datum stx)))
3589 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3590 (define (->keyword sym)
3591 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3593 (define (parse-iface args)
3594 (let loop ((in args) (out '()))
3597 ;; The user wanted #:foo, but wrote :foo. Fix it.
3598 ((sym . in) (keyword-like? #'sym)
3599 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3600 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3601 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3602 ((#:renamer renamer . in)
3603 (loop #'in (cons* #',renamer #:renamer out)))
3605 (loop #'in (cons* #'val #'kw out))))))
3607 (define (parse args imp exp rex rep aut)
3608 ;; Just quote everything except #:use-module and #:use-syntax. We
3609 ;; need to know about all arguments regardless since we want to turn
3610 ;; symbols that look like keywords into real keywords, and the
3611 ;; keyword args in a define-module form are not regular
3612 ;; (i.e. no-backtrace doesn't take a value).
3613 (syntax-case args ()
3615 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3616 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3617 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3618 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3619 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3620 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3621 ;; The user wanted #:foo, but wrote :foo. Fix it.
3622 ((sym . args) (keyword-like? #'sym)
3623 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3624 imp exp rex rep aut))
3625 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3626 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3627 ((#:no-backtrace . args)
3629 (parse #'args imp exp rex rep aut))
3631 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3633 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3634 ((#:version (v ...) . args)
3635 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3636 ((#:duplicates (d ...) . args)
3637 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3638 ((#:filename f . args)
3639 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3640 ((#:use-module (name name* ...) . args)
3641 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3642 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3643 ((#:use-syntax (name name* ...) . args)
3644 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3645 #`(#:transformer '(name name* ...)
3646 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3647 ((#:use-module ((name name* ...) arg ...) . args)
3648 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3650 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3652 ((#:export (ex ...) . args)
3653 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3654 ((#:export-syntax (ex ...) . args)
3655 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3656 ((#:re-export (re ...) . args)
3657 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3658 ((#:re-export-syntax (re ...) . args)
3659 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3660 ((#:replace (r ...) . args)
3661 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3662 ((#:replace-syntax (r ...) . args)
3663 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3664 ((#:autoload name bindings . args)
3665 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3667 (syntax-violation 'define-module "unknown keyword or bad argument"
3671 ((_ (name name* ...) arg ...)
3672 (and-map symbol? (syntax->datum #'(name name* ...)))
3673 (with-syntax (((quoted-arg ...)
3674 (parse #'(arg ...) '() '() '() '() '()))
3675 ;; Ideally the filename is either a string or #f;
3676 ;; this hack is to work around a case in which
3677 ;; port-filename returns a symbol (`socket') for
3679 (filename (let ((f (assq-ref (or (syntax-source x) '())
3681 (and (string? f) f))))
3682 #'(eval-when (eval load compile expand)
3683 (let ((m (define-module* '(name name* ...)
3684 #:filename filename quoted-arg ...)))
3685 (set-current-module m)
3688 ;; The guts of the use-modules macro. Add the interfaces of the named
3689 ;; modules to the use-list of the current module, in order.
3691 ;; This function is called by "modules.c". If you change it, be sure
3692 ;; to change scm_c_use_module as well.
3694 (define (process-use-modules module-interface-args)
3695 (let ((interfaces (map (lambda (mif-args)
3696 (or (apply resolve-interface mif-args)
3697 (error "no such module" mif-args)))
3698 module-interface-args)))
3699 (call-with-deferred-observers
3701 (module-use-interfaces! (current-module) interfaces)))))
3703 (define-syntax use-modules
3705 (define (keyword-like? stx)
3706 (let ((dat (syntax->datum stx)))
3708 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3709 (define (->keyword sym)
3710 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3712 (define (quotify-iface args)
3713 (let loop ((in args) (out '()))
3716 ;; The user wanted #:foo, but wrote :foo. Fix it.
3717 ((sym . in) (keyword-like? #'sym)
3718 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3719 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3720 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3721 ((#:renamer renamer . in)
3722 (loop #'in (cons* #'renamer #:renamer out)))
3724 (loop #'in (cons* #''val #'kw out))))))
3726 (define (quotify specs)
3727 (let lp ((in specs) (out '()))
3730 (((name name* ...) . in)
3731 (and-map symbol? (syntax->datum #'(name name* ...)))
3732 (lp #'in (cons #''((name name* ...)) out)))
3733 ((((name name* ...) arg ...) . in)
3734 (and-map symbol? (syntax->datum #'(name name* ...)))
3735 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3736 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3741 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3742 #'(eval-when (eval load compile expand)
3743 (process-use-modules (list quoted-args ...))
3746 (include-from-path "ice-9/r6rs-libraries")
3748 (define-syntax-rule (define-private foo bar)
3751 (define-syntax define-public
3753 ((_ (name . args) . body)
3755 (define (name . args) . body)
3762 (define-syntax-rule (defmacro-public name args body ...)
3764 (defmacro name args body ...)
3765 (export-syntax name)))
3767 ;; And now for the most important macro.
3768 (define-syntax-rule (λ formals body ...)
3769 (lambda formals body ...))
3772 ;; Export a local variable
3774 ;; This function is called from "modules.c". If you change it, be
3775 ;; sure to update "modules.c" as well.
3777 (define (module-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-ensure-local-variable! m internal-name)))
3783 (module-add! public-i external-name var)))
3786 (define (module-replace! m names)
3787 (let ((public-i (module-public-interface m)))
3788 (for-each (lambda (name)
3789 (let* ((internal-name (if (pair? name) (car name) name))
3790 (external-name (if (pair? name) (cdr name) name))
3791 (var (module-ensure-local-variable! m internal-name)))
3792 ;; FIXME: use a bit on variables instead of object
3794 (set-object-property! var 'replace #t)
3795 (module-add! public-i external-name var)))
3798 ;; Export all local variables from a module
3800 (define (module-export-all! mod)
3801 (define (fresh-interface!)
3802 (let ((iface (make-module)))
3803 (set-module-name! iface (module-name mod))
3804 (set-module-version! iface (module-version mod))
3805 (set-module-kind! iface 'interface)
3806 (set-module-public-interface! mod iface)
3808 (let ((iface (or (module-public-interface mod)
3809 (fresh-interface!))))
3810 (set-module-obarray! iface (module-obarray mod))))
3812 ;; Re-export a imported variable
3814 (define (module-re-export! m names)
3815 (let ((public-i (module-public-interface m)))
3816 (for-each (lambda (name)
3817 (let* ((internal-name (if (pair? name) (car name) name))
3818 (external-name (if (pair? name) (cdr name) name))
3819 (var (module-variable m internal-name)))
3821 (error "Undefined variable:" internal-name))
3822 ((eq? var (module-local-variable m internal-name))
3823 (error "re-exporting local variable:" internal-name))
3825 (module-add! public-i external-name var)))))
3828 (define-syntax-rule (export name ...)
3829 (eval-when (eval load compile expand)
3830 (call-with-deferred-observers
3832 (module-export! (current-module) '(name ...))))))
3834 (define-syntax-rule (re-export name ...)
3835 (eval-when (eval load compile expand)
3836 (call-with-deferred-observers
3838 (module-re-export! (current-module) '(name ...))))))
3840 (define-syntax-rule (export! name ...)
3841 (eval-when (eval load compile expand)
3842 (call-with-deferred-observers
3844 (module-replace! (current-module) '(name ...))))))
3846 (define-syntax-rule (export-syntax name ...)
3849 (define-syntax-rule (re-export-syntax name ...)
3850 (re-export name ...))
3857 (define* (make-mutable-parameter init #:optional (converter identity))
3858 (let ((fluid (make-fluid (converter init))))
3860 (() (fluid-ref fluid))
3861 ((val) (fluid-set! fluid (converter val))))))
3866 ;;; {Handling of duplicate imported bindings}
3869 ;; Duplicate handlers take the following arguments:
3871 ;; module importing module
3872 ;; name conflicting name
3873 ;; int1 old interface where name occurs
3874 ;; val1 value of binding in old interface
3875 ;; int2 new interface where name occurs
3876 ;; val2 value of binding in new interface
3877 ;; var previous resolution or #f
3878 ;; val value of previous resolution
3880 ;; A duplicate handler can take three alternative actions:
3882 ;; 1. return #f => leave responsibility to next handler
3883 ;; 2. exit with an error
3884 ;; 3. return a variable resolving the conflict
3887 (define duplicate-handlers
3888 (let ((m (make-module 7)))
3890 (define (check module name int1 val1 int2 val2 var val)
3891 (scm-error 'misc-error
3893 "~A: `~A' imported from both ~A and ~A"
3894 (list (module-name module)
3900 (define (warn module name int1 val1 int2 val2 var val)
3901 (format (current-warning-port)
3902 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3903 (module-name module)
3909 (define (replace module name int1 val1 int2 val2 var val)
3910 (let ((old (or (and var (object-property var 'replace) var)
3911 (module-variable int1 name)))
3912 (new (module-variable int2 name)))
3913 (if (object-property old 'replace)
3914 (and (or (eq? old new)
3915 (not (object-property new 'replace)))
3917 (and (object-property new 'replace)
3920 (define (warn-override-core module name int1 val1 int2 val2 var val)
3921 (and (eq? int1 the-scm-module)
3923 (format (current-warning-port)
3924 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3925 (module-name module)
3928 (module-local-variable int2 name))))
3930 (define (first module name int1 val1 int2 val2 var val)
3931 (or var (module-local-variable int1 name)))
3933 (define (last module name int1 val1 int2 val2 var val)
3934 (module-local-variable int2 name))
3936 (define (noop module name int1 val1 int2 val2 var val)
3939 (set-module-name! m 'duplicate-handlers)
3940 (set-module-kind! m 'interface)
3941 (module-define! m 'check check)
3942 (module-define! m 'warn warn)
3943 (module-define! m 'replace replace)
3944 (module-define! m 'warn-override-core warn-override-core)
3945 (module-define! m 'first first)
3946 (module-define! m 'last last)
3947 (module-define! m 'merge-generics noop)
3948 (module-define! m 'merge-accessors noop)
3951 (define (lookup-duplicates-handlers handler-names)
3953 (map (lambda (handler-name)
3954 (or (module-symbol-local-binding
3955 duplicate-handlers handler-name #f)
3956 (error "invalid duplicate handler name:"
3958 (if (list? handler-names)
3960 (list handler-names)))))
3962 (define default-duplicate-binding-procedures
3963 (make-mutable-parameter #f))
3965 (define default-duplicate-binding-handler
3966 (make-mutable-parameter '(replace warn-override-core warn last)
3967 (lambda (handler-names)
3968 (default-duplicate-binding-procedures
3969 (lookup-duplicates-handlers handler-names))
3976 ;;; Load is tricky when combined with relative file names, compilation,
3977 ;;; and the file system. If a file name is relative, what is it
3978 ;;; relative to? The name of the source file at the time it was
3979 ;;; compiled? The name of the compiled file? What if both or either
3980 ;;; were installed? And how do you get that information? Tricky, I
3983 ;;; To get around all of this, we're going to do something nasty, and
3984 ;;; turn `load' into a macro. That way it can know the name of the
3985 ;;; source file with respect to which it was invoked, so it can resolve
3986 ;;; relative file names with respect to the original source file.
3988 ;;; There is an exception, and that is that if the source file was in
3989 ;;; the load path when it was compiled, instead of looking up against
3990 ;;; the absolute source location, we load-from-path against the relative
3991 ;;; source location.
3994 (define %auto-compilation-options
3995 ;; Default `compile-file' option when auto-compiling.
3996 '(#:warnings (unbound-variable arity-mismatch format
3997 duplicate-case-datum bad-case-datum)))
3999 (define* (load-in-vicinity dir file-name #:optional reader)
4000 "Load source file FILE-NAME in vicinity of directory DIR. Use a
4001 pre-compiled version of FILE-NAME when available, and auto-compile one
4002 when none is available, reading FILE-NAME with READER."
4004 ;; The auto-compilation code will residualize a .go file in the cache
4005 ;; dir: by default, $HOME/.cache/guile/2.0/ccache/PATH.go. This
4006 ;; function determines the PATH to use as a key into the compilation
4008 (define (canonical->suffix canon)
4010 ((and (not (string-null? canon))
4011 (file-name-separator? (string-ref canon 0)))
4013 ((and (eq? (system-file-name-convention) 'windows)
4014 (absolute-file-name? canon))
4015 ;; An absolute file name that doesn't start with a separator
4016 ;; starts with a drive component. Transform the drive component
4017 ;; to a file name element: c:\foo -> \c\foo.
4018 (string-append file-name-separator-string
4019 (substring canon 0 1)
4020 (substring canon 2)))
4023 (define compiled-extension
4024 ;; File name extension of compiled files.
4025 (cond ((or (null? %load-compiled-extensions)
4026 (string-null? (car %load-compiled-extensions)))
4027 (warn "invalid %load-compiled-extensions"
4028 %load-compiled-extensions)
4030 (else (car %load-compiled-extensions))))
4032 (define (more-recent? stat1 stat2)
4033 ;; Return #t when STAT1 has an mtime greater than that of STAT2.
4034 (or (> (stat:mtime stat1) (stat:mtime stat2))
4035 (and (= (stat:mtime stat1) (stat:mtime stat2))
4036 (>= (stat:mtimensec stat1)
4037 (stat:mtimensec stat2)))))
4039 (define (fallback-file-name canon-file-name)
4040 ;; Return the in-cache compiled file name for source file
4043 ;; FIXME: would probably be better just to append
4044 ;; SHA1(canon-file-name) to the %compile-fallback-path, to avoid
4045 ;; deep directory stats.
4046 (and %compile-fallback-path
4047 (string-append %compile-fallback-path
4048 (canonical->suffix canon-file-name)
4049 compiled-extension)))
4051 (define (compile file)
4052 ;; Compile source FILE, lazily loading the compiler.
4053 ((module-ref (resolve-interface '(system base compile))
4056 #:opts %auto-compilation-options
4057 #:env (current-module)))
4059 ;; Returns the .go file corresponding to `name'. Does not search load
4060 ;; paths, only the fallback path. If the .go file is missing or out
4061 ;; of date, and auto-compilation is enabled, will try
4062 ;; auto-compilation, just as primitive-load-path does internally.
4063 ;; primitive-load is unaffected. Returns #f if auto-compilation
4064 ;; failed or was disabled.
4066 ;; NB: Unless we need to compile the file, this function should not
4067 ;; cause (system base compile) to be loaded up. For that reason
4068 ;; compiled-file-name partially duplicates functionality from (system
4071 (define (fresh-compiled-file-name name scmstat go-file-name)
4072 ;; Return GO-FILE-NAME after making sure that it contains a freshly
4073 ;; compiled version of source file NAME with stat SCMSTAT; return #f
4076 (let ((gostat (and (not %fresh-auto-compile)
4077 (stat go-file-name #f))))
4078 (if (and gostat (more-recent? gostat scmstat))
4082 (format (current-warning-port)
4083 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
4086 (%load-should-auto-compile
4087 (%warn-auto-compilation-enabled)
4088 (format (current-warning-port) ";;; compiling ~a\n" name)
4089 (let ((cfn (compile name)))
4090 (format (current-warning-port) ";;; compiled ~a\n" cfn)
4093 #:warning "WARNING: compilation of ~a failed:\n" name))
4095 (define (sans-extension file)
4096 (let ((dot (string-rindex file #\.)))
4098 (substring file 0 dot)
4101 (define (load-absolute abs-file-name)
4102 ;; Load from ABS-FILE-NAME, using a compiled file or auto-compiling
4106 (stat abs-file-name)
4107 #:warning "Stat of ~a failed:\n" abs-file-name))
4109 (define (pre-compiled)
4110 (and=> (search-path %load-compiled-path (sans-extension file-name)
4111 %load-compiled-extensions #t)
4112 (lambda (go-file-name)
4113 (let ((gostat (stat go-file-name #f)))
4114 (and gostat (more-recent? gostat scmstat)
4118 (and=> (false-if-exception (canonicalize-path abs-file-name))
4120 (and=> (fallback-file-name canon)
4121 (lambda (go-file-name)
4122 (fresh-compiled-file-name abs-file-name
4126 (let ((compiled (and scmstat (or (pre-compiled) (fallback)))))
4130 (%load-hook abs-file-name))
4131 (load-compiled compiled))
4132 (start-stack 'load-stack
4133 (primitive-load abs-file-name)))))
4135 (save-module-excursion
4137 (with-fluids ((current-reader reader)
4138 (%file-port-name-canonicalization 'relative))
4140 ((absolute-file-name? file-name)
4141 (load-absolute file-name))
4142 ((absolute-file-name? dir)
4143 (load-absolute (in-vicinity dir file-name)))
4145 (load-from-path (in-vicinity dir file-name))))))))
4148 (make-variable-transformer
4150 (let* ((src (syntax-source x))
4151 (file (and src (assq-ref src 'filename)))
4152 (dir (and (string? file) (dirname file))))
4155 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
4159 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
4163 ;;; {`cond-expand' for SRFI-0 support.}
4165 ;;; This syntactic form expands into different commands or
4166 ;;; definitions, depending on the features provided by the Scheme
4172 ;;; --> (cond-expand <cond-expand-clause>+)
4173 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
4174 ;;; <cond-expand-clause>
4175 ;;; --> (<feature-requirement> <command-or-definition>*)
4176 ;;; <feature-requirement>
4177 ;;; --> <feature-identifier>
4178 ;;; | (and <feature-requirement>*)
4179 ;;; | (or <feature-requirement>*)
4180 ;;; | (not <feature-requirement>)
4181 ;;; <feature-identifier>
4182 ;;; --> <a symbol which is the name or alias of a SRFI>
4184 ;;; Additionally, this implementation provides the
4185 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
4186 ;;; determine the implementation type and the supported standard.
4188 ;;; Remember to update the features list when adding more SRFIs.
4191 (define %cond-expand-features
4192 ;; This should contain only features that are present in core Guile,
4193 ;; before loading any modules. Modular features are handled by
4194 ;; placing 'cond-expand-provide' in the relevant module.
4199 srfi-0 ;; cond-expand itself
4200 srfi-4 ;; homogeneous numeric vectors
4201 srfi-6 ;; string ports
4202 srfi-13 ;; string library
4203 srfi-14 ;; character sets
4204 srfi-23 ;; `error` procedure
4205 srfi-39 ;; parameterize
4206 srfi-55 ;; require-extension
4207 srfi-61 ;; general cond clause
4208 srfi-105 ;; curly infix expressions
4211 ;; This table maps module public interfaces to the list of features.
4213 (define %cond-expand-table (make-hash-table 31))
4215 ;; Add one or more features to the `cond-expand' feature list of the
4218 (define (cond-expand-provide module features)
4219 (let ((mod (module-public-interface module)))
4221 (hashq-set! %cond-expand-table mod
4222 (append (hashq-ref %cond-expand-table mod '())
4225 (define-syntax cond-expand
4227 (define (module-has-feature? mod sym)
4228 (or-map (lambda (mod)
4229 (memq sym (hashq-ref %cond-expand-table mod '())))
4232 (define (condition-matches? condition)
4233 (syntax-case condition (and or not)
4235 (and-map condition-matches? #'(c ...)))
4237 (or-map condition-matches? #'(c ...)))
4239 (if (condition-matches? #'c) #f #t))
4242 (let ((sym (syntax->datum #'c)))
4243 (if (memq sym %cond-expand-features)
4245 (module-has-feature? (current-module) sym))))))
4247 (define (match clauses alternate)
4248 (syntax-case clauses ()
4249 (((condition form ...) . rest)
4250 (if (condition-matches? #'condition)
4252 (match #'rest alternate)))
4255 (syntax-case x (else)
4256 ((_ clause ... (else form ...))
4257 (match #'(clause ...)
4259 #'(begin form ...))))
4261 (match #'(clause ...)
4263 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
4265 ;; This procedure gets called from the startup code with a list of
4266 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
4268 (define (use-srfis srfis)
4269 (process-use-modules
4271 (list (list 'srfi (string->symbol
4272 (string-append "srfi-" (number->string num))))))
4277 ;;; srfi-55: require-extension
4280 (define-syntax require-extension
4282 (syntax-case x (srfi)
4284 (and-map integer? (syntax->datum #'(n ...)))
4288 (datum->syntax x (symbol-append 'srfi- n)))
4290 (map number->string (syntax->datum #'(n ...)))))))
4291 #'(use-modules (srfi srfi-n) ...)))
4293 (identifier? #'type)
4294 (syntax-violation 'require-extension "Not a recognized extension type"
4298 ;;; Defining transparently inlinable procedures
4301 (define-syntax define-inlinable
4302 ;; Define a macro and a procedure such that direct calls are inlined, via
4303 ;; the macro expansion, whereas references in non-call contexts refer to
4304 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
4306 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
4308 (define prefix (string->symbol "% "))
4309 (define (make-procedure-name name)
4311 (symbol-append prefix (syntax->datum name)
4315 ((_ (name formals ...) body ...)
4316 (identifier? #'name)
4317 (with-syntax ((proc-name (make-procedure-name #'name))
4318 ((args ...) (generate-temporaries #'(formals ...))))
4320 (define (proc-name formals ...)
4321 (syntax-parameterize ((name (identifier-syntax proc-name)))
4323 (define-syntax-parameter name
4327 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
4328 (lambda (formals ...)
4333 #'proc-name))))))))))
4337 (define using-readline?
4338 (let ((using-readline? (make-fluid)))
4339 (make-procedure-with-setter
4340 (lambda () (fluid-ref using-readline?))
4341 (lambda (v) (fluid-set! using-readline? v)))))
4345 ;;; {Deprecated stuff}
4349 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
4353 ;;; SRFI-4 in the default environment. FIXME: we should figure out how
4354 ;;; to deprecate this.
4358 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
4362 ;;; A few identifiers that need to be defined in this file are really
4363 ;;; internal implementation details. We shove them off into internal
4364 ;;; modules, removing them from the (guile) module.
4367 (define-module (system syntax))
4370 (define (steal-bindings! from to ids)
4373 (let ((v (module-local-variable from sym)))
4374 (module-remove! from sym)
4375 (module-add! to sym v)))
4377 (module-export! to ids))
4379 (steal-bindings! the-root-module (resolve-module '(system syntax))
4380 '(syntax-local-binding
4382 syntax-locally-bound-identifiers
4383 syntax-session-id)))
4388 ;;; Place the user in the guile-user module.
4391 ;; Set filename to #f to prevent reload.
4392 (define-module (guile-user)
4393 #:autoload (system base compile) (compile compile-file)
4396 ;; Remain in the `(guile)' module at compilation-time so that the
4397 ;; `-Wunused-toplevel' warning works as expected.
4398 (eval-when (compile) (set-current-module the-root-module))
4400 ;;; boot-9.scm ends here