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 (@prompt tag (thunk) handler))
66 (define (abort-to-prompt tag . args)
67 (abort-to-prompt* tag args))
70 ;; Define catch and with-throw-handler, using some common helper routines and a
71 ;; shared fluid. Hide the helpers in a lexical contour.
73 (define with-throw-handler #f)
75 (define (default-exception-handler k . args)
79 ((not (pair? args)) 0)
80 ((integer? (car args)) (car args))
84 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
87 (define %running-exception-handlers (make-fluid '()))
88 (define %exception-handler (make-fluid default-exception-handler))
90 (define (default-throw-handler prompt-tag catch-k)
91 (let ((prev (fluid-ref %exception-handler)))
92 (lambda (thrown-k . args)
93 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
94 (apply abort-to-prompt prompt-tag thrown-k args)
95 (apply prev thrown-k args)))))
97 (define (custom-throw-handler prompt-tag catch-k pre)
98 (let ((prev (fluid-ref %exception-handler)))
99 (lambda (thrown-k . args)
100 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
101 (let ((running (fluid-ref %running-exception-handlers)))
102 (with-fluids ((%running-exception-handlers (cons pre running)))
103 (if (not (memq pre running))
104 (apply pre thrown-k args))
107 (apply abort-to-prompt prompt-tag thrown-k args)
108 (apply prev thrown-k args))))
109 (apply prev thrown-k args)))))
112 (lambda* (k thunk handler #:optional pre-unwind-handler)
113 "Invoke @var{thunk} in the dynamic context of @var{handler} for
114 exceptions matching @var{key}. If thunk throws to the symbol
115 @var{key}, then @var{handler} is invoked this way:
117 (handler key args ...)
120 @var{key} is a symbol or @code{#t}.
122 @var{thunk} takes no arguments. If @var{thunk} returns
123 normally, that is the return value of @code{catch}.
125 Handler is invoked outside the scope of its own @code{catch}.
126 If @var{handler} again throws to the same key, a new handler
127 from further up the call chain is invoked.
129 If the key is @code{#t}, then a throw to @emph{any} symbol will
130 match this call to @code{catch}.
132 If a @var{pre-unwind-handler} is given and @var{thunk} throws
133 an exception that matches @var{key}, Guile calls the
134 @var{pre-unwind-handler} before unwinding the dynamic state and
135 invoking the main @var{handler}. @var{pre-unwind-handler} should
136 be a procedure with the same signature as @var{handler}, that
137 is @code{(lambda (key . args))}. It is typically used to save
138 the stack at the point where the exception occurred, but can also
139 query other parts of the dynamic state at that point, such as
142 A @var{pre-unwind-handler} can exit either normally or non-locally.
143 If it exits normally, Guile unwinds the stack and dynamic context
144 and then calls the normal (third argument) handler. If it exits
145 non-locally, that exit determines the continuation."
146 (if (not (or (symbol? k) (eqv? k #t)))
147 (scm-error 'wrong-type-arg "catch"
148 "Wrong type argument in position ~a: ~a"
149 (list 1 k) (list k)))
150 (let ((tag (make-prompt-tag "catch")))
156 (if pre-unwind-handler
157 (custom-throw-handler tag k pre-unwind-handler)
158 (default-throw-handler tag k))))
160 (lambda (cont k . args)
161 (apply handler k args))))))
163 (set! with-throw-handler
164 (lambda (k thunk pre-unwind-handler)
165 "Add @var{handler} to the dynamic context as a throw handler
166 for key @var{k}, then invoke @var{thunk}."
167 (if (not (or (symbol? k) (eqv? k #t)))
168 (scm-error 'wrong-type-arg "with-throw-handler"
169 "Wrong type argument in position ~a: ~a"
170 (list 1 k) (list k)))
171 (with-fluids ((%exception-handler
172 (custom-throw-handler #f k pre-unwind-handler)))
177 "Invoke the catch form matching @var{key}, passing @var{args} to the
180 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
182 If there is no handler at all, Guile prints an error and then exits."
183 (if (not (symbol? key))
184 ((fluid-ref %exception-handler) 'wrong-type-arg "throw"
185 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
186 (apply (fluid-ref %exception-handler) key args)))))
191 ;;; {Language primitives}
194 ;; These are are the procedural wrappers around the primitives of
195 ;; Guile's language: @apply, @call-with-current-continuation, etc.
197 ;; Usually, a call to a primitive is compiled specially. The compiler
198 ;; knows about all these kinds of expressions. But the primitives may
199 ;; be referenced not only as operators, but as values as well. These
200 ;; stub procedures are the "values" of apply, dynamic-wind, and other
203 (define (apply fun . args)
204 (@apply fun (apply:nconc2last args)))
205 (define (call-with-current-continuation proc)
206 (@call-with-current-continuation proc))
207 (define (call-with-values producer consumer)
208 (@call-with-values producer consumer))
209 (define (dynamic-wind in thunk out)
210 "All three arguments must be 0-argument procedures.
211 Guard @var{in} is called, then @var{thunk}, then
214 If, any time during the execution of @var{thunk}, the
215 continuation of the @code{dynamic_wind} expression is escaped
216 non-locally, @var{out} is called. If the continuation of
217 the dynamic-wind is re-entered, @var{in} is called. Thus
218 @var{in} and @var{out} may be called any number of
221 (define x 'normal-binding)
224 (call-with-current-continuation
230 (lambda () (set! x 'special-binding))
234 (lambda () (display x) (newline)
235 (call-with-current-continuation escape)
236 (display x) (newline)
241 (lambda () (set! x old-x)))))))
248 @result{} normal-binding
253 @result{} a-cont ;; the value of the (define a-cont...)
255 @result{} normal-binding
257 @result{} special-binding
259 (@dynamic-wind in (thunk) out))
263 ;;; {Low-Level Port Code}
266 ;; These are used to request the proper mode to open files in.
268 (define OPEN_READ "r")
269 (define OPEN_WRITE "w")
270 (define OPEN_BOTH "r+")
272 (define *null-device* "/dev/null")
274 ;; NOTE: Later in this file, this is redefined to support keywords
275 (define (open-input-file str)
276 "Takes a string naming an existing file and returns an input port
277 capable of delivering characters from the file. If the file
278 cannot be opened, an error is signalled."
279 (open-file str OPEN_READ))
281 ;; NOTE: Later in this file, this is redefined to support keywords
282 (define (open-output-file str)
283 "Takes a string naming an output file to be created and returns an
284 output port capable of writing characters to a new file by that
285 name. If the file cannot be opened, an error is signalled. If a
286 file with the given name already exists, the effect is unspecified."
287 (open-file str OPEN_WRITE))
289 (define (open-io-file str)
290 "Open file with name STR for both input and output."
291 (open-file str OPEN_BOTH))
295 ;;; {Simple Debugging Tools}
298 ;; peek takes any number of arguments, writes them to the
299 ;; current ouput port, and returns the last argument.
300 ;; It is handy to wrap around an expression to look at
301 ;; a value each time is evaluated, e.g.:
303 ;; (+ 10 (troublesome-fn))
304 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
307 (define (peek . stuff)
312 (car (last-pair stuff)))
316 ;; Temporary definition; replaced later.
317 (define current-warning-port current-error-port)
319 (define (warn . stuff)
320 (newline (current-warning-port))
321 (display ";;; WARNING " (current-warning-port))
322 (display stuff (current-warning-port))
323 (newline (current-warning-port))
324 (car (last-pair stuff)))
331 (define (provide sym)
332 (if (not (memq sym *features*))
333 (set! *features* (cons sym *features*))))
335 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
336 ;; provided? also checks to see if the module is available. We should do that
339 (define (provided? feature)
340 (and (memq feature *features*) #t))
347 (define (make-struct/no-tail vtable . args)
348 (apply make-struct vtable 0 args))
352 ;;; Boot versions of `map' and `for-each', enough to get the expander
361 (cons (f (car l)) (map1 (cdr l))))))
363 (let map2 ((l1 l1) (l2 l2))
366 (cons (f (car l1) (car l2))
367 (map2 (cdr l1) (cdr l2))))))
369 (let lp ((l1 l1) (rest rest))
372 (cons (apply f (car l1) (map car rest))
373 (lp (cdr l1) (map cdr rest))))))))
378 (let for-each1 ((l l))
382 (for-each1 (cdr l))))))
384 (let for-each2 ((l1 l1) (l2 l2))
387 (f (car l1) (car l2))
388 (for-each2 (cdr l1) (cdr l2))))))
390 (let lp ((l1 l1) (rest rest))
393 (apply f (car l1) (map car rest))
394 (lp (cdr l1) (map cdr rest))))))))
396 ;; Temporary definition used in the include-from-path expansion;
399 (define (absolute-file-name? file-name)
402 ;;; {and-map and or-map}
404 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
405 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
410 ;; Apply f to successive elements of l until exhaustion or f returns #f.
411 ;; If returning early, return #f. Otherwise, return the last value returned
412 ;; by f. If f has never been called because l is empty, return #t.
414 (define (and-map f lst)
415 (let loop ((result #t)
420 (loop (f (car l)) (cdr l))))))
424 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
425 ;; If returning early, return the return value of f.
427 (define (or-map f lst)
428 (let loop ((result #f)
432 (loop (f (car l)) (cdr l))))))
436 ;; let format alias simple-format until the more complete version is loaded
438 (define format simple-format)
440 ;; this is scheme wrapping the C code so the final pred call is a tail call,
443 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
444 (if (and (procedure? char_pred)
446 (<= end (string-length s))) ;; let c-code handle range error
447 (or (string-any-c-code char_pred s start (1- end))
448 (char_pred (string-ref s (1- end))))
449 (string-any-c-code char_pred s start end))))
451 ;; this is scheme wrapping the C code so the final pred call is a tail call,
454 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
455 (if (and (procedure? char_pred)
457 (<= end (string-length s))) ;; let c-code handle range error
458 (and (string-every-c-code char_pred s start (1- end))
459 (char_pred (string-ref s (1- end))))
460 (string-every-c-code char_pred s start end))))
462 ;; A variant of string-fill! that we keep for compatability
464 (define (substring-fill! str start end fill)
465 (string-fill! str fill start end))
469 ;; Define a minimal stub of the module API for psyntax, before modules
471 (define (module-name x)
473 (define (module-add! module sym var)
474 (hashq-set! (%get-pre-modules-obarray) sym var))
475 (define (module-define! module sym val)
476 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
478 (variable-set! v val)
479 (module-add! (current-module) sym (make-variable val)))))
480 (define (module-ref module sym)
481 (let ((v (module-variable module sym)))
482 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
483 (define (resolve-module . args)
486 ;; API provided by psyntax
487 (define syntax-violation #f)
488 (define datum->syntax #f)
489 (define syntax->datum #f)
490 (define syntax-source #f)
491 (define identifier? #f)
492 (define generate-temporaries #f)
493 (define bound-identifier=? #f)
494 (define free-identifier=? #f)
496 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
497 ;; expanded macros, to dispatch an input against a set of patterns.
498 (define $sc-dispatch #f)
501 (primitive-load-path "ice-9/psyntax-pp")
502 ;; The binding for `macroexpand' has now been overridden, making psyntax the
509 ((_ x y ...) (if x (and y ...) #f))))
515 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
517 (include-from-path "ice-9/quasisyntax")
519 (define-syntax-rule (when test stmt stmt* ...)
520 (if test (begin stmt stmt* ...)))
522 (define-syntax-rule (unless test stmt stmt* ...)
523 (if (not test) (begin stmt stmt* ...)))
527 (define (fold f seed xs)
528 (let loop ((xs xs) (seed seed))
530 (loop (cdr xs) (f (car xs) seed)))))
531 (define (reverse-map f xs)
532 (fold (lambda (x seed) (cons (f x) seed))
534 (syntax-case whole-expr ()
535 ((_ clause clauses ...)
537 #,@(fold (lambda (clause-builder tail)
538 (clause-builder tail))
542 (define* (bad-clause #:optional (msg "invalid clause"))
543 (syntax-violation 'cond msg whole-expr clause))
544 (syntax-case clause (=> else)
549 (bad-clause "else must be the last clause"))))
550 ((else . _) (bad-clause))
557 ((test => receiver ...)
558 (bad-clause "wrong number of receiver expressions"))
559 ((generator guard => receiver)
561 #`((call-with-values (lambda () generator)
563 (if (apply guard vals)
564 (apply receiver vals)
566 ((generator guard => receiver ...)
567 (bad-clause "wrong number of receiver expressions"))
578 #'(clause clauses ...))))))))
582 (define (fold f seed xs)
583 (let loop ((xs xs) (seed seed))
585 (loop (cdr xs) (f (car xs) seed)))))
586 (define (fold2 f a b xs)
587 (let loop ((xs xs) (a a) (b b))
588 (if (null? xs) (values a b)
590 (lambda () (f (car xs) a b))
592 (loop (cdr xs) a b))))))
593 (define (reverse-map-with-seed f seed xs)
594 (fold2 (lambda (x ys seed)
596 (lambda () (f x seed))
598 (values (cons y ys) seed))))
600 (syntax-case whole-expr ()
601 ((_ expr clause clauses ...)
602 (with-syntax ((key #'key))
605 (lambda (clause-builder tail)
606 (clause-builder tail))
608 (reverse-map-with-seed
609 (lambda (clause seen)
610 (define* (bad-clause #:optional (msg "invalid clause"))
611 (syntax-violation 'case msg whole-expr clause))
612 (syntax-case clause ()
616 (syntax-case #'rest (=>)
617 ((=> receiver) #'(receiver key))
620 "wrong number of receiver expressions"))
621 ((e e* ...) #'(begin e e* ...))
623 (syntax-case #'test (else)
628 (define (warn-datum type)
629 ((@ (system base message)
632 (append (source-properties datum)
634 (syntax->datum #'test)))
636 (syntax->datum clause)
637 (syntax->datum whole-expr)))
638 (when (memv datum seen)
639 (warn-datum 'duplicate-case-datum))
640 (when (or (pair? datum) (array? datum))
641 (warn-datum 'bad-case-datum))
644 (map syntax->datum #'(datums ...)))))
645 (values (lambda (tail)
646 #`((if (memv key '(datums ...))
650 (else (values (lambda (tail)
654 "else must be the last clause")))
658 '() #'(clause clauses ...)))))))))
662 ((do ((var init step ...) ...)
675 (loop (do "step" var step ...)
683 (define-syntax-rule (delay exp)
684 (make-promise (lambda () exp)))
686 (define-syntax current-source-location
690 (with-syntax ((s (datum->syntax x (syntax-source x))))
693 ;; We provide this accessor out of convenience. current-line and
694 ;; current-column aren't so interesting, because they distort what they
695 ;; are measuring; better to use syntax-source from a macro.
697 (define-syntax current-filename
699 "A macro that expands to the current filename: the filename that
700 the (current-filename) form appears in. Expands to #f if this
701 information is unavailable."
703 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
705 (define-syntax-rule (define-once sym val)
707 (if (module-locally-bound? (current-module) 'sym) sym val)))
709 ;;; The real versions of `map' and `for-each', with cycle detection, and
710 ;;; that use reverse! instead of recursion in the case of `map'.
715 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
718 (if (eq? tortoise hare)
719 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
721 (map1 (cdr hare) (cdr tortoise) #f
722 (cons (f (car hare)) out)))
723 (map1 (cdr hare) tortoise #t
724 (cons (f (car hare)) out)))
727 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
731 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
736 (scm-error 'wrong-type-arg "map"
738 "List of wrong length: ~S"
742 (map2 (cdr h1) (cdr h2) t1 t2 #t
743 (cons (f (car h1) (car h2)) out)))
745 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
748 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
751 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
752 (cons (f (car h1) (car h2)) out)))))
754 ((and (null? h1) (null? h2))
758 (scm-error 'wrong-type-arg "map"
760 "List of wrong length: ~S"
764 (scm-error 'wrong-type-arg "map"
769 (let ((len (length l1)))
770 (let mapn ((rest rest))
772 (if (= (length (car rest)) len)
774 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
775 (list (car rest)) #f)))))
776 (let mapn ((l1 l1) (rest rest) (out '()))
779 (mapn (cdr l1) (map cdr rest)
780 (cons (apply f (car l1) (map car rest)) out)))))))
782 (define map-in-order map)
787 (let for-each1 ((hare l) (tortoise l) (move? #f))
790 (if (eq? tortoise hare)
791 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
795 (for-each1 (cdr hare) (cdr tortoise) #f)))
798 (for-each1 (cdr hare) tortoise #t)))
800 (if (not (null? hare))
801 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
805 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
807 ((and (pair? h1) (pair? h2))
810 (f (car h1) (car h2))
811 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
813 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
816 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
819 (f (car h1) (car h2))
820 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
823 (or (null? h2) (pair? h2))
824 (and (pair? h1) (null? h2)))
828 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
831 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
835 (let ((len (length l1)))
836 (let for-eachn ((rest rest))
838 (if (= (length (car rest)) len)
839 (for-eachn (cdr rest))
840 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
841 (list (car rest)) #f)))))
843 (let for-eachn ((l1 l1) (rest rest))
846 (apply f (car l1) (map car rest))
847 (for-eachn (cdr l1) (map cdr rest))))))))
853 ;;; Extensible exception printing.
856 (define set-exception-printer! #f)
857 ;; There is already a definition of print-exception from backtrace.c
858 ;; that we will override.
860 (let ((exception-printers '()))
861 (define (print-location frame port)
862 (let ((source (and=> frame frame-source)))
863 ;; source := (addr . (filename . (line . column)))
865 (let ((filename (or (cadr source) "<unnamed port>"))
866 (line (caddr source))
867 (col (cdddr source)))
868 (format port "~a:~a:~a: " filename (1+ line) col))
869 (format port "ERROR: "))))
871 (set! set-exception-printer!
873 (set! exception-printers (acons key proc exception-printers))))
875 (set! print-exception
876 (lambda (port frame key args)
877 (define (default-printer)
878 (format port "Throw to key `~a' with args `~s'." key args))
881 (let ((proc (frame-procedure frame)))
882 (print-location frame port)
883 (format port "In procedure ~a:\n"
884 (or (false-if-exception (procedure-name proc))
887 (print-location frame port)
890 (let ((printer (assq-ref exception-printers key)))
892 (printer port key args default-printer)
895 (format port "Error while printing exception.")))
897 (force-output port))))
900 ;;; Printers for those keys thrown by Guile.
903 (define (scm-error-printer port key args default-printer)
904 ;; Abuse case-lambda as a pattern matcher, given that we don't have
905 ;; ice-9 match at this point.
907 ((subr msg args . rest)
909 (format port "In procedure ~a: " subr))
910 (apply format port msg (or args '())))
911 (_ (default-printer)))
914 (define (syntax-error-printer port key args default-printer)
916 ((who what where form subform . extra)
917 (format port "Syntax error:\n")
919 (let ((file (or (assq-ref where 'filename) "unknown file"))
920 (line (and=> (assq-ref where 'line) 1+))
921 (col (assq-ref where 'column)))
922 (format port "~a:~a:~a: " file line col))
923 (format port "unknown location: "))
925 (format port "~a: " who))
926 (format port "~a" what)
928 (format port " in subform ~s of ~s" subform form)
930 (format port " in form ~s" form))))
931 (_ (default-printer)))
934 (define (getaddrinfo-error-printer port key args default-printer)
935 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
937 (set-exception-printer! 'goops-error scm-error-printer)
938 (set-exception-printer! 'host-not-found scm-error-printer)
939 (set-exception-printer! 'keyword-argument-error scm-error-printer)
940 (set-exception-printer! 'misc-error scm-error-printer)
941 (set-exception-printer! 'no-data scm-error-printer)
942 (set-exception-printer! 'no-recovery scm-error-printer)
943 (set-exception-printer! 'null-pointer-error scm-error-printer)
944 (set-exception-printer! 'out-of-range scm-error-printer)
945 (set-exception-printer! 'program-error scm-error-printer)
946 (set-exception-printer! 'read-error scm-error-printer)
947 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
948 (set-exception-printer! 'signal scm-error-printer)
949 (set-exception-printer! 'stack-overflow scm-error-printer)
950 (set-exception-printer! 'system-error scm-error-printer)
951 (set-exception-printer! 'try-again scm-error-printer)
952 (set-exception-printer! 'unbound-variable scm-error-printer)
953 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
954 (set-exception-printer! 'wrong-type-arg scm-error-printer)
956 (set-exception-printer! 'syntax-error syntax-error-printer)
958 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
966 (define-syntax define-macro
970 ((_ (macro . args) doc body1 body ...)
971 (string? (syntax->datum #'doc))
972 #'(define-macro macro doc (lambda args body1 body ...)))
973 ((_ (macro . args) body ...)
974 #'(define-macro macro #f (lambda args body ...)))
975 ((_ macro transformer)
976 #'(define-macro macro #f transformer))
977 ((_ macro doc transformer)
978 (or (string? (syntax->datum #'doc))
979 (not (syntax->datum #'doc)))
980 #'(define-syntax macro
983 #((macro-type . defmacro)
984 (defmacro-args args))
987 (let ((v (syntax->datum #'args)))
988 (datum->syntax y (apply transformer v)))))))))))
990 (define-syntax defmacro
992 "Define a defmacro, with the old lispy defun syntax."
994 ((_ macro args doc body1 body ...)
995 (string? (syntax->datum #'doc))
996 #'(define-macro macro doc (lambda args body1 body ...)))
997 ((_ macro args body ...)
998 #'(define-macro macro #f (lambda args body ...))))))
1007 (define-syntax begin-deprecated
1011 (if (include-deprecated-features)
1012 #'(begin form form* ...)
1017 ;;; {Trivial Functions}
1020 (define (identity x) x)
1022 (define (compose proc . rest)
1023 "Compose PROC with the procedures in REST, such that the last one in
1024 REST is applied first and PROC last, and return the resulting procedure.
1025 The given procedures must have compatible arity."
1028 (let ((g (apply compose rest)))
1030 (call-with-values (lambda () (apply g args)) proc)))))
1032 (define (negate proc)
1033 "Return a procedure with the same arity as PROC that returns the `not'
1036 (not (apply proc args))))
1038 (define (const value)
1039 "Return a procedure that accepts any number of arguments and returns
1044 (define (and=> value procedure)
1045 "When VALUE is #f, return #f. Otherwise, return (PROC VALUE)."
1046 (and value (procedure value)))
1048 (define call/cc call-with-current-continuation)
1050 (define-syntax false-if-exception
1052 ((false-if-exception expr)
1056 ((false-if-exception expr #:warning template arg ...)
1059 (lambda (key . args)
1060 (for-each (lambda (s)
1061 (if (not (string-null? s))
1062 (format (current-warning-port) ";;; ~a\n" s)))
1064 (call-with-output-string
1066 (format port template arg ...)
1067 (print-exception port #f key args)))
1073 ;;; {General Properties}
1076 ;; Properties are a lispy way to associate random info with random objects.
1077 ;; Traditionally properties are implemented as an alist or a plist actually
1078 ;; pertaining to the object in question.
1080 ;; These "object properties" have the advantage that they can be associated with
1081 ;; any object, even if the object has no plist. Object properties are good when
1082 ;; you are extending pre-existing objects in unexpected ways. They also present
1083 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
1084 ;; type that always has properties, it's often still best to store those
1085 ;; properties within the object itself.
1087 (define (make-object-property)
1088 ;; Weak tables are thread-safe.
1089 (let ((prop (make-weak-key-hash-table)))
1090 (make-procedure-with-setter
1091 (lambda (obj) (hashq-ref prop obj))
1092 (lambda (obj val) (hashq-set! prop obj val)))))
1097 ;;; {Symbol Properties}
1100 ;;; Symbol properties are something you see in old Lisp code. In most current
1101 ;;; Guile code, symbols are not used as a data structure -- they are used as
1102 ;;; keys into other data structures.
1104 (define (symbol-property sym prop)
1105 (let ((pair (assoc prop (symbol-pref sym))))
1106 (and pair (cdr pair))))
1108 (define (set-symbol-property! sym prop val)
1109 (let ((pair (assoc prop (symbol-pref sym))))
1112 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
1114 (define (symbol-property-remove! sym prop)
1115 (let ((pair (assoc prop (symbol-pref sym))))
1117 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
1124 (define (array-shape a)
1125 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1126 (array-dimensions a)))
1133 ;;; It's much better if you can use lambda* / define*, of course.
1135 (define (kw-arg-ref args kw)
1136 (let ((rem (member kw args)))
1137 (and rem (pair? (cdr rem)) (cadr rem))))
1144 (define (struct-layout s)
1145 (struct-ref (struct-vtable s) vtable-index-layout))
1152 ;; Printing records: by default, records are printed as
1154 ;; #<type-name field1: val1 field2: val2 ...>
1156 ;; You can change that by giving a custom printing function to
1157 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1158 ;; will be called like
1160 ;; (<printer> object port)
1162 ;; It should print OBJECT to PORT.
1164 (define (inherit-print-state old-port new-port)
1165 (if (get-print-state old-port)
1166 (port-with-print-state new-port (get-print-state old-port))
1169 ;; 0: type-name, 1: fields, 2: constructor
1170 (define record-type-vtable
1171 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1173 (display "#<record-type " p)
1174 (display (record-type-name s) p)
1176 (set-struct-vtable-name! s 'record-type)
1179 (define (record-type? obj)
1180 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1182 (define* (make-record-type type-name fields #:optional printer)
1183 ;; Pre-generate constructors for nfields < 20.
1184 (define-syntax make-constructor
1186 (define *max-static-argument-count* 20)
1187 (define (make-formals n)
1190 (cons (datum->syntax
1193 (string (integer->char (+ (char->integer #\a) i)))))
1197 ((_ rtd exp) (not (identifier? #'exp))
1199 (make-constructor rtd n)))
1203 (if (< n *max-static-argument-count*)
1204 (cons (with-syntax (((formal ...) (make-formals n))
1207 (lambda (formal ...)
1208 (make-struct rtd 0 formal ...))))
1213 (if (= (length args) nfields)
1214 (apply make-struct rtd 0 args)
1215 (scm-error 'wrong-number-of-args
1216 (format #f "make-~a" type-name)
1217 "Wrong number of arguments" '() #f)))))))))
1219 (define (default-record-printer s p)
1221 (display (record-type-name (record-type-descriptor s)) p)
1222 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1225 ((not (null? fields))
1227 (display (car fields) p)
1229 (display (struct-ref s off) p)
1230 (loop (cdr fields) (+ 1 off)))))
1233 (let ((rtd (make-struct record-type-vtable 0
1235 (apply string-append
1236 (map (lambda (f) "pw") fields)))
1237 (or printer default-record-printer)
1239 (copy-tree fields))))
1240 (struct-set! rtd (+ vtable-offset-user 2)
1241 (make-constructor rtd (length fields)))
1242 ;; Temporary solution: Associate a name to the record type descriptor
1243 ;; so that the object system can create a wrapper class for it.
1244 (set-struct-vtable-name! rtd (if (symbol? type-name)
1246 (string->symbol type-name)))
1249 (define (record-type-name obj)
1250 (if (record-type? obj)
1251 (struct-ref obj vtable-offset-user)
1252 (error 'not-a-record-type obj)))
1254 (define (record-type-fields obj)
1255 (if (record-type? obj)
1256 (struct-ref obj (+ 1 vtable-offset-user))
1257 (error 'not-a-record-type obj)))
1259 (define* (record-constructor rtd #:optional field-names)
1260 (if (not field-names)
1261 (struct-ref rtd (+ 2 vtable-offset-user))
1263 `(lambda ,field-names
1264 (make-struct ',rtd 0 ,@(map (lambda (f)
1265 (if (memq f field-names)
1268 (record-type-fields rtd)))))))
1270 (define (record-predicate rtd)
1271 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1273 (define (%record-type-error rtd obj) ;; private helper
1274 (or (eq? rtd (record-type-descriptor obj))
1275 (scm-error 'wrong-type-arg "%record-type-check"
1276 "Wrong type record (want `~S'): ~S"
1277 (list (record-type-name rtd) obj)
1280 (define (record-accessor rtd field-name)
1281 (let ((pos (list-index (record-type-fields rtd) field-name)))
1283 (error 'no-such-field field-name))
1285 (if (eq? (struct-vtable obj) rtd)
1286 (struct-ref obj pos)
1287 (%record-type-error rtd obj)))))
1289 (define (record-modifier rtd field-name)
1290 (let ((pos (list-index (record-type-fields rtd) field-name)))
1292 (error 'no-such-field field-name))
1294 (if (eq? (struct-vtable obj) rtd)
1295 (struct-set! obj pos val)
1296 (%record-type-error rtd obj)))))
1298 (define (record? obj)
1299 (and (struct? obj) (record-type? (struct-vtable obj))))
1301 (define (record-type-descriptor obj)
1304 (error 'not-a-record obj)))
1314 ;; Three fields: the procedure itself, the fluid, and the converter.
1315 (make-struct <applicable-struct-vtable> 0 'pwprpr))
1316 (set-struct-vtable-name! <parameter> '<parameter>)
1318 (define* (make-parameter init #:optional (conv (lambda (x) x)))
1319 "Make a new parameter.
1321 A parameter is a dynamically bound value, accessed through a procedure.
1322 To access the current value, apply the procedure with no arguments:
1324 (define p (make-parameter 10))
1327 To provide a new value for the parameter in a dynamic extent, use
1330 (parameterize ((p 20))
1334 The value outside of the dynamic extent of the body is unaffected. To
1335 update the current value, apply it to one argument:
1340 As you can see, the call that updates a parameter returns its previous
1343 All values for the parameter are first run through the CONV procedure,
1344 including INIT, the initial value. The default CONV procedure is the
1345 identity procedure. CONV is commonly used to ensure some set of
1346 invariants on the values that a parameter may have."
1347 (let ((fluid (make-fluid (conv init))))
1348 (make-struct <parameter> 0
1350 (() (fluid-ref fluid))
1351 ((x) (let ((prev (fluid-ref fluid)))
1352 (fluid-set! fluid (conv x))
1356 (define (parameter? x)
1357 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
1359 (define (parameter-fluid p)
1362 (scm-error 'wrong-type-arg "parameter-fluid"
1363 "Not a parameter: ~S" (list p) #f)))
1365 (define (parameter-converter p)
1368 (scm-error 'wrong-type-arg "parameter-fluid"
1369 "Not a parameter: ~S" (list p) #f)))
1371 (define-syntax parameterize
1374 ((_ ((param value) ...) body body* ...)
1375 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
1376 #'(let ((p param) ...)
1377 (if (not (parameter? p))
1378 (scm-error 'wrong-type-arg "parameterize"
1379 "Not a parameter: ~S" (list p) #f))
1381 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
1383 body body* ...)))))))
1385 (define* (fluid->parameter fluid #:optional (conv (lambda (x) x)))
1386 "Make a parameter that wraps a fluid.
1388 The value of the parameter will be the same as the value of the fluid.
1389 If the parameter is rebound in some dynamic extent, perhaps via
1390 `parameterize', the new value will be run through the optional CONV
1391 procedure, as with any parameter. Note that unlike `make-parameter',
1392 CONV is not applied to the initial value."
1393 (make-struct <parameter> 0
1395 (() (fluid-ref fluid))
1396 ((x) (let ((prev (fluid-ref fluid)))
1397 (fluid-set! fluid (conv x))
1403 ;;; Once parameters have booted, define the default prompt tag as being
1407 (set! default-prompt-tag (make-parameter (default-prompt-tag)))
1411 ;;; Current ports as parameters.
1415 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
1417 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
1421 (hashq-remove! (%get-pre-modules-obarray) 'fluid)))
1423 (port-parameterize! current-input-port %current-input-port-fluid
1424 input-port? "expected an input port")
1425 (port-parameterize! current-output-port %current-output-port-fluid
1426 output-port? "expected an output port")
1427 (port-parameterize! current-error-port %current-error-port-fluid
1428 output-port? "expected an output port"))
1435 (define current-warning-port
1436 (make-parameter (current-error-port)
1438 (if (output-port? x)
1440 (error "expected an output port" x)))))
1448 ;; The language can be a symbolic name or a <language> object from
1449 ;; (system base language).
1451 (define current-language (make-parameter 'scheme))
1456 ;;; {High-Level Port Routines}
1459 (define* (open-input-file
1460 file #:key (binary #f) (encoding #f) (guess-encoding #f))
1461 "Takes a string naming an existing file and returns an input port
1462 capable of delivering characters from the file. If the file
1463 cannot be opened, an error is signalled."
1464 (open-file file (if binary "rb" "r")
1466 #:guess-encoding guess-encoding))
1468 (define* (open-output-file file #:key (binary #f) (encoding #f))
1469 "Takes a string naming an output file to be created and returns an
1470 output port capable of writing characters to a new file by that
1471 name. If the file cannot be opened, an error is signalled. If a
1472 file with the given name already exists, the effect is unspecified."
1473 (open-file file (if binary "wb" "w")
1474 #:encoding encoding))
1476 (define* (call-with-input-file
1477 file proc #:key (binary #f) (encoding #f) (guess-encoding #f))
1478 "PROC should be a procedure of one argument, and FILE should be a
1479 string naming a file. The file must
1480 already exist. These procedures call PROC
1481 with one argument: the port obtained by opening the named file for
1482 input or output. If the file cannot be opened, an error is
1483 signalled. If the procedure returns, then the port is closed
1484 automatically and the values yielded by the procedure are returned.
1485 If the procedure does not return, then the port will not be closed
1486 automatically unless it is possible to prove that the port will
1487 never again be used for a read or write operation."
1488 (let ((p (open-input-file file
1491 #:guess-encoding guess-encoding)))
1493 (lambda () (proc p))
1495 (close-input-port p)
1496 (apply values vals)))))
1498 (define* (call-with-output-file file proc #:key (binary #f) (encoding #f))
1499 "PROC should be a procedure of one argument, and FILE should be a
1500 string naming a file. The behaviour is unspecified if the file
1501 already exists. These procedures call PROC
1502 with one argument: the port obtained by opening the named file for
1503 input or output. If the file cannot be opened, an error is
1504 signalled. If the procedure returns, then the port is closed
1505 automatically and the values yielded by the procedure are returned.
1506 If the procedure does not return, then the port will not be closed
1507 automatically unless it is possible to prove that the port will
1508 never again be used for a read or write operation."
1509 (let ((p (open-output-file file #:binary binary #:encoding encoding)))
1511 (lambda () (proc p))
1513 (close-output-port p)
1514 (apply values vals)))))
1516 (define (with-input-from-port port thunk)
1517 (parameterize ((current-input-port port))
1520 (define (with-output-to-port port thunk)
1521 (parameterize ((current-output-port port))
1524 (define (with-error-to-port port thunk)
1525 (parameterize ((current-error-port port))
1528 (define* (with-input-from-file
1529 file thunk #:key (binary #f) (encoding #f) (guess-encoding #f))
1530 "THUNK must be a procedure of no arguments, and FILE must be a
1531 string naming a file. The file must already exist. The file is opened for
1532 input, an input port connected to it is made
1533 the default value returned by `current-input-port',
1534 and the THUNK is called with no arguments.
1535 When the THUNK returns, the port is closed and the previous
1536 default is restored. Returns the values yielded by THUNK. If an
1537 escape procedure is used to escape from the continuation of these
1538 procedures, their behavior is implementation dependent."
1539 (call-with-input-file file
1540 (lambda (p) (with-input-from-port p thunk))
1543 #:guess-encoding guess-encoding))
1545 (define* (with-output-to-file file thunk #:key (binary #f) (encoding #f))
1546 "THUNK must be a procedure of no arguments, and FILE must be a
1547 string naming a file. The effect is unspecified if the file already exists.
1548 The file is opened for output, an output port connected to it is made
1549 the default value returned by `current-output-port',
1550 and the THUNK is called with no arguments.
1551 When the THUNK returns, the port is closed and the previous
1552 default is restored. Returns the values yielded by THUNK. If an
1553 escape procedure is used to escape from the continuation of these
1554 procedures, their behavior is implementation dependent."
1555 (call-with-output-file file
1556 (lambda (p) (with-output-to-port p thunk))
1558 #:encoding encoding))
1560 (define* (with-error-to-file file thunk #:key (binary #f) (encoding #f))
1561 "THUNK must be a procedure of no arguments, and FILE must be a
1562 string naming a file. The effect is unspecified if the file already exists.
1563 The file is opened for output, an output port connected to it is made
1564 the default value returned by `current-error-port',
1565 and the THUNK is called with no arguments.
1566 When the THUNK returns, the port is closed and the previous
1567 default is restored. Returns the values yielded by THUNK. If an
1568 escape procedure is used to escape from the continuation of these
1569 procedures, their behavior is implementation dependent."
1570 (call-with-output-file file
1571 (lambda (p) (with-error-to-port p thunk))
1573 #:encoding encoding))
1575 (define (call-with-input-string string proc)
1576 "Calls the one-argument procedure @var{proc} with a newly created
1577 input port from which @var{string}'s contents may be read. The value
1578 yielded by the @var{proc} is returned."
1579 (proc (open-input-string string)))
1581 (define (with-input-from-string string thunk)
1582 "THUNK must be a procedure of no arguments.
1583 The test of STRING is opened for
1584 input, an input port connected to it is made,
1585 and the THUNK is called with no arguments.
1586 When the THUNK returns, the port is closed.
1587 Returns the values yielded by THUNK. If an
1588 escape procedure is used to escape from the continuation of these
1589 procedures, their behavior is implementation dependent."
1590 (call-with-input-string string
1591 (lambda (p) (with-input-from-port p thunk))))
1593 (define (call-with-output-string proc)
1594 "Calls the one-argument procedure @var{proc} with a newly created output
1595 port. When the function returns, the string composed of the characters
1596 written into the port is returned."
1597 (let ((port (open-output-string)))
1599 (get-output-string port)))
1601 (define (with-output-to-string thunk)
1602 "Calls THUNK and returns its output as a string."
1603 (call-with-output-string
1604 (lambda (p) (with-output-to-port p thunk))))
1606 (define (with-error-to-string thunk)
1607 "Calls THUNK and returns its error output as a string."
1608 (call-with-output-string
1609 (lambda (p) (with-error-to-port p thunk))))
1611 (define the-eof-object (call-with-input-string "" (lambda (p) (read-char p))))
1618 (define (->bool x) (not (not x)))
1625 (define (symbol-append . args)
1626 (string->symbol (apply string-append (map symbol->string args))))
1628 (define (list->symbol . args)
1629 (string->symbol (apply list->string args)))
1631 (define (symbol . args)
1632 (string->symbol (apply string args)))
1639 (define (list-index l k)
1642 (and (not (null? l))
1645 (loop (+ n 1) (cdr l))))))
1649 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1650 ;; `stat' accessors.
1651 (primitive-load-path "ice-9/posix")
1653 (if (provided? 'socket)
1654 (primitive-load-path "ice-9/networking"))
1656 ;; For reference, Emacs file-exists-p uses stat in this same way.
1657 (define file-exists?
1658 (if (provided? 'posix)
1660 (->bool (stat str #f)))
1662 (let ((port (catch 'system-error (lambda () (open-input-file str))
1664 (if port (begin (close-port port) #t)
1667 (define file-is-directory?
1668 (if (provided? 'posix)
1670 (eq? (stat:type (stat str)) 'directory))
1672 (let ((port (catch 'system-error
1674 (open-input-file (string-append str "/.")))
1676 (if port (begin (close-port port) #t)
1679 (define (system-error-errno args)
1680 (if (eq? (car args) 'system-error)
1681 (car (list-ref args 4))
1686 ;;; {Error Handling}
1692 (scm-error 'misc-error #f "?" #f #f))
1694 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1695 (scm-error 'misc-error #f msg (cons message args) #f)))))
1699 ;;; {Time Structures}
1702 (define (tm:sec obj) (vector-ref obj 0))
1703 (define (tm:min obj) (vector-ref obj 1))
1704 (define (tm:hour obj) (vector-ref obj 2))
1705 (define (tm:mday obj) (vector-ref obj 3))
1706 (define (tm:mon obj) (vector-ref obj 4))
1707 (define (tm:year obj) (vector-ref obj 5))
1708 (define (tm:wday obj) (vector-ref obj 6))
1709 (define (tm:yday obj) (vector-ref obj 7))
1710 (define (tm:isdst obj) (vector-ref obj 8))
1711 (define (tm:gmtoff obj) (vector-ref obj 9))
1712 (define (tm:zone obj) (vector-ref obj 10))
1714 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1715 (define (set-tm:min obj val) (vector-set! obj 1 val))
1716 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1717 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1718 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1719 (define (set-tm:year obj val) (vector-set! obj 5 val))
1720 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1721 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1722 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1723 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1724 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1726 (define (tms:clock obj) (vector-ref obj 0))
1727 (define (tms:utime obj) (vector-ref obj 1))
1728 (define (tms:stime obj) (vector-ref obj 2))
1729 (define (tms:cutime obj) (vector-ref obj 3))
1730 (define (tms:cstime obj) (vector-ref obj 4))
1734 ;;; {File Descriptors and Ports}
1737 (define file-position ftell)
1738 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1739 (seek port offset whence))
1741 (define (move->fdes fd/port fd)
1742 (cond ((integer? fd/port)
1743 (dup->fdes fd/port fd)
1747 (primitive-move->fdes fd/port fd)
1748 (set-port-revealed! fd/port 1)
1751 (define (release-port-handle port)
1752 (let ((revealed (port-revealed port)))
1754 (set-port-revealed! port (- revealed 1)))))
1759 (fdopen (dup->fdes port/fd) mode))
1760 ((port/fd mode new-fd)
1761 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1762 (set-port-revealed! port 1)
1768 (dup->port port/fd "r"))
1770 (dup->port port/fd "r" new-fd))))
1772 (define dup->outport
1775 (dup->port port/fd "w"))
1777 (dup->port port/fd "w" new-fd))))
1782 (if (integer? port/fd)
1784 (dup->port port/fd (port-mode port/fd))))
1786 (if (integer? port/fd)
1787 (dup->fdes port/fd new-fd)
1788 (dup->port port/fd (port-mode port/fd) new-fd)))))
1790 (define (duplicate-port port modes)
1791 (dup->port port modes))
1793 (define (fdes->inport fdes)
1794 (let loop ((rest-ports (fdes->ports fdes)))
1795 (cond ((null? rest-ports)
1796 (let ((result (fdopen fdes "r")))
1797 (set-port-revealed! result 1)
1799 ((input-port? (car rest-ports))
1800 (set-port-revealed! (car rest-ports)
1801 (+ (port-revealed (car rest-ports)) 1))
1804 (loop (cdr rest-ports))))))
1806 (define (fdes->outport fdes)
1807 (let loop ((rest-ports (fdes->ports fdes)))
1808 (cond ((null? rest-ports)
1809 (let ((result (fdopen fdes "w")))
1810 (set-port-revealed! result 1)
1812 ((output-port? (car rest-ports))
1813 (set-port-revealed! (car rest-ports)
1814 (+ (port-revealed (car rest-ports)) 1))
1817 (loop (cdr rest-ports))))))
1819 (define (port->fdes port)
1820 (set-port-revealed! port (+ (port-revealed port) 1))
1823 (define (setenv name value)
1825 (putenv (string-append name "=" value))
1828 (define (unsetenv name)
1829 "Remove the entry for NAME from the environment."
1837 (let-syntax ((compile-time-case
1840 ((_ exp clauses ...)
1841 (let ((val (primitive-eval (syntax->datum #'exp))))
1842 (let next-clause ((clauses #'(clauses ...)))
1843 (syntax-case clauses (else)
1845 (syntax-violation 'compile-time-case
1846 "all clauses failed to match" stx))
1849 ((((k ...) form ...) clauses ...)
1850 (if (memv val (syntax->datum #'(k ...)))
1852 (next-clause #'(clauses ...))))))))))))
1853 ;; emacs: (put 'compile-time-case 'scheme-indent-function 1)
1854 (compile-time-case (system-file-name-convention)
1856 (define (file-name-separator? c)
1859 (define file-name-separator-string "/")
1861 (define (absolute-file-name? file-name)
1862 (string-prefix? "/" file-name)))
1865 (define (file-name-separator? c)
1869 (define file-name-separator-string "\\")
1871 (define (absolute-file-name? file-name)
1872 (define (file-name-separator-at-index? idx)
1873 (and (> (string-length file-name) idx)
1874 (file-name-separator? (string-ref file-name idx))))
1875 (define (unc-file-name?)
1876 ;; Universal Naming Convention (UNC) file-names start with \\,
1877 ;; and are always absolute. See:
1878 ;; http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
1879 (and (file-name-separator-at-index? 0)
1880 (file-name-separator-at-index? 1)))
1881 (define (has-drive-specifier?)
1882 (and (>= (string-length file-name) 2)
1883 (let ((drive (string-ref file-name 0)))
1884 (or (char<=? #\a drive #\z)
1885 (char<=? #\A drive #\Z)))
1886 (eqv? (string-ref file-name 1) #\:)))
1887 (or (unc-file-name?)
1888 (if (has-drive-specifier?)
1889 (file-name-separator-at-index? 2)
1890 (file-name-separator-at-index? 0)))))))
1892 (define (in-vicinity vicinity file)
1893 (let ((tail (let ((len (string-length vicinity)))
1896 (string-ref vicinity (- len 1))))))
1897 (string-append vicinity
1898 (if (or (not tail) (file-name-separator? tail))
1900 file-name-separator-string)
1905 ;;; {Help for scm_shell}
1907 ;;; The argument-processing code used by Guile-based shells generates
1908 ;;; Scheme code based on the argument list. This page contains help
1909 ;;; functions for the code it generates.
1912 (define (command-line) (program-arguments))
1914 ;; This is mostly for the internal use of the code generated by
1915 ;; scm_compile_shell_switches.
1917 (define (load-user-init)
1918 (let* ((home (or (getenv "HOME")
1919 (false-if-exception (passwd:dir (getpwuid (getuid))))
1920 file-name-separator-string)) ;; fallback for cygwin etc.
1921 (init-file (in-vicinity home ".guile")))
1922 (if (file-exists? init-file)
1923 (primitive-load init-file))))
1927 ;;; {The interpreter stack}
1930 ;; %stacks defined in stacks.c
1931 (define (%start-stack tag thunk)
1932 (let ((prompt-tag (make-prompt-tag "start-stack")))
1936 (with-fluids ((%stacks (acons tag prompt-tag
1937 (or (fluid-ref %stacks) '()))))
1940 (%start-stack tag (lambda () (apply k args)))))))
1942 (define-syntax-rule (start-stack tag exp)
1943 (%start-stack tag (lambda () exp)))
1947 ;;; {Loading by paths}
1950 ;;; Load a Scheme source file named NAME, searching for it in the
1951 ;;; directories listed in %load-path, and applying each of the file
1952 ;;; name extensions listed in %load-extensions.
1953 (define (load-from-path name)
1954 (start-stack 'load-stack
1955 (primitive-load-path name)))
1957 (define-syntax-rule (add-to-load-path elt)
1958 "Add ELT to Guile's load path, at compile-time and at run-time."
1959 (eval-when (compile load eval)
1960 (set! %load-path (cons elt %load-path))))
1962 (define %load-verbosely #f)
1963 (define (assert-load-verbosity v) (set! %load-verbosely v))
1965 (define (%load-announce file)
1967 (with-output-to-port (current-warning-port)
1970 (display "loading ")
1975 (set! %load-hook %load-announce)
1979 ;;; {Reader Extensions}
1981 ;;; Reader code for various "#c" forms.
1984 (define read-eval? (make-fluid #f))
1985 (read-hash-extend #\.
1987 (if (fluid-ref read-eval?)
1988 (eval (read port) (interaction-environment))
1990 "#. read expansion found and read-eval? is #f."))))
1994 ;;; {Low Level Modules}
1996 ;;; These are the low level data structures for modules.
1998 ;;; Every module object is of the type 'module-type', which is a record
1999 ;;; consisting of the following members:
2001 ;;; - eval-closure: A deprecated field, to be removed in Guile 2.2.
2003 ;;; - obarray: a hash table that maps symbols to variable objects. In this
2004 ;;; hash table, the definitions are found that are local to the module (that
2005 ;;; is, not imported from other modules). When looking up bindings in the
2006 ;;; module, this hash table is searched first.
2008 ;;; - binder: either #f or a function taking a module and a symbol argument.
2009 ;;; If it is a function it is called after the obarray has been
2010 ;;; unsuccessfully searched for a binding. It then can provide bindings
2011 ;;; that would otherwise not be found locally in the module.
2013 ;;; - uses: a list of modules from which non-local bindings can be inherited.
2014 ;;; These modules are the third place queried for bindings after the obarray
2015 ;;; has been unsuccessfully searched and the binder function did not deliver
2016 ;;; a result either.
2018 ;;; - transformer: either #f or a function taking a scheme expression as
2019 ;;; delivered by read. If it is a function, it will be called to perform
2020 ;;; syntax transformations (e. g. makro expansion) on the given scheme
2021 ;;; expression. The output of the transformer function will then be passed
2022 ;;; to Guile's internal memoizer. This means that the output must be valid
2023 ;;; scheme code. The only exception is, that the output may make use of the
2024 ;;; syntax extensions provided to identify the modules that a binding
2027 ;;; - name: the name of the module. This is used for all kinds of printing
2028 ;;; outputs. In certain places the module name also serves as a way of
2029 ;;; identification. When adding a module to the uses list of another
2030 ;;; module, it is made sure that the new uses list will not contain two
2031 ;;; modules of the same name.
2033 ;;; - kind: classification of the kind of module. The value is (currently?)
2034 ;;; only used for printing. It has no influence on how a module is treated.
2035 ;;; Currently the following values are used when setting the module kind:
2036 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
2037 ;;; is set, it defaults to 'module.
2039 ;;; - duplicates-handlers: a list of procedures that get called to make a
2040 ;;; choice between two duplicate bindings when name clashes occur. See the
2041 ;;; `duplicate-handlers' global variable below.
2043 ;;; - observers: a list of procedures that get called when the module is
2046 ;;; - weak-observers: a weak-key hash table of procedures that get called
2047 ;;; when the module is modified. See `module-observe-weak' for details.
2049 ;;; In addition, the module may (must?) contain a binding for
2050 ;;; `%module-public-interface'. This variable should be bound to a module
2051 ;;; representing the exported interface of a module. See the
2052 ;;; `module-public-interface' and `module-export!' procedures.
2054 ;;; !!! warning: The interface to lazy binder procedures is going
2055 ;;; to be changed in an incompatible way to permit all the basic
2056 ;;; module ops to be virtualized.
2058 ;;; (make-module size use-list lazy-binding-proc) => module
2059 ;;; module-{obarray,uses,binder}[|-set!]
2060 ;;; (module? obj) => [#t|#f]
2061 ;;; (module-locally-bound? module symbol) => [#t|#f]
2062 ;;; (module-bound? module symbol) => [#t|#f]
2063 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
2064 ;;; (module-symbol-interned? module symbol) => [#t|#f]
2065 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
2066 ;;; (module-variable module symbol) => [#<variable ...> | #f]
2067 ;;; (module-symbol-binding module symbol opt-value)
2068 ;;; => [ <obj> | opt-value | an error occurs ]
2069 ;;; (module-make-local-var! module symbol) => #<variable...>
2070 ;;; (module-add! module symbol var) => unspecified
2071 ;;; (module-remove! module symbol) => unspecified
2072 ;;; (module-for-each proc module) => unspecified
2073 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
2074 ;;; (set-current-module module) => unspecified
2075 ;;; (current-module) => #<module...>
2081 ;;; {Printing Modules}
2084 ;; This is how modules are printed. You can re-define it.
2085 (define (%print-module mod port)
2087 (display (or (module-kind mod) "module") port)
2089 (display (module-name mod) port)
2091 (display (number->string (object-address mod) 16) port)
2095 ;; Locally extend the syntax to allow record accessors to be defined at
2096 ;; compile-time. Cache the rtd locally to the constructor, the getters and
2097 ;; the setters, in order to allow for redefinition of the record type; not
2098 ;; relevant in the case of modules, but perhaps if we make this public, it
2101 ((define-record-type
2103 (define (make-id scope . fragments)
2104 (datum->syntax scope
2105 (apply symbol-append
2107 (if (symbol? x) x (syntax->datum x)))
2110 (define (getter rtd type-name field slot)
2111 #`(define #,(make-id rtd type-name '- field)
2113 (lambda (#,type-name)
2114 (if (eq? (struct-vtable #,type-name) rtd)
2115 (struct-ref #,type-name #,slot)
2116 (%record-type-error rtd #,type-name))))))
2118 (define (setter rtd type-name field slot)
2119 #`(define #,(make-id rtd 'set- type-name '- field '!)
2121 (lambda (#,type-name val)
2122 (if (eq? (struct-vtable #,type-name) rtd)
2123 (struct-set! #,type-name #,slot val)
2124 (%record-type-error rtd #,type-name))))))
2126 (define (accessors rtd type-name fields n exp)
2127 (syntax-case fields ()
2129 (((field #:no-accessors) field* ...) (identifier? #'field)
2130 (accessors rtd type-name #'(field* ...) (1+ n)
2132 (((field #:no-setter) field* ...) (identifier? #'field)
2133 (accessors rtd type-name #'(field* ...) (1+ n)
2135 #,(getter rtd type-name #'field n))))
2136 (((field #:no-getter) field* ...) (identifier? #'field)
2137 (accessors rtd type-name #'(field* ...) (1+ n)
2139 #,(setter rtd type-name #'field n))))
2140 ((field field* ...) (identifier? #'field)
2141 (accessors rtd type-name #'(field* ...) (1+ n)
2143 #,(getter rtd type-name #'field n)
2144 #,(setter rtd type-name #'field n))))))
2146 (define (predicate rtd type-name fields exp)
2148 rtd type-name fields 0
2151 (define (#,(make-id rtd type-name '?) obj)
2152 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
2154 (define (field-list fields)
2155 (syntax-case fields ()
2157 (((f . opts) . rest) (identifier? #'f)
2158 (cons #'f (field-list #'rest)))
2159 ((f . rest) (identifier? #'f)
2160 (cons #'f (field-list #'rest)))))
2162 (define (constructor rtd type-name fields exp)
2163 (let ((ctor (make-id rtd type-name '-constructor))
2164 (args (field-list fields)))
2165 (predicate rtd type-name fields
2170 (make-struct rtd 0 #,@args))))
2171 (struct-set! #,rtd (+ vtable-offset-user 2)
2174 (define (type type-name printer fields)
2175 (define (make-layout)
2176 (let lp ((fields fields) (slots '()))
2177 (syntax-case fields ()
2178 (() (datum->syntax #'here
2180 (apply string-append slots))))
2181 ((_ . rest) (lp #'rest (cons "pw" slots))))))
2183 (let ((rtd (make-id type-name type-name '-type)))
2184 (constructor rtd type-name fields
2187 (make-struct record-type-vtable 0
2191 '#,(field-list fields)))
2192 (set-struct-vtable-name! #,rtd '#,type-name)))))
2195 ((_ type-name printer (field ...))
2196 (type #'type-name #'printer #'(field ...)))))))
2200 ;; A module is characterized by an obarray in which local symbols
2201 ;; are interned, a list of modules, "uses", from which non-local
2202 ;; bindings can be inherited, and an optional lazy-binder which
2203 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
2204 ;; bindings that would otherwise not be found locally in the module.
2206 ;; NOTE: If you change the set of fields or their order, you also need to
2207 ;; change the constants in libguile/modules.h.
2209 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
2210 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
2211 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
2213 (define-record-type module
2214 (lambda (obj port) (%print-module obj port))
2219 (transformer #:no-getter)
2223 (import-obarray #:no-setter)
2225 (weak-observers #:no-setter)
2233 ;; make-module &opt size uses binder
2235 ;; Create a new module, perhaps with a particular size of obarray,
2236 ;; initial uses list, or binding procedure.
2238 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
2239 (if (not (integer? size))
2240 (error "Illegal size to make-module." size))
2241 (if (not (and (list? uses)
2242 (and-map module? uses)))
2243 (error "Incorrect use list." uses))
2244 (if (and binder (not (procedure? binder)))
2246 "Lazy-binder expected to be a procedure or #f." binder))
2248 (module-constructor (make-hash-table size)
2249 uses binder #f macroexpand
2253 (make-weak-key-hash-table 31) #f
2254 (make-hash-table 7) #f #f #f))
2259 ;;; {Observer protocol}
2262 (define (module-observe module proc)
2263 (set-module-observers! module (cons proc (module-observers module)))
2266 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
2267 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
2268 ;; be any Scheme object). PROC is invoked and passed MODULE any time
2269 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
2270 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
2273 ;; The two-argument version is kept for backward compatibility: when called
2274 ;; with two arguments, the observer gets unregistered when closure PROC
2275 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
2276 (hashq-set! (module-weak-observers module) observer-id proc))
2278 (define (module-unobserve token)
2279 (let ((module (car token))
2282 (hash-remove! (module-weak-observers module) id)
2283 (set-module-observers! module (delq1! id (module-observers module)))))
2286 (define module-defer-observers #f)
2287 (define module-defer-observers-mutex (make-mutex 'recursive))
2288 (define module-defer-observers-table (make-hash-table))
2290 (define (module-modified m)
2291 (if module-defer-observers
2292 (hash-set! module-defer-observers-table m #t)
2293 (module-call-observers m)))
2295 ;;; This function can be used to delay calls to observers so that they
2296 ;;; can be called once only in the face of massive updating of modules.
2298 (define (call-with-deferred-observers thunk)
2301 (lock-mutex module-defer-observers-mutex)
2302 (set! module-defer-observers #t))
2305 (set! module-defer-observers #f)
2306 (hash-for-each (lambda (m dummy)
2307 (module-call-observers m))
2308 module-defer-observers-table)
2309 (hash-clear! module-defer-observers-table)
2310 (unlock-mutex module-defer-observers-mutex))))
2312 (define (module-call-observers m)
2313 (for-each (lambda (proc) (proc m)) (module-observers m))
2315 ;; We assume that weak observers don't (un)register themselves as they are
2316 ;; called since this would preclude proper iteration over the hash table
2318 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
2322 ;;; {Module Searching in General}
2324 ;;; We sometimes want to look for properties of a symbol
2325 ;;; just within the obarray of one module. If the property
2326 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
2327 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
2330 ;;; Other times, we want to test for a symbol property in the obarray
2331 ;;; of M and, if it is not found there, try each of the modules in the
2332 ;;; uses list of M. This is the normal way of testing for some
2333 ;;; property, so we state these properties without qualification as
2334 ;;; in: ``The symbol 'fnord is interned in module M because it is
2335 ;;; interned locally in module M2 which is a member of the uses list
2339 ;; module-search fn m
2341 ;; return the first non-#f result of FN applied to M and then to
2342 ;; the modules in the uses of m, and so on recursively. If all applications
2343 ;; return #f, then so does this function.
2345 (define (module-search fn m v)
2348 (or (module-search fn (car pos) v)
2351 (loop (module-uses m))))
2354 ;;; {Is a symbol bound in a module?}
2356 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
2357 ;;; of S in M has been set to some well-defined value.
2360 ;; module-locally-bound? module symbol
2362 ;; Is a symbol bound (interned and defined) locally in a given module?
2364 (define (module-locally-bound? m v)
2365 (let ((var (module-local-variable m v)))
2367 (variable-bound? var))))
2369 ;; module-bound? module symbol
2371 ;; Is a symbol bound (interned and defined) anywhere in a given module
2374 (define (module-bound? m v)
2375 (let ((var (module-variable m v)))
2377 (variable-bound? var))))
2379 ;;; {Is a symbol interned in a module?}
2381 ;;; Symbol S in Module M is interned if S occurs in
2382 ;;; of S in M has been set to some well-defined value.
2384 ;;; It is possible to intern a symbol in a module without providing
2385 ;;; an initial binding for the corresponding variable. This is done
2387 ;;; (module-add! module symbol (make-undefined-variable))
2389 ;;; In that case, the symbol is interned in the module, but not
2390 ;;; bound there. The unbound symbol shadows any binding for that
2391 ;;; symbol that might otherwise be inherited from a member of the uses list.
2394 (define (module-obarray-get-handle ob key)
2395 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
2397 (define (module-obarray-ref ob key)
2398 ((if (symbol? key) hashq-ref hash-ref) ob key))
2400 (define (module-obarray-set! ob key val)
2401 ((if (symbol? key) hashq-set! hash-set!) ob key val))
2403 (define (module-obarray-remove! ob key)
2404 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
2406 ;; module-symbol-locally-interned? module symbol
2408 ;; is a symbol interned (not neccessarily defined) locally in a given module
2409 ;; or its uses? Interned symbols shadow inherited bindings even if
2410 ;; they are not themselves bound to a defined value.
2412 (define (module-symbol-locally-interned? m v)
2413 (not (not (module-obarray-get-handle (module-obarray m) v))))
2415 ;; module-symbol-interned? module symbol
2417 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
2418 ;; or its uses? Interned symbols shadow inherited bindings even if
2419 ;; they are not themselves bound to a defined value.
2421 (define (module-symbol-interned? m v)
2422 (module-search module-symbol-locally-interned? m v))
2425 ;;; {Mapping modules x symbols --> variables}
2428 ;; module-local-variable module symbol
2429 ;; return the local variable associated with a MODULE and SYMBOL.
2431 ;;; This function is very important. It is the only function that can
2432 ;;; return a variable from a module other than the mutators that store
2433 ;;; new variables in modules. Therefore, this function is the location
2434 ;;; of the "lazy binder" hack.
2436 ;;; If symbol is defined in MODULE, and if the definition binds symbol
2437 ;;; to a variable, return that variable object.
2439 ;;; If the symbols is not found at first, but the module has a lazy binder,
2440 ;;; then try the binder.
2442 ;;; If the symbol is not found at all, return #f.
2444 ;;; (This is now written in C, see `modules.c'.)
2447 ;;; {Mapping modules x symbols --> bindings}
2449 ;;; These are similar to the mapping to variables, except that the
2450 ;;; variable is dereferenced.
2453 ;; module-symbol-binding module symbol opt-value
2455 ;; return the binding of a variable specified by name within
2456 ;; a given module, signalling an error if the variable is unbound.
2457 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2458 ;; return OPT-VALUE.
2460 (define (module-symbol-local-binding m v . opt-val)
2461 (let ((var (module-local-variable m v)))
2462 (if (and var (variable-bound? var))
2464 (if (not (null? opt-val))
2466 (error "Locally unbound variable." v)))))
2468 ;; module-symbol-binding module symbol opt-value
2470 ;; return the binding of a variable specified by name within
2471 ;; a given module, signalling an error if the variable is unbound.
2472 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2473 ;; return OPT-VALUE.
2475 (define (module-symbol-binding m v . opt-val)
2476 (let ((var (module-variable m v)))
2477 (if (and var (variable-bound? var))
2479 (if (not (null? opt-val))
2481 (error "Unbound variable." v)))))
2486 ;;; {Adding Variables to Modules}
2489 ;; module-make-local-var! module symbol
2491 ;; ensure a variable for V in the local namespace of M.
2492 ;; If no variable was already there, then create a new and uninitialzied
2495 ;; This function is used in modules.c.
2497 (define (module-make-local-var! m v)
2498 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2501 ;; Mark as modified since this function is called when
2502 ;; the standard eval closure defines a binding
2506 ;; Create a new local variable.
2507 (let ((local-var (make-undefined-variable)))
2508 (module-add! m v local-var)
2511 ;; module-ensure-local-variable! module symbol
2513 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2514 ;; there is no binding for SYMBOL, create a new uninitialized
2515 ;; variable. Return the local variable.
2517 (define (module-ensure-local-variable! module symbol)
2518 (or (module-local-variable module symbol)
2519 (let ((var (make-undefined-variable)))
2520 (module-add! module symbol var)
2523 ;; module-add! module symbol var
2525 ;; ensure a particular variable for V in the local namespace of M.
2527 (define (module-add! m v var)
2528 (if (not (variable? var))
2529 (error "Bad variable to module-add!" var))
2530 (module-obarray-set! (module-obarray m) v var)
2531 (module-modified m))
2535 ;; make sure that a symbol is undefined in the local namespace of M.
2537 (define (module-remove! m v)
2538 (module-obarray-remove! (module-obarray m) v)
2539 (module-modified m))
2541 (define (module-clear! m)
2542 (hash-clear! (module-obarray m))
2543 (module-modified m))
2545 ;; MODULE-FOR-EACH -- exported
2547 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2549 (define (module-for-each proc module)
2550 (hash-for-each proc (module-obarray module)))
2552 (define (module-map proc module)
2553 (hash-map->list proc (module-obarray module)))
2557 ;; Modules exist in a separate namespace from values, because you generally do
2558 ;; not want the name of a submodule, which you might not even use, to collide
2559 ;; with local variables that happen to be named the same as the submodule.
2561 (define (module-ref-submodule module name)
2562 (or (hashq-ref (module-submodules module) name)
2563 (and (module-submodule-binder module)
2564 ((module-submodule-binder module) module name))))
2566 (define (module-define-submodule! module name submodule)
2567 (hashq-set! (module-submodules module) name submodule))
2571 ;;; {Module-based Loading}
2574 (define (save-module-excursion thunk)
2575 (let ((inner-module (current-module))
2577 (dynamic-wind (lambda ()
2578 (set! outer-module (current-module))
2579 (set-current-module inner-module)
2580 (set! inner-module #f))
2583 (set! inner-module (current-module))
2584 (set-current-module outer-module)
2585 (set! outer-module #f)))))
2589 ;;; {MODULE-REF -- exported}
2592 ;; Returns the value of a variable called NAME in MODULE or any of its
2593 ;; used modules. If there is no such variable, then if the optional third
2594 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2596 (define (module-ref module name . rest)
2597 (let ((variable (module-variable module name)))
2598 (if (and variable (variable-bound? variable))
2599 (variable-ref variable)
2601 (error "No variable named" name 'in module)
2602 (car rest) ; default value
2605 ;; MODULE-SET! -- exported
2607 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2608 ;; to VALUE; if there is no such variable, an error is signaled.
2610 (define (module-set! module name value)
2611 (let ((variable (module-variable module name)))
2613 (variable-set! variable value)
2614 (error "No variable named" name 'in module))))
2616 ;; MODULE-DEFINE! -- exported
2618 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2619 ;; variable, it is added first.
2621 (define (module-define! module name value)
2622 (let ((variable (module-local-variable module name)))
2625 (variable-set! variable value)
2626 (module-modified module))
2627 (let ((variable (make-variable value)))
2628 (module-add! module name variable)))))
2630 ;; MODULE-DEFINED? -- exported
2632 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2635 (define (module-defined? module name)
2636 (let ((variable (module-variable module name)))
2637 (and variable (variable-bound? variable))))
2639 ;; MODULE-USE! module interface
2641 ;; Add INTERFACE to the list of interfaces used by MODULE.
2643 (define (module-use! module interface)
2644 (if (not (or (eq? module interface)
2645 (memq interface (module-uses module))))
2647 ;; Newly used modules must be appended rather than consed, so that
2648 ;; `module-variable' traverses the use list starting from the first
2650 (set-module-uses! module (append (module-uses module)
2652 (hash-clear! (module-import-obarray module))
2653 (module-modified module))))
2655 ;; MODULE-USE-INTERFACES! module interfaces
2657 ;; Same as MODULE-USE!, but only notifies module observers after all
2658 ;; interfaces are added to the inports list.
2660 (define (module-use-interfaces! module interfaces)
2661 (let* ((cur (module-uses module))
2662 (new (let lp ((in interfaces) (out '()))
2666 (let ((iface (car in)))
2667 (if (or (memq iface cur) (memq iface out))
2669 (cons iface out))))))))
2670 (set-module-uses! module (append cur new))
2671 (hash-clear! (module-import-obarray module))
2672 (module-modified module)))
2676 ;;; {Recursive Namespaces}
2678 ;;; A hierarchical namespace emerges if we consider some module to be
2679 ;;; root, and submodules of that module to be nested namespaces.
2681 ;;; The routines here manage variable names in hierarchical namespace.
2682 ;;; Each variable name is a list of elements, looked up in successively nested
2685 ;;; (nested-ref some-root-module '(foo bar baz))
2686 ;;; => <value of a variable named baz in the submodule bar of
2687 ;;; the submodule foo of some-root-module>
2692 ;;; ;; a-root is a module
2693 ;;; ;; name is a list of symbols
2695 ;;; nested-ref a-root name
2696 ;;; nested-set! a-root name val
2697 ;;; nested-define! a-root name val
2698 ;;; nested-remove! a-root name
2700 ;;; These functions manipulate values in namespaces. For referencing the
2701 ;;; namespaces themselves, use the following:
2703 ;;; nested-ref-module a-root name
2704 ;;; nested-define-module! a-root name mod
2706 ;;; (current-module) is a natural choice for a root so for convenience there are
2709 ;;; local-ref name == nested-ref (current-module) name
2710 ;;; local-set! name val == nested-set! (current-module) name val
2711 ;;; local-define name val == nested-define! (current-module) name val
2712 ;;; local-remove name == nested-remove! (current-module) name
2713 ;;; local-ref-module name == nested-ref-module (current-module) name
2714 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2718 (define (nested-ref root names)
2721 (let loop ((cur root)
2725 (module-ref cur head #f)
2726 (let ((cur (module-ref-submodule cur head)))
2728 (loop cur (car tail) (cdr tail))))))))
2730 (define (nested-set! root names val)
2731 (let loop ((cur root)
2735 (module-set! cur head val)
2736 (let ((cur (module-ref-submodule cur head)))
2738 (error "failed to resolve module" names)
2739 (loop cur (car tail) (cdr tail)))))))
2741 (define (nested-define! root names val)
2742 (let loop ((cur root)
2746 (module-define! cur head val)
2747 (let ((cur (module-ref-submodule cur head)))
2749 (error "failed to resolve module" names)
2750 (loop cur (car tail) (cdr tail)))))))
2752 (define (nested-remove! root names)
2753 (let loop ((cur root)
2757 (module-remove! cur head)
2758 (let ((cur (module-ref-submodule cur head)))
2760 (error "failed to resolve module" names)
2761 (loop cur (car tail) (cdr tail)))))))
2764 (define (nested-ref-module root names)
2765 (let loop ((cur root)
2769 (let ((cur (module-ref-submodule cur (car names))))
2771 (loop cur (cdr names)))))))
2773 (define (nested-define-module! root names module)
2775 (error "can't redefine root module" root module)
2776 (let loop ((cur root)
2780 (module-define-submodule! cur head module)
2781 (let ((cur (or (module-ref-submodule cur head)
2782 (let ((m (make-module 31)))
2783 (set-module-kind! m 'directory)
2784 (set-module-name! m (append (module-name cur)
2786 (module-define-submodule! cur head m)
2788 (loop cur (car tail) (cdr tail)))))))
2791 (define (local-ref names)
2792 (nested-ref (current-module) names))
2794 (define (local-set! names val)
2795 (nested-set! (current-module) names val))
2797 (define (local-define names val)
2798 (nested-define! (current-module) names val))
2800 (define (local-remove names)
2801 (nested-remove! (current-module) names))
2803 (define (local-ref-module names)
2804 (nested-ref-module (current-module) names))
2806 (define (local-define-module names mod)
2807 (nested-define-module! (current-module) names mod))
2813 ;;; {The (guile) module}
2815 ;;; The standard module, which has the core Guile bindings. Also called the
2816 ;;; "root module", as it is imported by many other modules, but it is not
2817 ;;; necessarily the root of anything; and indeed, the module named '() might be
2818 ;;; better thought of as a root.
2821 ;; The root module uses the pre-modules-obarray as its obarray. This
2822 ;; special obarray accumulates all bindings that have been established
2823 ;; before the module system is fully booted.
2825 ;; (The obarray continues to be used by code that has been closed over
2826 ;; before the module system has been booted.)
2828 (define the-root-module
2829 (let ((m (make-module 0)))
2830 (set-module-obarray! m (%get-pre-modules-obarray))
2831 (set-module-name! m '(guile))
2834 ;; The root interface is a module that uses the same obarray as the
2835 ;; root module. It does not allow new definitions, tho.
2837 (define the-scm-module
2838 (let ((m (make-module 0)))
2839 (set-module-obarray! m (%get-pre-modules-obarray))
2840 (set-module-name! m '(guile))
2841 (set-module-kind! m 'interface)
2843 ;; In Guile 1.8 and earlier M was its own public interface.
2844 (set-module-public-interface! m m)
2848 (set-module-public-interface! the-root-module the-scm-module)
2852 ;; Now that we have a root module, even though modules aren't fully booted,
2853 ;; expand the definition of resolve-module.
2855 (define (resolve-module name . args)
2856 (if (equal? name '(guile))
2858 (error "unexpected module to resolve during module boot" name)))
2860 ;; Cheat. These bindings are needed by modules.c, but we don't want
2861 ;; to move their real definition here because that would be unnatural.
2863 (define define-module* #f)
2864 (define process-use-modules #f)
2865 (define module-export! #f)
2866 (define default-duplicate-binding-procedures #f)
2868 ;; This boots the module system. All bindings needed by modules.c
2869 ;; must have been defined by now.
2871 (set-current-module the-root-module)
2876 ;; Now that modules are booted, give module-name its final definition.
2879 (let ((accessor (record-accessor module-type 'name)))
2882 (let ((name (list (gensym))))
2883 ;; Name MOD and bind it in the module root so that it's visible to
2884 ;; `resolve-module'. This is important as `psyntax' stores module
2885 ;; names and relies on being able to `resolve-module' them.
2886 (set-module-name! mod name)
2887 (nested-define-module! (resolve-module '() #f) name mod)
2890 (define (make-modules-in module name)
2891 (or (nested-ref-module module name)
2892 (let ((m (make-module 31)))
2893 (set-module-kind! m 'directory)
2894 (set-module-name! m (append (module-name module) name))
2895 (nested-define-module! module name m)
2898 (define (beautify-user-module! module)
2899 (let ((interface (module-public-interface module)))
2900 (if (or (not interface)
2901 (eq? interface module))
2902 (let ((interface (make-module 31)))
2903 (set-module-name! interface (module-name module))
2904 (set-module-version! interface (module-version module))
2905 (set-module-kind! interface 'interface)
2906 (set-module-public-interface! module interface))))
2907 (if (and (not (memq the-scm-module (module-uses module)))
2908 (not (eq? module the-root-module)))
2909 ;; Import the default set of bindings (from the SCM module) in MODULE.
2910 (module-use! module the-scm-module)))
2912 (define (version-matches? version-ref target)
2913 (define (sub-versions-match? v-refs t)
2914 (define (sub-version-matches? v-ref t)
2915 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2917 ((number? v-ref) (eqv? v-ref t))
2920 ((>=) (>= t (cadr v-ref)))
2921 ((<=) (<= t (cadr v-ref)))
2922 ((and) (and-map matches? (cdr v-ref)))
2923 ((or) (or-map matches? (cdr v-ref)))
2924 ((not) (not (matches? (cadr v-ref))))
2925 (else (error "Invalid sub-version reference" v-ref))))
2926 (else (error "Invalid sub-version reference" v-ref)))))
2928 (and (not (null? t))
2929 (sub-version-matches? (car v-refs) (car t))
2930 (sub-versions-match? (cdr v-refs) (cdr t)))))
2932 (let ((matches? (lambda (v) (version-matches? v target))))
2933 (or (null? version-ref)
2934 (case (car version-ref)
2935 ((and) (and-map matches? (cdr version-ref)))
2936 ((or) (or-map matches? (cdr version-ref)))
2937 ((not) (not (matches? (cadr version-ref))))
2938 (else (sub-versions-match? version-ref target))))))
2940 (define (make-fresh-user-module)
2941 (let ((m (make-module)))
2942 (beautify-user-module! m)
2945 ;; NOTE: This binding is used in libguile/modules.c.
2947 (define resolve-module
2948 (let ((root (make-module)))
2949 (set-module-name! root '())
2950 ;; Define the-root-module as '(guile).
2951 (module-define-submodule! root 'guile the-root-module)
2953 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2954 (let ((already (nested-ref-module root name)))
2957 (or (not autoload) (module-public-interface already)))
2958 ;; A hit, a palpable hit.
2960 (not (version-matches? version (module-version already))))
2961 (error "incompatible module version already loaded" name))
2964 ;; Try to autoload the module, and recurse.
2965 (try-load-module name version)
2966 (resolve-module name #f #:ensure ensure))
2968 ;; No module found (or if one was, it had no public interface), and
2969 ;; we're not autoloading. Make an empty module if #:ensure is true.
2972 (make-modules-in root name)))))))))
2975 (define (try-load-module name version)
2976 (try-module-autoload name version))
2978 (define (reload-module m)
2979 "Revisit the source file corresponding to the module @var{m}."
2980 (let ((f (module-filename m)))
2982 (save-module-excursion
2984 ;; Re-set the initial environment, as in try-module-autoload.
2985 (set-current-module (make-fresh-user-module))
2986 (primitive-load-path f)
2988 ;; Though we could guess, we *should* know it.
2989 (error "unknown file name for module" m))))
2991 (define (purify-module! module)
2992 "Removes bindings in MODULE which are inherited from the (guile) module."
2993 (let ((use-list (module-uses module)))
2994 (if (and (pair? use-list)
2995 (eq? (car (last-pair use-list)) the-scm-module))
2996 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2998 ;; Return a module that is an interface to the module designated by
3001 ;; `resolve-interface' takes four keyword arguments:
3003 ;; #:select SELECTION
3005 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
3006 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
3007 ;; is the name in the used module and SEEN is the name in the using
3008 ;; module. Note that SEEN is also passed through RENAMER, below. The
3009 ;; default is to select all bindings. If you specify no selection but
3010 ;; a renamer, only the bindings that already exist in the used module
3011 ;; are made available in the interface. Bindings that are added later
3012 ;; are not picked up.
3016 ;; BINDINGS is a list of bindings which should not be imported.
3020 ;; PREFIX is a symbol that will be appended to each exported name.
3021 ;; The default is to not perform any renaming.
3023 ;; #:renamer RENAMER
3025 ;; RENAMER is a procedure that takes a symbol and returns its new
3026 ;; name. The default is not perform any renaming.
3028 ;; Signal "no code for module" error if module name is not resolvable
3029 ;; or its public interface is not available. Signal "no binding"
3030 ;; error if selected binding does not exist in the used module.
3032 (define* (resolve-interface name #:key
3037 (symbol-prefix-proc prefix)
3040 (let* ((module (resolve-module name #t version #:ensure #f))
3041 (public-i (and module (module-public-interface module))))
3043 (error "no code for module" name))
3044 (if (and (not select) (null? hide) (eq? renamer identity))
3046 (let ((selection (or select (module-map (lambda (sym var) sym)
3048 (custom-i (make-module 31)))
3049 (set-module-kind! custom-i 'custom-interface)
3050 (set-module-name! custom-i name)
3051 ;; XXX - should use a lazy binder so that changes to the
3052 ;; used module are picked up automatically.
3053 (for-each (lambda (bspec)
3054 (let* ((direct? (symbol? bspec))
3055 (orig (if direct? bspec (car bspec)))
3056 (seen (if direct? bspec (cdr bspec)))
3057 (var (or (module-local-variable public-i orig)
3058 (module-local-variable module orig)
3060 ;; fixme: format manually for now
3062 #f "no binding `~A' in module ~A"
3064 (if (memq orig hide)
3065 (set! hide (delq! orig hide))
3066 (module-add! custom-i
3070 ;; Check that we are not hiding bindings which don't exist
3071 (for-each (lambda (binding)
3072 (if (not (module-local-variable public-i binding))
3075 #f "no binding `~A' to hide in module ~A"
3080 (define (symbol-prefix-proc prefix)
3082 (symbol-append prefix symbol)))
3084 ;; This function is called from "modules.c". If you change it, be
3085 ;; sure to update "modules.c" as well.
3087 (define* (define-module* name
3088 #:key filename pure version (duplicates '())
3089 (imports '()) (exports '()) (replacements '())
3090 (re-exports '()) (autoloads '()) transformer)
3091 (define (list-of pred l)
3093 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
3094 (define (valid-export? x)
3095 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
3096 (define (valid-autoload? x)
3097 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
3099 (define (resolve-imports imports)
3100 (define (resolve-import import-spec)
3101 (if (list? import-spec)
3102 (apply resolve-interface import-spec)
3103 (error "unexpected use-module specification" import-spec)))
3104 (let lp ((imports imports) (out '()))
3106 ((null? imports) (reverse! out))
3109 (cons (resolve-import (car imports)) out)))
3110 (else (error "unexpected tail of imports list" imports)))))
3112 ;; We could add a #:no-check arg, set by the define-module macro, if
3113 ;; these checks are taking too much time.
3115 (let ((module (resolve-module name #f)))
3116 (beautify-user-module! module)
3118 (set-module-filename! module filename))
3120 (purify-module! module))
3123 (if (not (list-of integer? version))
3124 (error "expected list of integers for version"))
3125 (set-module-version! module version)
3126 (set-module-version! (module-public-interface module) version)))
3127 (let ((imports (resolve-imports imports)))
3128 (call-with-deferred-observers
3131 (module-use-interfaces! module imports))
3132 (if (list-of valid-export? exports)
3134 (module-export! module exports))
3135 (error "expected exports to be a list of symbols or symbol pairs"))
3136 (if (list-of valid-export? replacements)
3137 (if (pair? replacements)
3138 (module-replace! module replacements))
3139 (error "expected replacements to be a list of symbols or symbol pairs"))
3140 (if (list-of valid-export? re-exports)
3141 (if (pair? re-exports)
3142 (module-re-export! module re-exports))
3143 (error "expected re-exports to be a list of symbols or symbol pairs"))
3145 (if (not (null? autoloads))
3146 (apply module-autoload! module autoloads))
3147 ;; Wait until modules have been loaded to resolve duplicates
3149 (if (pair? duplicates)
3150 (let ((handlers (lookup-duplicates-handlers duplicates)))
3151 (set-module-duplicates-handlers! module handlers))))))
3154 (if (and (pair? transformer) (list-of symbol? transformer))
3155 (let ((iface (resolve-interface transformer))
3156 (sym (car (last-pair transformer))))
3157 (set-module-transformer! module (module-ref iface sym)))
3158 (error "expected transformer to be a module name" transformer)))
3160 (run-hook module-defined-hook module)
3163 ;; `module-defined-hook' is a hook that is run whenever a new module
3164 ;; is defined. Its members are called with one argument, the new
3166 (define module-defined-hook (make-hook 1))
3173 (define (make-autoload-interface module name bindings)
3174 (let ((b (lambda (a sym definep)
3176 (and (memq sym bindings)
3177 (let ((i (module-public-interface (resolve-module name))))
3179 (error "missing interface for module" name))
3180 (let ((autoload (memq a (module-uses module))))
3181 ;; Replace autoload-interface with actual interface if
3182 ;; that has not happened yet.
3183 (if (pair? autoload)
3184 (set-car! autoload i)))
3185 (module-local-variable i sym)))
3186 #:warning "Failed to autoload ~a in ~a:\n" sym name))))
3187 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
3188 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
3189 (make-hash-table 0) #f #f #f)))
3191 (define (module-autoload! module . args)
3192 "Have @var{module} automatically load the module named @var{name} when one
3193 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
3194 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
3195 module '(ice-9 q) '(make-q q-length))}."
3196 (let loop ((args args))
3200 (error "invalid name+binding autoload list" args))
3202 (let ((name (car args))
3203 (bindings (cadr args)))
3204 (module-use! module (make-autoload-interface module
3206 (loop (cddr args)))))))
3211 ;;; {Autoloading modules}
3214 (define autoloads-in-progress '())
3216 ;; This function is called from scm_load_scheme_module in
3217 ;; "deprecated.c". Please do not change its interface.
3219 (define* (try-module-autoload module-name #:optional version)
3220 "Try to load a module of the given name. If it is not found, return
3221 #f. Otherwise return #t. May raise an exception if a file is found,
3222 but it fails to load."
3223 (let* ((reverse-name (reverse module-name))
3224 (name (symbol->string (car reverse-name)))
3225 (dir-hint-module-name (reverse (cdr reverse-name)))
3226 (dir-hint (apply string-append
3228 (string-append (symbol->string elt)
3229 file-name-separator-string))
3230 dir-hint-module-name))))
3231 (resolve-module dir-hint-module-name #f)
3232 (and (not (autoload-done-or-in-progress? dir-hint name))
3235 (lambda () (autoload-in-progress! dir-hint name))
3237 (with-fluids ((current-reader #f))
3238 (save-module-excursion
3240 (define (call/ec proc)
3241 (let ((tag (make-prompt-tag)))
3245 (proc (lambda () (abort-to-prompt tag))))
3246 (lambda (k) (values)))))
3247 ;; The initial environment when loading a module is a fresh
3249 (set-current-module (make-fresh-user-module))
3250 ;; Here we could allow some other search strategy (other than
3251 ;; primitive-load-path), for example using versions encoded
3252 ;; into the file system -- but then we would have to figure
3253 ;; out how to locate the compiled file, do auto-compilation,
3254 ;; etc. Punt for now, and don't use versions when locating
3258 (primitive-load-path (in-vicinity dir-hint name)
3260 (set! didit #t)))))))
3261 (lambda () (set-autoloaded! dir-hint name didit)))
3266 ;;; {Dynamic linking of modules}
3269 (define autoloads-done '((guile . guile)))
3271 (define (autoload-done-or-in-progress? p m)
3272 (let ((n (cons p m)))
3273 (->bool (or (member n autoloads-done)
3274 (member n autoloads-in-progress)))))
3276 (define (autoload-done! p m)
3277 (let ((n (cons p m)))
3278 (set! autoloads-in-progress
3279 (delete! n autoloads-in-progress))
3280 (or (member n autoloads-done)
3281 (set! autoloads-done (cons n autoloads-done)))))
3283 (define (autoload-in-progress! p m)
3284 (let ((n (cons p m)))
3285 (set! autoloads-done
3286 (delete! n autoloads-done))
3287 (set! autoloads-in-progress (cons n autoloads-in-progress))))
3289 (define (set-autoloaded! p m done?)
3291 (autoload-done! p m)
3292 (let ((n (cons p m)))
3293 (set! autoloads-done (delete! n autoloads-done))
3294 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
3298 ;;; {Run-time options}
3301 (define-syntax define-option-interface
3303 ((_ (interface (options enable disable) (option-set!)))
3310 (begin (interface arg) (interface))
3313 (apply (lambda (name value documentation)
3315 (let ((len (string-length (symbol->string name))))
3323 (display documentation)
3327 (define (enable . flags)
3328 (interface (append flags (interface)))
3330 (define (disable . flags)
3331 (let ((options (interface)))
3332 (for-each (lambda (flag) (set! options (delq! flag options)))
3336 (define-syntax-rule (option-set! opt val)
3337 (eval-when (eval load compile expand)
3338 (options (append (options) (list 'opt val)))))))))
3340 (define-option-interface
3341 (debug-options-interface
3342 (debug-options debug-enable debug-disable)
3345 (define-option-interface
3346 (read-options-interface
3347 (read-options read-enable read-disable)
3350 (define-option-interface
3351 (print-options-interface
3352 (print-options print-enable print-disable)
3357 ;;; {The Unspecified Value}
3359 ;;; Currently Guile represents unspecified values via one particular value,
3360 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
3361 ;;; future if we could replace this with a return of 0 values, though.
3364 (define-syntax *unspecified*
3365 (identifier-syntax (if #f #f)))
3367 (define (unspecified? v) (eq? v *unspecified*))
3375 (define *repl-stack* (make-fluid '()))
3377 ;; Programs can call `batch-mode?' to see if they are running as part of a
3378 ;; script or if they are running interactively. REPL implementations ensure that
3379 ;; `batch-mode?' returns #f during their extent.
3381 (define (batch-mode?)
3382 (null? (fluid-ref *repl-stack*)))
3384 ;; Programs can re-enter batch mode, for example after a fork, by calling
3385 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3386 ;; to abort to the outermost prompt, and call a thunk there.
3388 (define (ensure-batch-mode!)
3389 (set! batch-mode? (lambda () #t)))
3391 (define (quit . args)
3392 (apply throw 'quit args))
3396 (define (gc-run-time)
3397 (cdr (assq 'gc-time-taken (gc-stats))))
3399 (define abort-hook (make-hook))
3400 (define before-error-hook (make-hook))
3401 (define after-error-hook (make-hook))
3402 (define before-backtrace-hook (make-hook))
3403 (define after-backtrace-hook (make-hook))
3405 (define before-read-hook (make-hook))
3406 (define after-read-hook (make-hook))
3407 (define before-eval-hook (make-hook 1))
3408 (define after-eval-hook (make-hook 1))
3409 (define before-print-hook (make-hook 1))
3410 (define after-print-hook (make-hook 1))
3412 ;;; This hook is run at the very end of an interactive session.
3414 (define exit-hook (make-hook))
3416 ;;; The default repl-reader function. We may override this if we've
3417 ;;; the readline library.
3419 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3420 (if (not (char-ready?))
3422 (display (if (string? prompt) prompt (prompt)))
3423 ;; An interesting situation. The printer resets the column to
3424 ;; 0 by printing a newline, but we then advance it by printing
3425 ;; the prompt. However the port-column of the output port
3426 ;; does not typically correspond with the actual column on the
3427 ;; screen, because the input is echoed back! Since the
3428 ;; input is line-buffered and thus ends with a newline, the
3429 ;; output will really start on column zero. So, here we zero
3430 ;; it out. See bug 9664.
3432 ;; Note that for similar reasons, the output-line will not
3433 ;; reflect the actual line on the screen. But given the
3434 ;; possibility of multiline input, the fix is not as
3435 ;; straightforward, so we don't bother.
3437 ;; Also note that the readline implementation papers over
3438 ;; these concerns, because it's readline itself printing the
3439 ;; prompt, and not Guile.
3440 (set-port-column! (current-output-port) 0)))
3442 (run-hook before-read-hook)
3443 ((or reader read) (current-input-port))))
3448 ;;; {IOTA functions: generating lists of numbers}
3452 (let loop ((count (1- n)) (result '()))
3453 (if (< count 0) result
3454 (loop (1- count) (cons count result)))))
3460 ;;; with `continue' and `break'.
3463 ;; The inliner will remove the prompts at compile-time if it finds that
3464 ;; `continue' or `break' are not used.
3466 (define-syntax while
3469 ((while cond body ...)
3470 #`(let ((break-tag (make-prompt-tag "break"))
3471 (continue-tag (make-prompt-tag "continue")))
3475 (define-syntax #,(datum->syntax #'while 'break)
3479 #'(abort-to-prompt break-tag arg (... ...)))
3482 (apply abort-to-prompt break-tag args))))))
3487 (define-syntax #,(datum->syntax #'while 'continue)
3491 #'(abort-to-prompt continue-tag))
3493 (syntax-violation 'continue "too many arguments" x))
3496 (abort-to-prompt continue-tag))))))
3497 (do () ((not cond) #f) body ...))
3498 (lambda (k) (lp)))))
3502 (apply values args)))))))))
3507 ;;; {Module System Macros}
3510 ;; Return a list of expressions that evaluate to the appropriate
3511 ;; arguments for resolve-interface according to SPEC.
3513 (eval-when (compile)
3514 (if (memq 'prefix (read-options))
3515 (error "boot-9 must be compiled with #:kw, not :kw")))
3517 (define (keyword-like-symbol->keyword sym)
3518 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3520 (define-syntax define-module
3522 (define (keyword-like? stx)
3523 (let ((dat (syntax->datum stx)))
3525 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3526 (define (->keyword sym)
3527 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3529 (define (parse-iface args)
3530 (let loop ((in args) (out '()))
3533 ;; The user wanted #:foo, but wrote :foo. Fix it.
3534 ((sym . in) (keyword-like? #'sym)
3535 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3536 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3537 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3538 ((#:renamer renamer . in)
3539 (loop #'in (cons* #',renamer #:renamer out)))
3541 (loop #'in (cons* #'val #'kw out))))))
3543 (define (parse args imp exp rex rep aut)
3544 ;; Just quote everything except #:use-module and #:use-syntax. We
3545 ;; need to know about all arguments regardless since we want to turn
3546 ;; symbols that look like keywords into real keywords, and the
3547 ;; keyword args in a define-module form are not regular
3548 ;; (i.e. no-backtrace doesn't take a value).
3549 (syntax-case args ()
3551 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3552 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3553 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3554 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3555 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3556 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3557 ;; The user wanted #:foo, but wrote :foo. Fix it.
3558 ((sym . args) (keyword-like? #'sym)
3559 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3560 imp exp rex rep aut))
3561 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3562 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3563 ((#:no-backtrace . args)
3565 (parse #'args imp exp rex rep aut))
3567 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3569 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3570 ((#:version (v ...) . args)
3571 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3572 ((#:duplicates (d ...) . args)
3573 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3574 ((#:filename f . args)
3575 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3576 ((#:use-module (name name* ...) . args)
3577 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3578 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3579 ((#:use-syntax (name name* ...) . args)
3580 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3581 #`(#:transformer '(name name* ...)
3582 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3583 ((#:use-module ((name name* ...) arg ...) . args)
3584 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3586 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3588 ((#:export (ex ...) . args)
3589 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3590 ((#:export-syntax (ex ...) . args)
3591 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3592 ((#:re-export (re ...) . args)
3593 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3594 ((#:re-export-syntax (re ...) . args)
3595 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3596 ((#:replace (r ...) . args)
3597 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3598 ((#:replace-syntax (r ...) . args)
3599 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3600 ((#:autoload name bindings . args)
3601 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3603 (syntax-violation 'define-module "unknown keyword or bad argument"
3607 ((_ (name name* ...) arg ...)
3608 (and-map symbol? (syntax->datum #'(name name* ...)))
3609 (with-syntax (((quoted-arg ...)
3610 (parse #'(arg ...) '() '() '() '() '()))
3611 ;; Ideally the filename is either a string or #f;
3612 ;; this hack is to work around a case in which
3613 ;; port-filename returns a symbol (`socket') for
3615 (filename (let ((f (assq-ref (or (syntax-source x) '())
3617 (and (string? f) f))))
3618 #'(eval-when (eval load compile expand)
3619 (let ((m (define-module* '(name name* ...)
3620 #:filename filename quoted-arg ...)))
3621 (set-current-module m)
3624 ;; The guts of the use-modules macro. Add the interfaces of the named
3625 ;; modules to the use-list of the current module, in order.
3627 ;; This function is called by "modules.c". If you change it, be sure
3628 ;; to change scm_c_use_module as well.
3630 (define (process-use-modules module-interface-args)
3631 (let ((interfaces (map (lambda (mif-args)
3632 (or (apply resolve-interface mif-args)
3633 (error "no such module" mif-args)))
3634 module-interface-args)))
3635 (call-with-deferred-observers
3637 (module-use-interfaces! (current-module) interfaces)))))
3639 (define-syntax use-modules
3641 (define (keyword-like? stx)
3642 (let ((dat (syntax->datum stx)))
3644 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3645 (define (->keyword sym)
3646 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3648 (define (quotify-iface args)
3649 (let loop ((in args) (out '()))
3652 ;; The user wanted #:foo, but wrote :foo. Fix it.
3653 ((sym . in) (keyword-like? #'sym)
3654 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3655 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3656 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3657 ((#:renamer renamer . in)
3658 (loop #'in (cons* #'renamer #:renamer out)))
3660 (loop #'in (cons* #''val #'kw out))))))
3662 (define (quotify specs)
3663 (let lp ((in specs) (out '()))
3666 (((name name* ...) . in)
3667 (and-map symbol? (syntax->datum #'(name name* ...)))
3668 (lp #'in (cons #''((name name* ...)) out)))
3669 ((((name name* ...) arg ...) . in)
3670 (and-map symbol? (syntax->datum #'(name name* ...)))
3671 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3672 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3677 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3678 #'(eval-when (eval load compile expand)
3679 (process-use-modules (list quoted-args ...))
3682 (include-from-path "ice-9/r6rs-libraries")
3684 (define-syntax-rule (define-private foo bar)
3687 (define-syntax define-public
3689 ((_ (name . args) . body)
3691 (define name (lambda args . body))
3698 (define-syntax-rule (defmacro-public name args body ...)
3700 (defmacro name args body ...)
3701 (export-syntax name)))
3703 ;; And now for the most important macro.
3704 (define-syntax-rule (λ formals body ...)
3705 (lambda formals body ...))
3708 ;; Export a local variable
3710 ;; This function is called from "modules.c". If you change it, be
3711 ;; sure to update "modules.c" as well.
3713 (define (module-export! m names)
3714 (let ((public-i (module-public-interface m)))
3715 (for-each (lambda (name)
3716 (let* ((internal-name (if (pair? name) (car name) name))
3717 (external-name (if (pair? name) (cdr name) name))
3718 (var (module-ensure-local-variable! m internal-name)))
3719 (module-add! public-i external-name var)))
3722 (define (module-replace! m names)
3723 (let ((public-i (module-public-interface m)))
3724 (for-each (lambda (name)
3725 (let* ((internal-name (if (pair? name) (car name) name))
3726 (external-name (if (pair? name) (cdr name) name))
3727 (var (module-ensure-local-variable! m internal-name)))
3728 ;; FIXME: use a bit on variables instead of object
3730 (set-object-property! var 'replace #t)
3731 (module-add! public-i external-name var)))
3734 ;; Export all local variables from a module
3736 (define (module-export-all! mod)
3737 (define (fresh-interface!)
3738 (let ((iface (make-module)))
3739 (set-module-name! iface (module-name mod))
3740 (set-module-version! iface (module-version mod))
3741 (set-module-kind! iface 'interface)
3742 (set-module-public-interface! mod iface)
3744 (let ((iface (or (module-public-interface mod)
3745 (fresh-interface!))))
3746 (set-module-obarray! iface (module-obarray mod))))
3748 ;; Re-export a imported variable
3750 (define (module-re-export! m names)
3751 (let ((public-i (module-public-interface m)))
3752 (for-each (lambda (name)
3753 (let* ((internal-name (if (pair? name) (car name) name))
3754 (external-name (if (pair? name) (cdr name) name))
3755 (var (module-variable m internal-name)))
3757 (error "Undefined variable:" internal-name))
3758 ((eq? var (module-local-variable m internal-name))
3759 (error "re-exporting local variable:" internal-name))
3761 (module-add! public-i external-name var)))))
3764 (define-syntax-rule (export name ...)
3765 (eval-when (eval load compile expand)
3766 (call-with-deferred-observers
3768 (module-export! (current-module) '(name ...))))))
3770 (define-syntax-rule (re-export name ...)
3771 (eval-when (eval load compile expand)
3772 (call-with-deferred-observers
3774 (module-re-export! (current-module) '(name ...))))))
3776 (define-syntax-rule (export! name ...)
3777 (eval-when (eval load compile expand)
3778 (call-with-deferred-observers
3780 (module-replace! (current-module) '(name ...))))))
3782 (define-syntax-rule (export-syntax name ...)
3785 (define-syntax-rule (re-export-syntax name ...)
3786 (re-export name ...))
3793 (define* (make-mutable-parameter init #:optional (converter identity))
3794 (let ((fluid (make-fluid (converter init))))
3796 (() (fluid-ref fluid))
3797 ((val) (fluid-set! fluid (converter val))))))
3802 ;;; {Handling of duplicate imported bindings}
3805 ;; Duplicate handlers take the following arguments:
3807 ;; module importing module
3808 ;; name conflicting name
3809 ;; int1 old interface where name occurs
3810 ;; val1 value of binding in old interface
3811 ;; int2 new interface where name occurs
3812 ;; val2 value of binding in new interface
3813 ;; var previous resolution or #f
3814 ;; val value of previous resolution
3816 ;; A duplicate handler can take three alternative actions:
3818 ;; 1. return #f => leave responsibility to next handler
3819 ;; 2. exit with an error
3820 ;; 3. return a variable resolving the conflict
3823 (define duplicate-handlers
3824 (let ((m (make-module 7)))
3826 (define (check module name int1 val1 int2 val2 var val)
3827 (scm-error 'misc-error
3829 "~A: `~A' imported from both ~A and ~A"
3830 (list (module-name module)
3836 (define (warn module name int1 val1 int2 val2 var val)
3837 (format (current-warning-port)
3838 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3839 (module-name module)
3845 (define (replace module name int1 val1 int2 val2 var val)
3846 (let ((old (or (and var (object-property var 'replace) var)
3847 (module-variable int1 name)))
3848 (new (module-variable int2 name)))
3849 (if (object-property old 'replace)
3850 (and (or (eq? old new)
3851 (not (object-property new 'replace)))
3853 (and (object-property new 'replace)
3856 (define (warn-override-core module name int1 val1 int2 val2 var val)
3857 (and (eq? int1 the-scm-module)
3859 (format (current-warning-port)
3860 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3861 (module-name module)
3864 (module-local-variable int2 name))))
3866 (define (first module name int1 val1 int2 val2 var val)
3867 (or var (module-local-variable int1 name)))
3869 (define (last module name int1 val1 int2 val2 var val)
3870 (module-local-variable int2 name))
3872 (define (noop module name int1 val1 int2 val2 var val)
3875 (set-module-name! m 'duplicate-handlers)
3876 (set-module-kind! m 'interface)
3877 (module-define! m 'check check)
3878 (module-define! m 'warn warn)
3879 (module-define! m 'replace replace)
3880 (module-define! m 'warn-override-core warn-override-core)
3881 (module-define! m 'first first)
3882 (module-define! m 'last last)
3883 (module-define! m 'merge-generics noop)
3884 (module-define! m 'merge-accessors noop)
3887 (define (lookup-duplicates-handlers handler-names)
3889 (map (lambda (handler-name)
3890 (or (module-symbol-local-binding
3891 duplicate-handlers handler-name #f)
3892 (error "invalid duplicate handler name:"
3894 (if (list? handler-names)
3896 (list handler-names)))))
3898 (define default-duplicate-binding-procedures
3899 (make-mutable-parameter #f))
3901 (define default-duplicate-binding-handler
3902 (make-mutable-parameter '(replace warn-override-core warn last)
3903 (lambda (handler-names)
3904 (default-duplicate-binding-procedures
3905 (lookup-duplicates-handlers handler-names))
3912 ;;; Load is tricky when combined with relative file names, compilation,
3913 ;;; and the file system. If a file name is relative, what is it
3914 ;;; relative to? The name of the source file at the time it was
3915 ;;; compiled? The name of the compiled file? What if both or either
3916 ;;; were installed? And how do you get that information? Tricky, I
3919 ;;; To get around all of this, we're going to do something nasty, and
3920 ;;; turn `load' into a macro. That way it can know the name of the
3921 ;;; source file with respect to which it was invoked, so it can resolve
3922 ;;; relative file names with respect to the original source file.
3924 ;;; There is an exception, and that is that if the source file was in
3925 ;;; the load path when it was compiled, instead of looking up against
3926 ;;; the absolute source location, we load-from-path against the relative
3927 ;;; source location.
3930 (define %auto-compilation-options
3931 ;; Default `compile-file' option when auto-compiling.
3932 '(#:warnings (unbound-variable arity-mismatch format
3933 duplicate-case-datum bad-case-datum)))
3935 (define* (load-in-vicinity dir file-name #:optional reader)
3936 "Load source file FILE-NAME in vicinity of directory DIR. Use a
3937 pre-compiled version of FILE-NAME when available, and auto-compile one
3938 when none is available, reading FILE-NAME with READER."
3940 ;; The auto-compilation code will residualize a .go file in the cache
3941 ;; dir: by default, $HOME/.cache/guile/2.0/ccache/PATH.go. This
3942 ;; function determines the PATH to use as a key into the compilation
3944 (define (canonical->suffix canon)
3946 ((and (not (string-null? canon))
3947 (file-name-separator? (string-ref canon 0)))
3949 ((and (eq? (system-file-name-convention) 'windows)
3950 (absolute-file-name? canon))
3951 ;; An absolute file name that doesn't start with a separator
3952 ;; starts with a drive component. Transform the drive component
3953 ;; to a file name element: c:\foo -> \c\foo.
3954 (string-append file-name-separator-string
3955 (substring canon 0 1)
3956 (substring canon 2)))
3959 (define compiled-extension
3960 ;; File name extension of compiled files.
3961 (cond ((or (null? %load-compiled-extensions)
3962 (string-null? (car %load-compiled-extensions)))
3963 (warn "invalid %load-compiled-extensions"
3964 %load-compiled-extensions)
3966 (else (car %load-compiled-extensions))))
3968 (define (more-recent? stat1 stat2)
3969 ;; Return #t when STAT1 has an mtime greater than that of STAT2.
3970 (or (> (stat:mtime stat1) (stat:mtime stat2))
3971 (and (= (stat:mtime stat1) (stat:mtime stat2))
3972 (>= (stat:mtimensec stat1)
3973 (stat:mtimensec stat2)))))
3975 (define (fallback-file-name canon-file-name)
3976 ;; Return the in-cache compiled file name for source file
3979 ;; FIXME: would probably be better just to append
3980 ;; SHA1(canon-file-name) to the %compile-fallback-path, to avoid
3981 ;; deep directory stats.
3982 (and %compile-fallback-path
3983 (string-append %compile-fallback-path
3984 (canonical->suffix canon-file-name)
3985 compiled-extension)))
3987 (define (compile file)
3988 ;; Compile source FILE, lazily loading the compiler.
3989 ((module-ref (resolve-interface '(system base compile))
3992 #:opts %auto-compilation-options
3993 #:env (current-module)))
3995 ;; Returns the .go file corresponding to `name'. Does not search load
3996 ;; paths, only the fallback path. If the .go file is missing or out
3997 ;; of date, and auto-compilation is enabled, will try
3998 ;; auto-compilation, just as primitive-load-path does internally.
3999 ;; primitive-load is unaffected. Returns #f if auto-compilation
4000 ;; failed or was disabled.
4002 ;; NB: Unless we need to compile the file, this function should not
4003 ;; cause (system base compile) to be loaded up. For that reason
4004 ;; compiled-file-name partially duplicates functionality from (system
4007 (define (fresh-compiled-file-name name scmstat go-file-name)
4008 ;; Return GO-FILE-NAME after making sure that it contains a freshly
4009 ;; compiled version of source file NAME with stat SCMSTAT; return #f
4012 (let ((gostat (and (not %fresh-auto-compile)
4013 (stat go-file-name #f))))
4014 (if (and gostat (more-recent? gostat scmstat))
4018 (format (current-warning-port)
4019 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
4022 (%load-should-auto-compile
4023 (%warn-auto-compilation-enabled)
4024 (format (current-warning-port) ";;; compiling ~a\n" name)
4025 (let ((cfn (compile name)))
4026 (format (current-warning-port) ";;; compiled ~a\n" cfn)
4029 #:warning "WARNING: compilation of ~a failed:\n" name))
4031 (define (sans-extension file)
4032 (let ((dot (string-rindex file #\.)))
4034 (substring file 0 dot)
4037 (define (load-absolute abs-file-name)
4038 ;; Load from ABS-FILE-NAME, using a compiled file or auto-compiling
4042 (stat abs-file-name)
4043 #:warning "Stat of ~a failed:\n" abs-file-name))
4045 (define (pre-compiled)
4046 (and=> (search-path %load-compiled-path (sans-extension file-name)
4047 %load-compiled-extensions #t)
4048 (lambda (go-file-name)
4049 (let ((gostat (stat go-file-name #f)))
4050 (and gostat (more-recent? gostat scmstat)
4054 (and=> (false-if-exception (canonicalize-path abs-file-name))
4056 (and=> (fallback-file-name canon)
4057 (lambda (go-file-name)
4058 (fresh-compiled-file-name abs-file-name
4062 (let ((compiled (and scmstat (or (pre-compiled) (fallback)))))
4066 (%load-hook abs-file-name))
4067 (load-compiled compiled))
4068 (start-stack 'load-stack
4069 (primitive-load abs-file-name)))))
4071 (save-module-excursion
4073 (with-fluids ((current-reader reader)
4074 (%file-port-name-canonicalization 'relative))
4076 ((absolute-file-name? file-name)
4077 (load-absolute file-name))
4078 ((absolute-file-name? dir)
4079 (load-absolute (in-vicinity dir file-name)))
4081 (load-from-path (in-vicinity dir file-name))))))))
4084 (make-variable-transformer
4086 (let* ((src (syntax-source x))
4087 (file (and src (assq-ref src 'filename)))
4088 (dir (and (string? file) (dirname file))))
4091 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
4095 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
4099 ;;; {`cond-expand' for SRFI-0 support.}
4101 ;;; This syntactic form expands into different commands or
4102 ;;; definitions, depending on the features provided by the Scheme
4108 ;;; --> (cond-expand <cond-expand-clause>+)
4109 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
4110 ;;; <cond-expand-clause>
4111 ;;; --> (<feature-requirement> <command-or-definition>*)
4112 ;;; <feature-requirement>
4113 ;;; --> <feature-identifier>
4114 ;;; | (and <feature-requirement>*)
4115 ;;; | (or <feature-requirement>*)
4116 ;;; | (not <feature-requirement>)
4117 ;;; <feature-identifier>
4118 ;;; --> <a symbol which is the name or alias of a SRFI>
4120 ;;; Additionally, this implementation provides the
4121 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
4122 ;;; determine the implementation type and the supported standard.
4124 ;;; Remember to update the features list when adding more SRFIs.
4127 (define %cond-expand-features
4128 ;; This should contain only features that are present in core Guile,
4129 ;; before loading any modules. Modular features are handled by
4130 ;; placing 'cond-expand-provide' in the relevant module.
4135 srfi-0 ;; cond-expand itself
4136 srfi-4 ;; homogeneous numeric vectors
4137 ;; We omit srfi-6 because the 'open-input-string' etc in Guile
4138 ;; core are not conformant with SRFI-6; they expose details
4139 ;; of the binary I/O model and may fail to support some characters.
4140 srfi-13 ;; string library
4141 srfi-14 ;; character sets
4142 srfi-23 ;; `error` procedure
4143 srfi-39 ;; parameterize
4144 srfi-55 ;; require-extension
4145 srfi-61 ;; general cond clause
4146 srfi-105 ;; curly infix expressions
4149 ;; This table maps module public interfaces to the list of features.
4151 (define %cond-expand-table (make-hash-table 31))
4153 ;; Add one or more features to the `cond-expand' feature list of the
4156 (define (cond-expand-provide module features)
4157 (let ((mod (module-public-interface module)))
4159 (hashq-set! %cond-expand-table mod
4160 (append (hashq-ref %cond-expand-table mod '())
4163 (define-syntax cond-expand
4165 (define (module-has-feature? mod sym)
4166 (or-map (lambda (mod)
4167 (memq sym (hashq-ref %cond-expand-table mod '())))
4170 (define (condition-matches? condition)
4171 (syntax-case condition (and or not)
4173 (and-map condition-matches? #'(c ...)))
4175 (or-map condition-matches? #'(c ...)))
4177 (if (condition-matches? #'c) #f #t))
4180 (let ((sym (syntax->datum #'c)))
4181 (if (memq sym %cond-expand-features)
4183 (module-has-feature? (current-module) sym))))))
4185 (define (match clauses alternate)
4186 (syntax-case clauses ()
4187 (((condition form ...) . rest)
4188 (if (condition-matches? #'condition)
4190 (match #'rest alternate)))
4193 (syntax-case x (else)
4194 ((_ clause ... (else form ...))
4195 (match #'(clause ...)
4197 #'(begin form ...))))
4199 (match #'(clause ...)
4201 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
4203 ;; This procedure gets called from the startup code with a list of
4204 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
4206 (define (use-srfis srfis)
4207 (process-use-modules
4209 (list (list 'srfi (string->symbol
4210 (string-append "srfi-" (number->string num))))))
4215 ;;; srfi-55: require-extension
4218 (define-syntax require-extension
4220 (syntax-case x (srfi)
4222 (and-map integer? (syntax->datum #'(n ...)))
4226 (datum->syntax x (symbol-append 'srfi- n)))
4228 (map number->string (syntax->datum #'(n ...)))))))
4229 #'(use-modules (srfi srfi-n) ...)))
4231 (identifier? #'type)
4232 (syntax-violation 'require-extension "Not a recognized extension type"
4236 ;;; Defining transparently inlinable procedures
4239 (define-syntax define-inlinable
4240 ;; Define a macro and a procedure such that direct calls are inlined, via
4241 ;; the macro expansion, whereas references in non-call contexts refer to
4242 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
4244 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
4246 (define prefix (string->symbol "% "))
4247 (define (make-procedure-name name)
4249 (symbol-append prefix (syntax->datum name)
4253 ((_ (name formals ...) body ...)
4254 (identifier? #'name)
4255 (with-syntax ((proc-name (make-procedure-name #'name))
4256 ((args ...) (generate-temporaries #'(formals ...))))
4258 (define (proc-name formals ...)
4259 (syntax-parameterize ((name (identifier-syntax proc-name)))
4261 (define-syntax-parameter name
4265 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
4266 (lambda (formals ...)
4271 #'proc-name))))))))))
4275 (define using-readline?
4276 (let ((using-readline? (make-fluid)))
4277 (make-procedure-with-setter
4278 (lambda () (fluid-ref using-readline?))
4279 (lambda (v) (fluid-set! using-readline? v)))))
4283 ;;; {Deprecated stuff}
4287 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
4291 ;;; SRFI-4 in the default environment. FIXME: we should figure out how
4292 ;;; to deprecate this.
4296 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
4300 ;;; A few identifiers that need to be defined in this file are really
4301 ;;; internal implementation details. We shove them off into internal
4302 ;;; modules, removing them from the (guile) module.
4305 (define-module (system syntax))
4308 (define (steal-bindings! from to ids)
4311 (let ((v (module-local-variable from sym)))
4312 (module-remove! from sym)
4313 (module-add! to sym v)))
4315 (module-export! to ids))
4317 (steal-bindings! the-root-module (resolve-module '(system syntax))
4318 '(syntax-local-binding
4320 syntax-locally-bound-identifiers
4321 syntax-session-id)))
4326 ;;; Place the user in the guile-user module.
4329 ;; Set filename to #f to prevent reload.
4330 (define-module (guile-user)
4331 #:autoload (system base compile) (compile compile-file)
4334 ;; Remain in the `(guile)' module at compilation-time so that the
4335 ;; `-Wunused-toplevel' warning works as expected.
4336 (eval-when (compile) (set-current-module the-root-module))
4338 ;;; boot-9.scm ends here