1 ;;; -*- mode: scheme; coding: utf-8; -*-
3 ;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 ;;;; 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
5 ;;;; Free Software Foundation, Inc.
7 ;;;; This library is free software; you can redistribute it and/or
8 ;;;; modify it under the terms of the GNU Lesser General Public
9 ;;;; License as published by the Free Software Foundation; either
10 ;;;; version 3 of the License, or (at your option) any later version.
12 ;;;; This library is distributed in the hope that it will be useful,
13 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 ;;;; Lesser General Public License for more details.
17 ;;;; You should have received a copy of the GNU Lesser General Public
18 ;;;; License along with this library; if not, write to the Free Software
19 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 ;;; This file is the first thing loaded into Guile. It adds many mundane
27 ;;; definitions and a few that are interesting.
29 ;;; The module system (hence the hierarchical namespace) are defined in this
37 ;; Before compiling, make sure any symbols are resolved in the (guile)
38 ;; module, the primary location of those symbols, rather than in
39 ;; (guile-user), the default module that we compile in.
42 (set-current-module (resolve-module '(guile))))
49 ;; Define delimited continuation operators, and implement catch and throw in
52 (define make-prompt-tag
53 (lambda* (#:optional (stem "prompt"))
56 (define default-prompt-tag
57 ;; not sure if we should expose this to the user as a fluid
58 (let ((%default-prompt-tag (make-prompt-tag)))
60 %default-prompt-tag)))
62 (define (call-with-prompt tag thunk handler)
63 (@prompt tag (thunk) handler))
64 (define (abort-to-prompt tag . args)
68 ;; Define catch and with-throw-handler, using some common helper routines and a
69 ;; shared fluid. Hide the helpers in a lexical contour.
71 (define with-throw-handler #f)
73 (define (default-exception-handler k . args)
77 ((not (pair? args)) 0)
78 ((integer? (car args)) (car args))
82 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
85 (define %running-exception-handlers (make-fluid '()))
86 (define %exception-handler (make-fluid default-exception-handler))
88 (define (default-throw-handler prompt-tag catch-k)
89 (let ((prev (fluid-ref %exception-handler)))
90 (lambda (thrown-k . args)
91 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
92 (apply abort-to-prompt prompt-tag thrown-k args)
93 (apply prev thrown-k args)))))
95 (define (custom-throw-handler prompt-tag catch-k pre)
96 (let ((prev (fluid-ref %exception-handler)))
97 (lambda (thrown-k . args)
98 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
99 (let ((running (fluid-ref %running-exception-handlers)))
100 (with-fluids ((%running-exception-handlers (cons pre running)))
101 (if (not (memq pre running))
102 (apply pre thrown-k args))
105 (apply abort-to-prompt prompt-tag thrown-k args)
106 (apply prev thrown-k args))))
107 (apply prev thrown-k args)))))
110 (lambda* (k thunk handler #:optional pre-unwind-handler)
111 "Invoke @var{thunk} in the dynamic context of @var{handler} for
112 exceptions matching @var{key}. If thunk throws to the symbol
113 @var{key}, then @var{handler} is invoked this way:
115 (handler key args ...)
118 @var{key} is a symbol or @code{#t}.
120 @var{thunk} takes no arguments. If @var{thunk} returns
121 normally, that is the return value of @code{catch}.
123 Handler is invoked outside the scope of its own @code{catch}.
124 If @var{handler} again throws to the same key, a new handler
125 from further up the call chain is invoked.
127 If the key is @code{#t}, then a throw to @emph{any} symbol will
128 match this call to @code{catch}.
130 If a @var{pre-unwind-handler} is given and @var{thunk} throws
131 an exception that matches @var{key}, Guile calls the
132 @var{pre-unwind-handler} before unwinding the dynamic state and
133 invoking the main @var{handler}. @var{pre-unwind-handler} should
134 be a procedure with the same signature as @var{handler}, that
135 is @code{(lambda (key . args))}. It is typically used to save
136 the stack at the point where the exception occurred, but can also
137 query other parts of the dynamic state at that point, such as
140 A @var{pre-unwind-handler} can exit either normally or non-locally.
141 If it exits normally, Guile unwinds the stack and dynamic context
142 and then calls the normal (third argument) handler. If it exits
143 non-locally, that exit determines the continuation."
144 (if (not (or (symbol? k) (eqv? k #t)))
145 (scm-error 'wrong-type-arg "catch"
146 "Wrong type argument in position ~a: ~a"
147 (list 1 k) (list k)))
148 (let ((tag (make-prompt-tag "catch")))
154 (if pre-unwind-handler
155 (custom-throw-handler tag k pre-unwind-handler)
156 (default-throw-handler tag k))))
158 (lambda (cont k . args)
159 (apply handler k args))))))
161 (set! with-throw-handler
162 (lambda (k thunk pre-unwind-handler)
163 "Add @var{handler} to the dynamic context as a throw handler
164 for key @var{k}, then invoke @var{thunk}."
165 (if (not (or (symbol? k) (eqv? k #t)))
166 (scm-error 'wrong-type-arg "with-throw-handler"
167 "Wrong type argument in position ~a: ~a"
168 (list 1 k) (list k)))
169 (with-fluids ((%exception-handler
170 (custom-throw-handler #f k pre-unwind-handler)))
175 "Invoke the catch form matching @var{key}, passing @var{args} to the
178 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
180 If there is no handler at all, Guile prints an error and then exits."
181 (if (not (symbol? key))
182 ((fluid-ref %exception-handler) 'wrong-type-arg "throw"
183 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
184 (apply (fluid-ref %exception-handler) key args)))))
189 ;;; {R4RS compliance}
192 (primitive-load-path "ice-9/r4rs")
196 ;;; {Simple Debugging Tools}
199 ;; peek takes any number of arguments, writes them to the
200 ;; current ouput port, and returns the last argument.
201 ;; It is handy to wrap around an expression to look at
202 ;; a value each time is evaluated, e.g.:
204 ;; (+ 10 (troublesome-fn))
205 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
208 (define (peek . stuff)
213 (car (last-pair stuff)))
217 ;; Temporary definition; replaced later.
218 (define current-warning-port current-error-port)
220 (define (warn . stuff)
221 (with-output-to-port (current-warning-port)
224 (display ";;; WARNING ")
227 (car (last-pair stuff)))))
234 (define (provide sym)
235 (if (not (memq sym *features*))
236 (set! *features* (cons sym *features*))))
238 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
239 ;; provided? also checks to see if the module is available. We should do that
242 (define (provided? feature)
243 (and (memq feature *features*) #t))
250 (define (make-struct/no-tail vtable . args)
251 (apply make-struct vtable 0 args))
255 ;;; Boot versions of `map' and `for-each', enough to get the expander
264 (cons (f (car l)) (map1 (cdr l))))))
266 (let map2 ((l1 l1) (l2 l2))
269 (cons (f (car l1) (car l2))
270 (map2 (cdr l1) (cdr l2))))))
272 (let lp ((l1 l1) (rest rest))
275 (cons (apply f (car l1) (map car rest))
276 (lp (cdr l1) (map cdr rest))))))))
281 (let for-each1 ((l l))
285 (for-each1 (cdr l))))))
287 (let for-each2 ((l1 l1) (l2 l2))
290 (f (car l1) (car l2))
291 (for-each2 (cdr l1) (cdr l2))))))
293 (let lp ((l1 l1) (rest rest))
296 (apply f (car l1) (map car rest))
297 (lp (cdr l1) (map cdr rest))))))))
299 ;;; {and-map and or-map}
301 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
302 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
307 ;; Apply f to successive elements of l until exhaustion or f returns #f.
308 ;; If returning early, return #f. Otherwise, return the last value returned
309 ;; by f. If f has never been called because l is empty, return #t.
311 (define (and-map f lst)
312 (let loop ((result #t)
317 (loop (f (car l)) (cdr l))))))
321 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
322 ;; If returning early, return the return value of f.
324 (define (or-map f lst)
325 (let loop ((result #f)
329 (loop (f (car l)) (cdr l))))))
333 ;; let format alias simple-format until the more complete version is loaded
335 (define format simple-format)
337 ;; this is scheme wrapping the C code so the final pred call is a tail call,
340 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
341 (if (and (procedure? char_pred)
343 (<= end (string-length s))) ;; let c-code handle range error
344 (or (string-any-c-code char_pred s start (1- end))
345 (char_pred (string-ref s (1- end))))
346 (string-any-c-code char_pred s start end))))
348 ;; this is scheme wrapping the C code so the final pred call is a tail call,
351 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
352 (if (and (procedure? char_pred)
354 (<= end (string-length s))) ;; let c-code handle range error
355 (and (string-every-c-code char_pred s start (1- end))
356 (char_pred (string-ref s (1- end))))
357 (string-every-c-code char_pred s start end))))
359 ;; A variant of string-fill! that we keep for compatability
361 (define (substring-fill! str start end fill)
362 (string-fill! str fill start end))
366 ;; Define a minimal stub of the module API for psyntax, before modules
368 (define (module-name x)
370 (define (module-add! module sym var)
371 (hashq-set! (%get-pre-modules-obarray) sym var))
372 (define (module-define! module sym val)
373 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
375 (variable-set! v val)
376 (module-add! (current-module) sym (make-variable val)))))
377 (define (module-ref module sym)
378 (let ((v (module-variable module sym)))
379 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
380 (define (resolve-module . args)
383 ;; API provided by psyntax
384 (define syntax-violation #f)
385 (define datum->syntax #f)
386 (define syntax->datum #f)
387 (define syntax-source #f)
388 (define identifier? #f)
389 (define generate-temporaries #f)
390 (define bound-identifier=? #f)
391 (define free-identifier=? #f)
393 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
394 ;; expanded macros, to dispatch an input against a set of patterns.
395 (define $sc-dispatch #f)
398 (primitive-load-path "ice-9/psyntax-pp")
399 ;; The binding for `macroexpand' has now been overridden, making psyntax the
406 ((_ x y ...) (if x (and y ...) #f))))
412 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
414 (include-from-path "ice-9/quasisyntax")
416 (define-syntax-rule (when test stmt stmt* ...)
417 (if test (begin stmt stmt* ...)))
419 (define-syntax-rule (unless test stmt stmt* ...)
420 (if (not test) (begin stmt stmt* ...)))
424 (define (fold f seed xs)
425 (let loop ((xs xs) (seed seed))
427 (loop (cdr xs) (f (car xs) seed)))))
428 (define (reverse-map f xs)
429 (fold (lambda (x seed) (cons (f x) seed))
431 (syntax-case whole-expr ()
432 ((_ clause clauses ...)
434 #,@(fold (lambda (clause-builder tail)
435 (clause-builder tail))
439 (define* (bad-clause #:optional (msg "invalid clause"))
440 (syntax-violation 'cond msg whole-expr clause))
441 (syntax-case clause (=> else)
446 (bad-clause "else must be the last clause"))))
447 ((else . _) (bad-clause))
454 ((test => receiver ...)
455 (bad-clause "wrong number of receiver expressions"))
456 ((generator guard => receiver)
458 #`((call-with-values (lambda () generator)
460 (if (apply guard vals)
461 (apply receiver vals)
463 ((generator guard => receiver ...)
464 (bad-clause "wrong number of receiver expressions"))
475 #'(clause clauses ...))))))))
479 (define (fold f seed xs)
480 (let loop ((xs xs) (seed seed))
482 (loop (cdr xs) (f (car xs) seed)))))
483 (define (fold2 f a b xs)
484 (let loop ((xs xs) (a a) (b b))
485 (if (null? xs) (values a b)
487 (lambda () (f (car xs) a b))
489 (loop (cdr xs) a b))))))
490 (define (reverse-map-with-seed f seed xs)
491 (fold2 (lambda (x ys seed)
493 (lambda () (f x seed))
495 (values (cons y ys) seed))))
497 (syntax-case whole-expr ()
498 ((_ expr clause clauses ...)
499 (with-syntax ((key #'key))
502 (lambda (clause-builder tail)
503 (clause-builder tail))
505 (reverse-map-with-seed
506 (lambda (clause seen)
507 (define* (bad-clause #:optional (msg "invalid clause"))
508 (syntax-violation 'case msg whole-expr clause))
509 (syntax-case clause ()
513 (syntax-case #'rest (=>)
514 ((=> receiver) #'(receiver key))
517 "wrong number of receiver expressions"))
518 ((e e* ...) #'(begin e e* ...))
520 (syntax-case #'test (else)
525 (define (warn-datum type)
526 ((@ (system base message)
529 (append (source-properties datum)
531 (syntax->datum #'test)))
533 (syntax->datum clause)
534 (syntax->datum whole-expr)))
535 (if (memv datum seen)
536 (warn-datum 'duplicate-case-datum))
537 (if (or (pair? datum)
539 (generalized-vector? datum))
540 (warn-datum 'bad-case-datum))
543 (map syntax->datum #'(datums ...)))))
544 (values (lambda (tail)
545 #`((if (memv key '(datums ...))
549 (else (values (lambda (tail)
553 "else must be the last clause")))
557 '() #'(clause clauses ...)))))))))
561 ((do ((var init step ...) ...)
574 (loop (do "step" var step ...)
582 (define-syntax-rule (delay exp)
583 (make-promise (lambda () exp)))
585 (define-syntax current-source-location
589 (with-syntax ((s (datum->syntax x (syntax-source x))))
592 ;; We provide this accessor out of convenience. current-line and
593 ;; current-column aren't so interesting, because they distort what they
594 ;; are measuring; better to use syntax-source from a macro.
596 (define-syntax current-filename
598 "A macro that expands to the current filename: the filename that
599 the (current-filename) form appears in. Expands to #f if this
600 information is unavailable."
602 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
604 (define-syntax-rule (define-once sym val)
606 (if (module-locally-bound? (current-module) 'sym) sym val)))
608 ;;; The real versions of `map' and `for-each', with cycle detection, and
609 ;;; that use reverse! instead of recursion in the case of `map'.
614 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
617 (if (eq? tortoise hare)
618 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
620 (map1 (cdr hare) (cdr tortoise) #f
621 (cons (f (car hare)) out)))
622 (map1 (cdr hare) tortoise #t
623 (cons (f (car hare)) out)))
626 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
630 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
635 (scm-error 'wrong-type-arg "map"
637 "List of wrong length: ~S"
641 (map2 (cdr h1) (cdr h2) t1 t2 #t
642 (cons (f (car h1) (car h2)) out)))
644 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
647 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
650 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
651 (cons (f (car h1) (car h2)) out)))))
653 ((and (null? h1) (null? h2))
657 (scm-error 'wrong-type-arg "map"
659 "List of wrong length: ~S"
663 (scm-error 'wrong-type-arg "map"
668 (let ((len (length l1)))
669 (let mapn ((rest rest))
671 (if (= (length (car rest)) len)
673 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
674 (list (car rest)) #f)))))
675 (let mapn ((l1 l1) (rest rest) (out '()))
678 (mapn (cdr l1) (map cdr rest)
679 (cons (apply f (car l1) (map car rest)) out)))))))
681 (define map-in-order map)
686 (let for-each1 ((hare l) (tortoise l) (move? #f))
689 (if (eq? tortoise hare)
690 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
694 (for-each1 (cdr hare) (cdr tortoise) #f)))
697 (for-each1 (cdr hare) tortoise #t)))
699 (if (not (null? hare))
700 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
704 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
706 ((and (pair? h1) (pair? h2))
709 (f (car h1) (car h2))
710 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
712 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
715 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
718 (f (car h1) (car h2))
719 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
722 (or (null? h2) (pair? h2))
723 (and (pair? h1) (null? h2)))
727 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
730 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
734 (let ((len (length l1)))
735 (let for-eachn ((rest rest))
737 (if (= (length (car rest)) len)
738 (for-eachn (cdr rest))
739 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
740 (list (car rest)) #f)))))
742 (let for-eachn ((l1 l1) (rest rest))
745 (apply f (car l1) (map car rest))
746 (for-eachn (cdr l1) (map cdr rest))))))))
752 ;;; Extensible exception printing.
755 (define set-exception-printer! #f)
756 ;; There is already a definition of print-exception from backtrace.c
757 ;; that we will override.
759 (let ((exception-printers '()))
760 (define (print-location frame port)
761 (let ((source (and=> frame frame-source)))
762 ;; source := (addr . (filename . (line . column)))
764 (let ((filename (or (cadr source) "<unnamed port>"))
765 (line (caddr source))
766 (col (cdddr source)))
767 (format port "~a:~a:~a: " filename (1+ line) col))
768 (format port "ERROR: "))))
770 (set! set-exception-printer!
772 (set! exception-printers (acons key proc exception-printers))))
774 (set! print-exception
775 (lambda (port frame key args)
776 (define (default-printer)
777 (format port "Throw to key `~a' with args `~s'." key args))
780 (let ((proc (frame-procedure frame)))
781 (print-location frame port)
782 (format port "In procedure ~a:\n"
783 (or (false-if-exception (procedure-name proc))
786 (print-location frame port)
789 (let ((printer (assq-ref exception-printers key)))
791 (printer port key args default-printer)
794 (format port "Error while printing exception.")))
796 (force-output port))))
799 ;;; Printers for those keys thrown by Guile.
802 (define (scm-error-printer port key args default-printer)
803 ;; Abuse case-lambda as a pattern matcher, given that we don't have
804 ;; ice-9 match at this point.
806 ((subr msg args . rest)
808 (format port "In procedure ~a: " subr))
809 (apply format port msg (or args '())))
810 (_ (default-printer)))
813 (define (syntax-error-printer port key args default-printer)
815 ((who what where form subform . extra)
816 (format port "Syntax error:\n")
818 (let ((file (or (assq-ref where 'filename) "unknown file"))
819 (line (and=> (assq-ref where 'line) 1+))
820 (col (assq-ref where 'column)))
821 (format port "~a:~a:~a: " file line col))
822 (format port "unknown location: "))
824 (format port "~a: " who))
825 (format port "~a" what)
827 (format port " in subform ~s of ~s" subform form)
829 (format port " in form ~s" form))))
830 (_ (default-printer)))
833 (define (getaddrinfo-error-printer port key args default-printer)
834 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
836 (set-exception-printer! 'goops-error scm-error-printer)
837 (set-exception-printer! 'host-not-found scm-error-printer)
838 (set-exception-printer! 'keyword-argument-error scm-error-printer)
839 (set-exception-printer! 'misc-error scm-error-printer)
840 (set-exception-printer! 'no-data scm-error-printer)
841 (set-exception-printer! 'no-recovery scm-error-printer)
842 (set-exception-printer! 'null-pointer-error scm-error-printer)
843 (set-exception-printer! 'out-of-range scm-error-printer)
844 (set-exception-printer! 'program-error scm-error-printer)
845 (set-exception-printer! 'read-error scm-error-printer)
846 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
847 (set-exception-printer! 'signal scm-error-printer)
848 (set-exception-printer! 'stack-overflow scm-error-printer)
849 (set-exception-printer! 'system-error scm-error-printer)
850 (set-exception-printer! 'try-again scm-error-printer)
851 (set-exception-printer! 'unbound-variable scm-error-printer)
852 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
853 (set-exception-printer! 'wrong-type-arg scm-error-printer)
855 (set-exception-printer! 'syntax-error syntax-error-printer)
857 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
865 (define-syntax define-macro
869 ((_ (macro . args) doc body1 body ...)
870 (string? (syntax->datum #'doc))
871 #'(define-macro macro doc (lambda args body1 body ...)))
872 ((_ (macro . args) body ...)
873 #'(define-macro macro #f (lambda args body ...)))
874 ((_ macro doc transformer)
875 (or (string? (syntax->datum #'doc))
876 (not (syntax->datum #'doc)))
877 #'(define-syntax macro
880 #((macro-type . defmacro)
881 (defmacro-args args))
884 (let ((v (syntax->datum #'args)))
885 (datum->syntax y (apply transformer v)))))))))))
887 (define-syntax defmacro
889 "Define a defmacro, with the old lispy defun syntax."
891 ((_ macro args doc body1 body ...)
892 (string? (syntax->datum #'doc))
893 #'(define-macro macro doc (lambda args body1 body ...)))
894 ((_ macro args body ...)
895 #'(define-macro macro #f (lambda args body ...))))))
904 (define-syntax begin-deprecated
908 (if (include-deprecated-features)
909 #'(begin form form* ...)
914 ;;; {Trivial Functions}
917 (define (identity x) x)
919 (define (compose proc . rest)
920 "Compose PROC with the procedures in REST, such that the last one in
921 REST is applied first and PROC last, and return the resulting procedure.
922 The given procedures must have compatible arity."
925 (let ((g (apply compose rest)))
927 (call-with-values (lambda () (apply g args)) proc)))))
929 (define (negate proc)
930 "Return a procedure with the same arity as PROC that returns the `not'
933 (not (apply proc args))))
935 (define (const value)
936 "Return a procedure that accepts any number of arguments and returns
941 (define (and=> value procedure) (and value (procedure value)))
942 (define call/cc call-with-current-continuation)
944 (define-syntax-rule (false-if-exception expr)
947 (lambda (k . args) #f)))
951 ;;; {General Properties}
954 ;; Properties are a lispy way to associate random info with random objects.
955 ;; Traditionally properties are implemented as an alist or a plist actually
956 ;; pertaining to the object in question.
958 ;; These "object properties" have the advantage that they can be associated with
959 ;; any object, even if the object has no plist. Object properties are good when
960 ;; you are extending pre-existing objects in unexpected ways. They also present
961 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
962 ;; type that always has properties, it's often still best to store those
963 ;; properties within the object itself.
965 (define (make-object-property)
966 (define-syntax-rule (with-mutex lock exp)
967 (dynamic-wind (lambda () (lock-mutex lock))
969 (lambda () (unlock-mutex lock))))
970 (let ((prop (make-weak-key-hash-table))
972 (make-procedure-with-setter
973 (lambda (obj) (with-mutex lock (hashq-ref prop obj)))
974 (lambda (obj val) (with-mutex lock (hashq-set! prop obj val))))))
979 ;;; {Symbol Properties}
982 ;;; Symbol properties are something you see in old Lisp code. In most current
983 ;;; Guile code, symbols are not used as a data structure -- they are used as
984 ;;; keys into other data structures.
986 (define (symbol-property sym prop)
987 (let ((pair (assoc prop (symbol-pref sym))))
988 (and pair (cdr pair))))
990 (define (set-symbol-property! sym prop val)
991 (let ((pair (assoc prop (symbol-pref sym))))
994 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
996 (define (symbol-property-remove! sym prop)
997 (let ((pair (assoc prop (symbol-pref sym))))
999 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
1006 (define (array-shape a)
1007 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1008 (array-dimensions a)))
1015 ;;; It's much better if you can use lambda* / define*, of course.
1017 (define (kw-arg-ref args kw)
1018 (let ((rem (member kw args)))
1019 (and rem (pair? (cdr rem)) (cadr rem))))
1026 (define (struct-layout s)
1027 (struct-ref (struct-vtable s) vtable-index-layout))
1034 ;; Printing records: by default, records are printed as
1036 ;; #<type-name field1: val1 field2: val2 ...>
1038 ;; You can change that by giving a custom printing function to
1039 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1040 ;; will be called like
1042 ;; (<printer> object port)
1044 ;; It should print OBJECT to PORT.
1046 (define (inherit-print-state old-port new-port)
1047 (if (get-print-state old-port)
1048 (port-with-print-state new-port (get-print-state old-port))
1051 ;; 0: type-name, 1: fields, 2: constructor
1052 (define record-type-vtable
1053 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1055 (display "#<record-type " p)
1056 (display (record-type-name s) p)
1058 (set-struct-vtable-name! s 'record-type)
1061 (define (record-type? obj)
1062 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1064 (define* (make-record-type type-name fields #:optional printer)
1065 ;; Pre-generate constructors for nfields < 20.
1066 (define-syntax make-constructor
1068 (define *max-static-argument-count* 20)
1069 (define (make-formals n)
1072 (cons (datum->syntax
1075 (string (integer->char (+ (char->integer #\a) i)))))
1079 ((_ rtd exp) (not (identifier? #'exp))
1081 (make-constructor rtd n)))
1085 (if (< n *max-static-argument-count*)
1086 (cons (with-syntax (((formal ...) (make-formals n))
1089 (lambda (formal ...)
1090 (make-struct rtd 0 formal ...))))
1095 (if (= (length args) nfields)
1096 (apply make-struct rtd 0 args)
1097 (scm-error 'wrong-number-of-args
1098 (format #f "make-~a" type-name)
1099 "Wrong number of arguments" '() #f)))))))))
1101 (define (default-record-printer s p)
1103 (display (record-type-name (record-type-descriptor s)) p)
1104 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1107 ((not (null? fields))
1109 (display (car fields) p)
1111 (display (struct-ref s off) p)
1112 (loop (cdr fields) (+ 1 off)))))
1115 (let ((rtd (make-struct record-type-vtable 0
1117 (apply string-append
1118 (map (lambda (f) "pw") fields)))
1119 (or printer default-record-printer)
1121 (copy-tree fields))))
1122 (struct-set! rtd (+ vtable-offset-user 2)
1123 (make-constructor rtd (length fields)))
1124 ;; Temporary solution: Associate a name to the record type descriptor
1125 ;; so that the object system can create a wrapper class for it.
1126 (set-struct-vtable-name! rtd (if (symbol? type-name)
1128 (string->symbol type-name)))
1131 (define (record-type-name obj)
1132 (if (record-type? obj)
1133 (struct-ref obj vtable-offset-user)
1134 (error 'not-a-record-type obj)))
1136 (define (record-type-fields obj)
1137 (if (record-type? obj)
1138 (struct-ref obj (+ 1 vtable-offset-user))
1139 (error 'not-a-record-type obj)))
1141 (define* (record-constructor rtd #:optional field-names)
1142 (if (not field-names)
1143 (struct-ref rtd (+ 2 vtable-offset-user))
1145 `(lambda ,field-names
1146 (make-struct ',rtd 0 ,@(map (lambda (f)
1147 (if (memq f field-names)
1150 (record-type-fields rtd)))))))
1152 (define (record-predicate rtd)
1153 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1155 (define (%record-type-error rtd obj) ;; private helper
1156 (or (eq? rtd (record-type-descriptor obj))
1157 (scm-error 'wrong-type-arg "%record-type-check"
1158 "Wrong type record (want `~S'): ~S"
1159 (list (record-type-name rtd) obj)
1162 (define (record-accessor rtd field-name)
1163 (let ((pos (list-index (record-type-fields rtd) field-name)))
1165 (error 'no-such-field field-name))
1167 (if (eq? (struct-vtable obj) rtd)
1168 (struct-ref obj pos)
1169 (%record-type-error rtd obj)))))
1171 (define (record-modifier rtd field-name)
1172 (let ((pos (list-index (record-type-fields rtd) field-name)))
1174 (error 'no-such-field field-name))
1176 (if (eq? (struct-vtable obj) rtd)
1177 (struct-set! obj pos val)
1178 (%record-type-error rtd obj)))))
1180 (define (record? obj)
1181 (and (struct? obj) (record-type? (struct-vtable obj))))
1183 (define (record-type-descriptor obj)
1186 (error 'not-a-record obj)))
1195 (define (->bool x) (not (not x)))
1202 (define (symbol-append . args)
1203 (string->symbol (apply string-append (map symbol->string args))))
1205 (define (list->symbol . args)
1206 (string->symbol (apply list->string args)))
1208 (define (symbol . args)
1209 (string->symbol (apply string args)))
1216 (define (list-index l k)
1219 (and (not (null? l))
1222 (loop (+ n 1) (cdr l))))))
1226 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1227 ;; `stat' accessors.
1228 (primitive-load-path "ice-9/posix")
1230 (if (provided? 'socket)
1231 (primitive-load-path "ice-9/networking"))
1233 ;; For reference, Emacs file-exists-p uses stat in this same way.
1234 (define file-exists?
1235 (if (provided? 'posix)
1237 (->bool (stat str #f)))
1239 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
1241 (if port (begin (close-port port) #t)
1244 (define file-is-directory?
1245 (if (provided? 'posix)
1247 (eq? (stat:type (stat str)) 'directory))
1249 (let ((port (catch 'system-error
1250 (lambda () (open-file (string-append str "/.")
1253 (if port (begin (close-port port) #t)
1256 (define (system-error-errno args)
1257 (if (eq? (car args) 'system-error)
1258 (car (list-ref args 4))
1263 ;;; {Error Handling}
1269 (scm-error 'misc-error #f "?" #f #f))
1271 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1272 (scm-error 'misc-error #f msg (cons message args) #f)))))
1276 ;;; {Time Structures}
1279 (define (tm:sec obj) (vector-ref obj 0))
1280 (define (tm:min obj) (vector-ref obj 1))
1281 (define (tm:hour obj) (vector-ref obj 2))
1282 (define (tm:mday obj) (vector-ref obj 3))
1283 (define (tm:mon obj) (vector-ref obj 4))
1284 (define (tm:year obj) (vector-ref obj 5))
1285 (define (tm:wday obj) (vector-ref obj 6))
1286 (define (tm:yday obj) (vector-ref obj 7))
1287 (define (tm:isdst obj) (vector-ref obj 8))
1288 (define (tm:gmtoff obj) (vector-ref obj 9))
1289 (define (tm:zone obj) (vector-ref obj 10))
1291 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1292 (define (set-tm:min obj val) (vector-set! obj 1 val))
1293 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1294 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1295 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1296 (define (set-tm:year obj val) (vector-set! obj 5 val))
1297 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1298 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1299 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1300 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1301 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1303 (define (tms:clock obj) (vector-ref obj 0))
1304 (define (tms:utime obj) (vector-ref obj 1))
1305 (define (tms:stime obj) (vector-ref obj 2))
1306 (define (tms:cutime obj) (vector-ref obj 3))
1307 (define (tms:cstime obj) (vector-ref obj 4))
1311 ;;; {File Descriptors and Ports}
1314 (define file-position ftell)
1315 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1316 (seek port offset whence))
1318 (define (move->fdes fd/port fd)
1319 (cond ((integer? fd/port)
1320 (dup->fdes fd/port fd)
1324 (primitive-move->fdes fd/port fd)
1325 (set-port-revealed! fd/port 1)
1328 (define (release-port-handle port)
1329 (let ((revealed (port-revealed port)))
1331 (set-port-revealed! port (- revealed 1)))))
1336 (fdopen (dup->fdes port/fd) mode))
1337 ((port/fd mode new-fd)
1338 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1339 (set-port-revealed! port 1)
1345 (dup->port port/fd "r"))
1347 (dup->port port/fd "r" new-fd))))
1349 (define dup->outport
1352 (dup->port port/fd "w"))
1354 (dup->port port/fd "w" new-fd))))
1359 (if (integer? port/fd)
1361 (dup->port port/fd (port-mode port/fd))))
1363 (if (integer? port/fd)
1364 (dup->fdes port/fd new-fd)
1365 (dup->port port/fd (port-mode port/fd) new-fd)))))
1367 (define (duplicate-port port modes)
1368 (dup->port port modes))
1370 (define (fdes->inport fdes)
1371 (let loop ((rest-ports (fdes->ports fdes)))
1372 (cond ((null? rest-ports)
1373 (let ((result (fdopen fdes "r")))
1374 (set-port-revealed! result 1)
1376 ((input-port? (car rest-ports))
1377 (set-port-revealed! (car rest-ports)
1378 (+ (port-revealed (car rest-ports)) 1))
1381 (loop (cdr rest-ports))))))
1383 (define (fdes->outport fdes)
1384 (let loop ((rest-ports (fdes->ports fdes)))
1385 (cond ((null? rest-ports)
1386 (let ((result (fdopen fdes "w")))
1387 (set-port-revealed! result 1)
1389 ((output-port? (car rest-ports))
1390 (set-port-revealed! (car rest-ports)
1391 (+ (port-revealed (car rest-ports)) 1))
1394 (loop (cdr rest-ports))))))
1396 (define (port->fdes port)
1397 (set-port-revealed! port (+ (port-revealed port) 1))
1400 (define (setenv name value)
1402 (putenv (string-append name "=" value))
1405 (define (unsetenv name)
1406 "Remove the entry for NAME from the environment."
1414 (define (in-vicinity vicinity file)
1415 (let ((tail (let ((len (string-length vicinity)))
1418 (string-ref vicinity (- len 1))))))
1419 (string-append vicinity
1428 ;;; {Help for scm_shell}
1430 ;;; The argument-processing code used by Guile-based shells generates
1431 ;;; Scheme code based on the argument list. This page contains help
1432 ;;; functions for the code it generates.
1435 (define (command-line) (program-arguments))
1437 ;; This is mostly for the internal use of the code generated by
1438 ;; scm_compile_shell_switches.
1440 (define (load-user-init)
1441 (let* ((home (or (getenv "HOME")
1442 (false-if-exception (passwd:dir (getpwuid (getuid))))
1443 "/")) ;; fallback for cygwin etc.
1444 (init-file (in-vicinity home ".guile")))
1445 (if (file-exists? init-file)
1446 (primitive-load init-file))))
1450 ;;; {The interpreter stack}
1453 ;; %stacks defined in stacks.c
1454 (define (%start-stack tag thunk)
1455 (let ((prompt-tag (make-prompt-tag "start-stack")))
1459 (with-fluids ((%stacks (acons tag prompt-tag
1460 (or (fluid-ref %stacks) '()))))
1463 (%start-stack tag (lambda () (apply k args)))))))
1465 (define-syntax-rule (start-stack tag exp)
1466 (%start-stack tag (lambda () exp)))
1470 ;;; {Loading by paths}
1473 ;;; Load a Scheme source file named NAME, searching for it in the
1474 ;;; directories listed in %load-path, and applying each of the file
1475 ;;; name extensions listed in %load-extensions.
1476 (define (load-from-path name)
1477 (start-stack 'load-stack
1478 (primitive-load-path name)))
1480 (define-syntax-rule (add-to-load-path elt)
1481 "Add ELT to Guile's load path, at compile-time and at run-time."
1482 (eval-when (compile load eval)
1483 (set! %load-path (cons elt %load-path))))
1485 (define %load-verbosely #f)
1486 (define (assert-load-verbosity v) (set! %load-verbosely v))
1488 (define (%load-announce file)
1490 (with-output-to-port (current-warning-port)
1493 (display "loading ")
1498 (set! %load-hook %load-announce)
1502 ;;; {Reader Extensions}
1504 ;;; Reader code for various "#c" forms.
1507 (define read-eval? (make-fluid #f))
1508 (read-hash-extend #\.
1510 (if (fluid-ref read-eval?)
1511 (eval (read port) (interaction-environment))
1513 "#. read expansion found and read-eval? is #f."))))
1517 ;;; {Low Level Modules}
1519 ;;; These are the low level data structures for modules.
1521 ;;; Every module object is of the type 'module-type', which is a record
1522 ;;; consisting of the following members:
1524 ;;; - eval-closure: A deprecated field, to be removed in Guile 2.2.
1526 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1527 ;;; hash table, the definitions are found that are local to the module (that
1528 ;;; is, not imported from other modules). When looking up bindings in the
1529 ;;; module, this hash table is searched first.
1531 ;;; - binder: either #f or a function taking a module and a symbol argument.
1532 ;;; If it is a function it is called after the obarray has been
1533 ;;; unsuccessfully searched for a binding. It then can provide bindings
1534 ;;; that would otherwise not be found locally in the module.
1536 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1537 ;;; These modules are the third place queried for bindings after the obarray
1538 ;;; has been unsuccessfully searched and the binder function did not deliver
1539 ;;; a result either.
1541 ;;; - transformer: either #f or a function taking a scheme expression as
1542 ;;; delivered by read. If it is a function, it will be called to perform
1543 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1544 ;;; expression. The output of the transformer function will then be passed
1545 ;;; to Guile's internal memoizer. This means that the output must be valid
1546 ;;; scheme code. The only exception is, that the output may make use of the
1547 ;;; syntax extensions provided to identify the modules that a binding
1550 ;;; - name: the name of the module. This is used for all kinds of printing
1551 ;;; outputs. In certain places the module name also serves as a way of
1552 ;;; identification. When adding a module to the uses list of another
1553 ;;; module, it is made sure that the new uses list will not contain two
1554 ;;; modules of the same name.
1556 ;;; - kind: classification of the kind of module. The value is (currently?)
1557 ;;; only used for printing. It has no influence on how a module is treated.
1558 ;;; Currently the following values are used when setting the module kind:
1559 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1560 ;;; is set, it defaults to 'module.
1562 ;;; - duplicates-handlers: a list of procedures that get called to make a
1563 ;;; choice between two duplicate bindings when name clashes occur. See the
1564 ;;; `duplicate-handlers' global variable below.
1566 ;;; - observers: a list of procedures that get called when the module is
1569 ;;; - weak-observers: a weak-key hash table of procedures that get called
1570 ;;; when the module is modified. See `module-observe-weak' for details.
1572 ;;; In addition, the module may (must?) contain a binding for
1573 ;;; `%module-public-interface'. This variable should be bound to a module
1574 ;;; representing the exported interface of a module. See the
1575 ;;; `module-public-interface' and `module-export!' procedures.
1577 ;;; !!! warning: The interface to lazy binder procedures is going
1578 ;;; to be changed in an incompatible way to permit all the basic
1579 ;;; module ops to be virtualized.
1581 ;;; (make-module size use-list lazy-binding-proc) => module
1582 ;;; module-{obarray,uses,binder}[|-set!]
1583 ;;; (module? obj) => [#t|#f]
1584 ;;; (module-locally-bound? module symbol) => [#t|#f]
1585 ;;; (module-bound? module symbol) => [#t|#f]
1586 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1587 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1588 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1589 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1590 ;;; (module-symbol-binding module symbol opt-value)
1591 ;;; => [ <obj> | opt-value | an error occurs ]
1592 ;;; (module-make-local-var! module symbol) => #<variable...>
1593 ;;; (module-add! module symbol var) => unspecified
1594 ;;; (module-remove! module symbol) => unspecified
1595 ;;; (module-for-each proc module) => unspecified
1596 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1597 ;;; (set-current-module module) => unspecified
1598 ;;; (current-module) => #<module...>
1604 ;;; {Printing Modules}
1607 ;; This is how modules are printed. You can re-define it.
1608 (define (%print-module mod port)
1610 (display (or (module-kind mod) "module") port)
1612 (display (module-name mod) port)
1614 (display (number->string (object-address mod) 16) port)
1618 ;; Locally extend the syntax to allow record accessors to be defined at
1619 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1620 ;; the setters, in order to allow for redefinition of the record type; not
1621 ;; relevant in the case of modules, but perhaps if we make this public, it
1624 ((define-record-type
1626 (define (make-id scope . fragments)
1627 (datum->syntax #'scope
1628 (apply symbol-append
1630 (if (symbol? x) x (syntax->datum x)))
1633 (define (getter rtd type-name field slot)
1634 #`(define #,(make-id rtd type-name '- field)
1636 (lambda (#,type-name)
1637 (if (eq? (struct-vtable #,type-name) rtd)
1638 (struct-ref #,type-name #,slot)
1639 (%record-type-error rtd #,type-name))))))
1641 (define (setter rtd type-name field slot)
1642 #`(define #,(make-id rtd 'set- type-name '- field '!)
1644 (lambda (#,type-name val)
1645 (if (eq? (struct-vtable #,type-name) rtd)
1646 (struct-set! #,type-name #,slot val)
1647 (%record-type-error rtd #,type-name))))))
1649 (define (accessors rtd type-name fields n exp)
1650 (syntax-case fields ()
1652 (((field #:no-accessors) field* ...) (identifier? #'field)
1653 (accessors rtd type-name #'(field* ...) (1+ n)
1655 (((field #:no-setter) field* ...) (identifier? #'field)
1656 (accessors rtd type-name #'(field* ...) (1+ n)
1658 #,(getter rtd type-name #'field n))))
1659 (((field #:no-getter) field* ...) (identifier? #'field)
1660 (accessors rtd type-name #'(field* ...) (1+ n)
1662 #,(setter rtd type-name #'field n))))
1663 ((field field* ...) (identifier? #'field)
1664 (accessors rtd type-name #'(field* ...) (1+ n)
1666 #,(getter rtd type-name #'field n)
1667 #,(setter rtd type-name #'field n))))))
1669 (define (predicate rtd type-name fields exp)
1671 rtd type-name fields 0
1674 (define (#,(make-id rtd type-name '?) obj)
1675 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1677 (define (field-list fields)
1678 (syntax-case fields ()
1680 (((f . opts) . rest) (identifier? #'f)
1681 (cons #'f (field-list #'rest)))
1682 ((f . rest) (identifier? #'f)
1683 (cons #'f (field-list #'rest)))))
1685 (define (constructor rtd type-name fields exp)
1686 (let ((ctor (make-id rtd type-name '-constructor))
1687 (args (field-list fields)))
1688 (predicate rtd type-name fields
1693 (make-struct rtd 0 #,@args))))
1694 (struct-set! #,rtd (+ vtable-offset-user 2)
1697 (define (type type-name printer fields)
1698 (define (make-layout)
1699 (let lp ((fields fields) (slots '()))
1700 (syntax-case fields ()
1701 (() (datum->syntax #'here
1703 (apply string-append slots))))
1704 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1706 (let ((rtd (make-id type-name type-name '-type)))
1707 (constructor rtd type-name fields
1710 (make-struct record-type-vtable 0
1714 '#,(field-list fields)))
1715 (set-struct-vtable-name! #,rtd '#,type-name)))))
1718 ((_ type-name printer (field ...))
1719 (type #'type-name #'printer #'(field ...)))))))
1723 ;; A module is characterized by an obarray in which local symbols
1724 ;; are interned, a list of modules, "uses", from which non-local
1725 ;; bindings can be inherited, and an optional lazy-binder which
1726 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1727 ;; bindings that would otherwise not be found locally in the module.
1729 ;; NOTE: If you change the set of fields or their order, you also need to
1730 ;; change the constants in libguile/modules.h.
1732 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1733 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1734 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1736 (define-record-type module
1737 (lambda (obj port) (%print-module obj port))
1742 (transformer #:no-getter)
1746 (import-obarray #:no-setter)
1748 (weak-observers #:no-setter)
1756 ;; make-module &opt size uses binder
1758 ;; Create a new module, perhaps with a particular size of obarray,
1759 ;; initial uses list, or binding procedure.
1761 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
1762 (define %default-import-size
1763 ;; Typical number of imported bindings actually used by a module.
1766 (if (not (integer? size))
1767 (error "Illegal size to make-module." size))
1768 (if (not (and (list? uses)
1769 (and-map module? uses)))
1770 (error "Incorrect use list." uses))
1771 (if (and binder (not (procedure? binder)))
1773 "Lazy-binder expected to be a procedure or #f." binder))
1775 (module-constructor (make-hash-table size)
1776 uses binder #f macroexpand
1778 (make-hash-table %default-import-size)
1780 (make-weak-key-hash-table 31) #f
1781 (make-hash-table 7) #f #f #f))
1786 ;;; {Observer protocol}
1789 (define (module-observe module proc)
1790 (set-module-observers! module (cons proc (module-observers module)))
1793 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1794 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1795 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1796 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1797 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1800 ;; The two-argument version is kept for backward compatibility: when called
1801 ;; with two arguments, the observer gets unregistered when closure PROC
1802 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1803 (hashq-set! (module-weak-observers module) observer-id proc))
1805 (define (module-unobserve token)
1806 (let ((module (car token))
1809 (hash-remove! (module-weak-observers module) id)
1810 (set-module-observers! module (delq1! id (module-observers module)))))
1813 (define module-defer-observers #f)
1814 (define module-defer-observers-mutex (make-mutex 'recursive))
1815 (define module-defer-observers-table (make-hash-table))
1817 (define (module-modified m)
1818 (if module-defer-observers
1819 (hash-set! module-defer-observers-table m #t)
1820 (module-call-observers m)))
1822 ;;; This function can be used to delay calls to observers so that they
1823 ;;; can be called once only in the face of massive updating of modules.
1825 (define (call-with-deferred-observers thunk)
1828 (lock-mutex module-defer-observers-mutex)
1829 (set! module-defer-observers #t))
1832 (set! module-defer-observers #f)
1833 (hash-for-each (lambda (m dummy)
1834 (module-call-observers m))
1835 module-defer-observers-table)
1836 (hash-clear! module-defer-observers-table)
1837 (unlock-mutex module-defer-observers-mutex))))
1839 (define (module-call-observers m)
1840 (for-each (lambda (proc) (proc m)) (module-observers m))
1842 ;; We assume that weak observers don't (un)register themselves as they are
1843 ;; called since this would preclude proper iteration over the hash table
1845 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1849 ;;; {Module Searching in General}
1851 ;;; We sometimes want to look for properties of a symbol
1852 ;;; just within the obarray of one module. If the property
1853 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1854 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1857 ;;; Other times, we want to test for a symbol property in the obarray
1858 ;;; of M and, if it is not found there, try each of the modules in the
1859 ;;; uses list of M. This is the normal way of testing for some
1860 ;;; property, so we state these properties without qualification as
1861 ;;; in: ``The symbol 'fnord is interned in module M because it is
1862 ;;; interned locally in module M2 which is a member of the uses list
1866 ;; module-search fn m
1868 ;; return the first non-#f result of FN applied to M and then to
1869 ;; the modules in the uses of m, and so on recursively. If all applications
1870 ;; return #f, then so does this function.
1872 (define (module-search fn m v)
1875 (or (module-search fn (car pos) v)
1878 (loop (module-uses m))))
1881 ;;; {Is a symbol bound in a module?}
1883 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1884 ;;; of S in M has been set to some well-defined value.
1887 ;; module-locally-bound? module symbol
1889 ;; Is a symbol bound (interned and defined) locally in a given module?
1891 (define (module-locally-bound? m v)
1892 (let ((var (module-local-variable m v)))
1894 (variable-bound? var))))
1896 ;; module-bound? module symbol
1898 ;; Is a symbol bound (interned and defined) anywhere in a given module
1901 (define (module-bound? m v)
1902 (let ((var (module-variable m v)))
1904 (variable-bound? var))))
1906 ;;; {Is a symbol interned in a module?}
1908 ;;; Symbol S in Module M is interned if S occurs in
1909 ;;; of S in M has been set to some well-defined value.
1911 ;;; It is possible to intern a symbol in a module without providing
1912 ;;; an initial binding for the corresponding variable. This is done
1914 ;;; (module-add! module symbol (make-undefined-variable))
1916 ;;; In that case, the symbol is interned in the module, but not
1917 ;;; bound there. The unbound symbol shadows any binding for that
1918 ;;; symbol that might otherwise be inherited from a member of the uses list.
1921 (define (module-obarray-get-handle ob key)
1922 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1924 (define (module-obarray-ref ob key)
1925 ((if (symbol? key) hashq-ref hash-ref) ob key))
1927 (define (module-obarray-set! ob key val)
1928 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1930 (define (module-obarray-remove! ob key)
1931 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1933 ;; module-symbol-locally-interned? module symbol
1935 ;; is a symbol interned (not neccessarily defined) locally in a given module
1936 ;; or its uses? Interned symbols shadow inherited bindings even if
1937 ;; they are not themselves bound to a defined value.
1939 (define (module-symbol-locally-interned? m v)
1940 (not (not (module-obarray-get-handle (module-obarray m) v))))
1942 ;; module-symbol-interned? module symbol
1944 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1945 ;; or its uses? Interned symbols shadow inherited bindings even if
1946 ;; they are not themselves bound to a defined value.
1948 (define (module-symbol-interned? m v)
1949 (module-search module-symbol-locally-interned? m v))
1952 ;;; {Mapping modules x symbols --> variables}
1955 ;; module-local-variable module symbol
1956 ;; return the local variable associated with a MODULE and SYMBOL.
1958 ;;; This function is very important. It is the only function that can
1959 ;;; return a variable from a module other than the mutators that store
1960 ;;; new variables in modules. Therefore, this function is the location
1961 ;;; of the "lazy binder" hack.
1963 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1964 ;;; to a variable, return that variable object.
1966 ;;; If the symbols is not found at first, but the module has a lazy binder,
1967 ;;; then try the binder.
1969 ;;; If the symbol is not found at all, return #f.
1971 ;;; (This is now written in C, see `modules.c'.)
1974 ;;; {Mapping modules x symbols --> bindings}
1976 ;;; These are similar to the mapping to variables, except that the
1977 ;;; variable is dereferenced.
1980 ;; module-symbol-binding module symbol opt-value
1982 ;; return the binding of a variable specified by name within
1983 ;; a given module, signalling an error if the variable is unbound.
1984 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1985 ;; return OPT-VALUE.
1987 (define (module-symbol-local-binding m v . opt-val)
1988 (let ((var (module-local-variable m v)))
1989 (if (and var (variable-bound? var))
1991 (if (not (null? opt-val))
1993 (error "Locally unbound variable." v)))))
1995 ;; module-symbol-binding module symbol opt-value
1997 ;; return the binding of a variable specified by name within
1998 ;; a given module, signalling an error if the variable is unbound.
1999 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2000 ;; return OPT-VALUE.
2002 (define (module-symbol-binding m v . opt-val)
2003 (let ((var (module-variable m v)))
2004 (if (and var (variable-bound? var))
2006 (if (not (null? opt-val))
2008 (error "Unbound variable." v)))))
2013 ;;; {Adding Variables to Modules}
2016 ;; module-make-local-var! module symbol
2018 ;; ensure a variable for V in the local namespace of M.
2019 ;; If no variable was already there, then create a new and uninitialzied
2022 ;; This function is used in modules.c.
2024 (define (module-make-local-var! m v)
2025 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2028 ;; Mark as modified since this function is called when
2029 ;; the standard eval closure defines a binding
2033 ;; Create a new local variable.
2034 (let ((local-var (make-undefined-variable)))
2035 (module-add! m v local-var)
2038 ;; module-ensure-local-variable! module symbol
2040 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2041 ;; there is no binding for SYMBOL, create a new uninitialized
2042 ;; variable. Return the local variable.
2044 (define (module-ensure-local-variable! module symbol)
2045 (or (module-local-variable module symbol)
2046 (let ((var (make-undefined-variable)))
2047 (module-add! module symbol var)
2050 ;; module-add! module symbol var
2052 ;; ensure a particular variable for V in the local namespace of M.
2054 (define (module-add! m v var)
2055 (if (not (variable? var))
2056 (error "Bad variable to module-add!" var))
2057 (module-obarray-set! (module-obarray m) v var)
2058 (module-modified m))
2062 ;; make sure that a symbol is undefined in the local namespace of M.
2064 (define (module-remove! m v)
2065 (module-obarray-remove! (module-obarray m) v)
2066 (module-modified m))
2068 (define (module-clear! m)
2069 (hash-clear! (module-obarray m))
2070 (module-modified m))
2072 ;; MODULE-FOR-EACH -- exported
2074 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2076 (define (module-for-each proc module)
2077 (hash-for-each proc (module-obarray module)))
2079 (define (module-map proc module)
2080 (hash-map->list proc (module-obarray module)))
2084 ;; Modules exist in a separate namespace from values, because you generally do
2085 ;; not want the name of a submodule, which you might not even use, to collide
2086 ;; with local variables that happen to be named the same as the submodule.
2088 (define (module-ref-submodule module name)
2089 (or (hashq-ref (module-submodules module) name)
2090 (and (module-submodule-binder module)
2091 ((module-submodule-binder module) module name))))
2093 (define (module-define-submodule! module name submodule)
2094 (hashq-set! (module-submodules module) name submodule))
2096 ;; It used to be, however, that module names were also present in the
2097 ;; value namespace. When we enable deprecated code, we preserve this
2100 ;; These shims are defined here instead of in deprecated.scm because we
2101 ;; need their definitions before loading other modules.
2104 (define (module-ref-submodule module name)
2105 (or (hashq-ref (module-submodules module) name)
2106 (and (module-submodule-binder module)
2107 ((module-submodule-binder module) module name))
2108 (let ((var (module-local-variable module name)))
2109 (and var (variable-bound? var) (module? (variable-ref var))
2111 (warn "module" module "not in submodules table")
2112 (variable-ref var))))))
2114 (define (module-define-submodule! module name submodule)
2115 (let ((var (module-local-variable module name)))
2117 (or (not (variable-bound? var))
2118 (not (module? (variable-ref var)))))
2119 (warn "defining module" module ": not overriding local definition" var)
2120 (module-define! module name submodule)))
2121 (hashq-set! (module-submodules module) name submodule)))
2125 ;;; {Module-based Loading}
2128 (define (save-module-excursion thunk)
2129 (let ((inner-module (current-module))
2131 (dynamic-wind (lambda ()
2132 (set! outer-module (current-module))
2133 (set-current-module inner-module)
2134 (set! inner-module #f))
2137 (set! inner-module (current-module))
2138 (set-current-module outer-module)
2139 (set! outer-module #f)))))
2143 ;;; {MODULE-REF -- exported}
2146 ;; Returns the value of a variable called NAME in MODULE or any of its
2147 ;; used modules. If there is no such variable, then if the optional third
2148 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2150 (define (module-ref module name . rest)
2151 (let ((variable (module-variable module name)))
2152 (if (and variable (variable-bound? variable))
2153 (variable-ref variable)
2155 (error "No variable named" name 'in module)
2156 (car rest) ; default value
2159 ;; MODULE-SET! -- exported
2161 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2162 ;; to VALUE; if there is no such variable, an error is signaled.
2164 (define (module-set! module name value)
2165 (let ((variable (module-variable module name)))
2167 (variable-set! variable value)
2168 (error "No variable named" name 'in module))))
2170 ;; MODULE-DEFINE! -- exported
2172 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2173 ;; variable, it is added first.
2175 (define (module-define! module name value)
2176 (let ((variable (module-local-variable module name)))
2179 (variable-set! variable value)
2180 (module-modified module))
2181 (let ((variable (make-variable value)))
2182 (module-add! module name variable)))))
2184 ;; MODULE-DEFINED? -- exported
2186 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2189 (define (module-defined? module name)
2190 (let ((variable (module-variable module name)))
2191 (and variable (variable-bound? variable))))
2193 ;; MODULE-USE! module interface
2195 ;; Add INTERFACE to the list of interfaces used by MODULE.
2197 (define (module-use! module interface)
2198 (if (not (or (eq? module interface)
2199 (memq interface (module-uses module))))
2201 ;; Newly used modules must be appended rather than consed, so that
2202 ;; `module-variable' traverses the use list starting from the first
2204 (set-module-uses! module (append (module-uses module)
2206 (hash-clear! (module-import-obarray module))
2207 (module-modified module))))
2209 ;; MODULE-USE-INTERFACES! module interfaces
2211 ;; Same as MODULE-USE!, but only notifies module observers after all
2212 ;; interfaces are added to the inports list.
2214 (define (module-use-interfaces! module interfaces)
2215 (let* ((cur (module-uses module))
2216 (new (let lp ((in interfaces) (out '()))
2220 (let ((iface (car in)))
2221 (if (or (memq iface cur) (memq iface out))
2223 (cons iface out))))))))
2224 (set-module-uses! module (append cur new))
2225 (hash-clear! (module-import-obarray module))
2226 (module-modified module)))
2230 ;;; {Recursive Namespaces}
2232 ;;; A hierarchical namespace emerges if we consider some module to be
2233 ;;; root, and submodules of that module to be nested namespaces.
2235 ;;; The routines here manage variable names in hierarchical namespace.
2236 ;;; Each variable name is a list of elements, looked up in successively nested
2239 ;;; (nested-ref some-root-module '(foo bar baz))
2240 ;;; => <value of a variable named baz in the submodule bar of
2241 ;;; the submodule foo of some-root-module>
2246 ;;; ;; a-root is a module
2247 ;;; ;; name is a list of symbols
2249 ;;; nested-ref a-root name
2250 ;;; nested-set! a-root name val
2251 ;;; nested-define! a-root name val
2252 ;;; nested-remove! a-root name
2254 ;;; These functions manipulate values in namespaces. For referencing the
2255 ;;; namespaces themselves, use the following:
2257 ;;; nested-ref-module a-root name
2258 ;;; nested-define-module! a-root name mod
2260 ;;; (current-module) is a natural choice for a root so for convenience there are
2263 ;;; local-ref name == nested-ref (current-module) name
2264 ;;; local-set! name val == nested-set! (current-module) name val
2265 ;;; local-define name val == nested-define! (current-module) name val
2266 ;;; local-remove name == nested-remove! (current-module) name
2267 ;;; local-ref-module name == nested-ref-module (current-module) name
2268 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2272 (define (nested-ref root names)
2275 (let loop ((cur root)
2279 (module-ref cur head #f)
2280 (let ((cur (module-ref-submodule cur head)))
2282 (loop cur (car tail) (cdr tail))))))))
2284 (define (nested-set! root names val)
2285 (let loop ((cur root)
2289 (module-set! cur head val)
2290 (let ((cur (module-ref-submodule cur head)))
2292 (error "failed to resolve module" names)
2293 (loop cur (car tail) (cdr tail)))))))
2295 (define (nested-define! root names val)
2296 (let loop ((cur root)
2300 (module-define! cur head val)
2301 (let ((cur (module-ref-submodule cur head)))
2303 (error "failed to resolve module" names)
2304 (loop cur (car tail) (cdr tail)))))))
2306 (define (nested-remove! root names)
2307 (let loop ((cur root)
2311 (module-remove! cur head)
2312 (let ((cur (module-ref-submodule cur head)))
2314 (error "failed to resolve module" names)
2315 (loop cur (car tail) (cdr tail)))))))
2318 (define (nested-ref-module root names)
2319 (let loop ((cur root)
2323 (let ((cur (module-ref-submodule cur (car names))))
2325 (loop cur (cdr names)))))))
2327 (define (nested-define-module! root names module)
2329 (error "can't redefine root module" root module)
2330 (let loop ((cur root)
2334 (module-define-submodule! cur head module)
2335 (let ((cur (or (module-ref-submodule cur head)
2336 (let ((m (make-module 31)))
2337 (set-module-kind! m 'directory)
2338 (set-module-name! m (append (module-name cur)
2340 (module-define-submodule! cur head m)
2342 (loop cur (car tail) (cdr tail)))))))
2345 (define (local-ref names)
2346 (nested-ref (current-module) names))
2348 (define (local-set! names val)
2349 (nested-set! (current-module) names val))
2351 (define (local-define names val)
2352 (nested-define! (current-module) names val))
2354 (define (local-remove names)
2355 (nested-remove! (current-module) names))
2357 (define (local-ref-module names)
2358 (nested-ref-module (current-module) names))
2360 (define (local-define-module names mod)
2361 (nested-define-module! (current-module) names mod))
2367 ;;; {The (guile) module}
2369 ;;; The standard module, which has the core Guile bindings. Also called the
2370 ;;; "root module", as it is imported by many other modules, but it is not
2371 ;;; necessarily the root of anything; and indeed, the module named '() might be
2372 ;;; better thought of as a root.
2375 ;; The root module uses the pre-modules-obarray as its obarray. This
2376 ;; special obarray accumulates all bindings that have been established
2377 ;; before the module system is fully booted.
2379 ;; (The obarray continues to be used by code that has been closed over
2380 ;; before the module system has been booted.)
2382 (define the-root-module
2383 (let ((m (make-module 0)))
2384 (set-module-obarray! m (%get-pre-modules-obarray))
2385 (set-module-name! m '(guile))
2388 ;; The root interface is a module that uses the same obarray as the
2389 ;; root module. It does not allow new definitions, tho.
2391 (define the-scm-module
2392 (let ((m (make-module 0)))
2393 (set-module-obarray! m (%get-pre-modules-obarray))
2394 (set-module-name! m '(guile))
2395 (set-module-kind! m 'interface)
2397 ;; In Guile 1.8 and earlier M was its own public interface.
2398 (set-module-public-interface! m m)
2402 (set-module-public-interface! the-root-module the-scm-module)
2406 ;; Now that we have a root module, even though modules aren't fully booted,
2407 ;; expand the definition of resolve-module.
2409 (define (resolve-module name . args)
2410 (if (equal? name '(guile))
2412 (error "unexpected module to resolve during module boot" name)))
2414 ;; Cheat. These bindings are needed by modules.c, but we don't want
2415 ;; to move their real definition here because that would be unnatural.
2417 (define define-module* #f)
2418 (define process-use-modules #f)
2419 (define module-export! #f)
2420 (define default-duplicate-binding-procedures #f)
2422 ;; This boots the module system. All bindings needed by modules.c
2423 ;; must have been defined by now.
2425 (set-current-module the-root-module)
2430 ;; Now that modules are booted, give module-name its final definition.
2433 (let ((accessor (record-accessor module-type 'name)))
2436 (let ((name (list (gensym))))
2437 ;; Name MOD and bind it in the module root so that it's visible to
2438 ;; `resolve-module'. This is important as `psyntax' stores module
2439 ;; names and relies on being able to `resolve-module' them.
2440 (set-module-name! mod name)
2441 (nested-define-module! (resolve-module '() #f) name mod)
2444 (define (make-modules-in module name)
2445 (or (nested-ref-module module name)
2446 (let ((m (make-module 31)))
2447 (set-module-kind! m 'directory)
2448 (set-module-name! m (append (module-name module) name))
2449 (nested-define-module! module name m)
2452 (define (beautify-user-module! module)
2453 (let ((interface (module-public-interface module)))
2454 (if (or (not interface)
2455 (eq? interface module))
2456 (let ((interface (make-module 31)))
2457 (set-module-name! interface (module-name module))
2458 (set-module-version! interface (module-version module))
2459 (set-module-kind! interface 'interface)
2460 (set-module-public-interface! module interface))))
2461 (if (and (not (memq the-scm-module (module-uses module)))
2462 (not (eq? module the-root-module)))
2463 ;; Import the default set of bindings (from the SCM module) in MODULE.
2464 (module-use! module the-scm-module)))
2466 (define (version-matches? version-ref target)
2467 (define (sub-versions-match? v-refs t)
2468 (define (sub-version-matches? v-ref t)
2469 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2471 ((number? v-ref) (eqv? v-ref t))
2474 ((>=) (>= t (cadr v-ref)))
2475 ((<=) (<= t (cadr v-ref)))
2476 ((and) (and-map matches? (cdr v-ref)))
2477 ((or) (or-map matches? (cdr v-ref)))
2478 ((not) (not (matches? (cadr v-ref))))
2479 (else (error "Invalid sub-version reference" v-ref))))
2480 (else (error "Invalid sub-version reference" v-ref)))))
2482 (and (not (null? t))
2483 (sub-version-matches? (car v-refs) (car t))
2484 (sub-versions-match? (cdr v-refs) (cdr t)))))
2486 (let ((matches? (lambda (v) (version-matches? v target))))
2487 (or (null? version-ref)
2488 (case (car version-ref)
2489 ((and) (and-map matches? (cdr version-ref)))
2490 ((or) (or-map matches? (cdr version-ref)))
2491 ((not) (not (matches? (cadr version-ref))))
2492 (else (sub-versions-match? version-ref target))))))
2494 (define (make-fresh-user-module)
2495 (let ((m (make-module)))
2496 (beautify-user-module! m)
2499 ;; NOTE: This binding is used in libguile/modules.c.
2501 (define resolve-module
2502 (let ((root (make-module)))
2503 (set-module-name! root '())
2504 ;; Define the-root-module as '(guile).
2505 (module-define-submodule! root 'guile the-root-module)
2507 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2508 (let ((already (nested-ref-module root name)))
2511 (or (not autoload) (module-public-interface already)))
2512 ;; A hit, a palpable hit.
2514 (not (version-matches? version (module-version already))))
2515 (error "incompatible module version already loaded" name))
2518 ;; Try to autoload the module, and recurse.
2519 (try-load-module name version)
2520 (resolve-module name #f #:ensure ensure))
2522 ;; No module found (or if one was, it had no public interface), and
2523 ;; we're not autoloading. Make an empty module if #:ensure is true.
2526 (make-modules-in root name)))))))))
2529 (define (try-load-module name version)
2530 (try-module-autoload name version))
2532 (define (reload-module m)
2533 "Revisit the source file corresponding to the module @var{m}."
2534 (let ((f (module-filename m)))
2536 (save-module-excursion
2538 ;; Re-set the initial environment, as in try-module-autoload.
2539 (set-current-module (make-fresh-user-module))
2540 (primitive-load-path f)
2542 ;; Though we could guess, we *should* know it.
2543 (error "unknown file name for module" m))))
2545 (define (purify-module! module)
2546 "Removes bindings in MODULE which are inherited from the (guile) module."
2547 (let ((use-list (module-uses module)))
2548 (if (and (pair? use-list)
2549 (eq? (car (last-pair use-list)) the-scm-module))
2550 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2552 ;; Return a module that is an interface to the module designated by
2555 ;; `resolve-interface' takes four keyword arguments:
2557 ;; #:select SELECTION
2559 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2560 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2561 ;; is the name in the used module and SEEN is the name in the using
2562 ;; module. Note that SEEN is also passed through RENAMER, below. The
2563 ;; default is to select all bindings. If you specify no selection but
2564 ;; a renamer, only the bindings that already exist in the used module
2565 ;; are made available in the interface. Bindings that are added later
2566 ;; are not picked up.
2570 ;; BINDINGS is a list of bindings which should not be imported.
2574 ;; PREFIX is a symbol that will be appended to each exported name.
2575 ;; The default is to not perform any renaming.
2577 ;; #:renamer RENAMER
2579 ;; RENAMER is a procedure that takes a symbol and returns its new
2580 ;; name. The default is not perform any renaming.
2582 ;; Signal "no code for module" error if module name is not resolvable
2583 ;; or its public interface is not available. Signal "no binding"
2584 ;; error if selected binding does not exist in the used module.
2586 (define* (resolve-interface name #:key
2591 (symbol-prefix-proc prefix)
2594 (let* ((module (resolve-module name #t version #:ensure #f))
2595 (public-i (and module (module-public-interface module))))
2596 (and (or (not module) (not public-i))
2597 (error "no code for module" name))
2598 (if (and (not select) (null? hide) (eq? renamer identity))
2600 (let ((selection (or select (module-map (lambda (sym var) sym)
2602 (custom-i (make-module 31)))
2603 (set-module-kind! custom-i 'custom-interface)
2604 (set-module-name! custom-i name)
2605 ;; XXX - should use a lazy binder so that changes to the
2606 ;; used module are picked up automatically.
2607 (for-each (lambda (bspec)
2608 (let* ((direct? (symbol? bspec))
2609 (orig (if direct? bspec (car bspec)))
2610 (seen (if direct? bspec (cdr bspec)))
2611 (var (or (module-local-variable public-i orig)
2612 (module-local-variable module orig)
2614 ;; fixme: format manually for now
2616 #f "no binding `~A' in module ~A"
2618 (if (memq orig hide)
2619 (set! hide (delq! orig hide))
2620 (module-add! custom-i
2624 ;; Check that we are not hiding bindings which don't exist
2625 (for-each (lambda (binding)
2626 (if (not (module-local-variable public-i binding))
2629 #f "no binding `~A' to hide in module ~A"
2634 (define (symbol-prefix-proc prefix)
2636 (symbol-append prefix symbol)))
2638 ;; This function is called from "modules.c". If you change it, be
2639 ;; sure to update "modules.c" as well.
2641 (define* (define-module* name
2642 #:key filename pure version (duplicates '())
2643 (imports '()) (exports '()) (replacements '())
2644 (re-exports '()) (autoloads '()) transformer)
2645 (define (list-of pred l)
2647 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2648 (define (valid-export? x)
2649 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2650 (define (valid-autoload? x)
2651 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
2653 (define (resolve-imports imports)
2654 (define (resolve-import import-spec)
2655 (if (list? import-spec)
2656 (apply resolve-interface import-spec)
2657 (error "unexpected use-module specification" import-spec)))
2658 (let lp ((imports imports) (out '()))
2660 ((null? imports) (reverse! out))
2663 (cons (resolve-import (car imports)) out)))
2664 (else (error "unexpected tail of imports list" imports)))))
2666 ;; We could add a #:no-check arg, set by the define-module macro, if
2667 ;; these checks are taking too much time.
2669 (let ((module (resolve-module name #f)))
2670 (beautify-user-module! module)
2672 (set-module-filename! module filename))
2674 (purify-module! module))
2677 (if (not (list-of integer? version))
2678 (error "expected list of integers for version"))
2679 (set-module-version! module version)
2680 (set-module-version! (module-public-interface module) version)))
2681 (let ((imports (resolve-imports imports)))
2682 (call-with-deferred-observers
2685 (module-use-interfaces! module imports))
2686 (if (list-of valid-export? exports)
2688 (module-export! module exports))
2689 (error "expected exports to be a list of symbols or symbol pairs"))
2690 (if (list-of valid-export? replacements)
2691 (if (pair? replacements)
2692 (module-replace! module replacements))
2693 (error "expected replacements to be a list of symbols or symbol pairs"))
2694 (if (list-of valid-export? re-exports)
2695 (if (pair? re-exports)
2696 (module-re-export! module re-exports))
2697 (error "expected re-exports to be a list of symbols or symbol pairs"))
2699 (if (not (null? autoloads))
2700 (apply module-autoload! module autoloads))
2701 ;; Wait until modules have been loaded to resolve duplicates
2703 (if (pair? duplicates)
2704 (let ((handlers (lookup-duplicates-handlers duplicates)))
2705 (set-module-duplicates-handlers! module handlers))))))
2708 (if (and (pair? transformer) (list-of symbol? transformer))
2709 (let ((iface (resolve-interface transformer))
2710 (sym (car (last-pair transformer))))
2711 (set-module-transformer! module (module-ref iface sym)))
2712 (error "expected transformer to be a module name" transformer)))
2714 (run-hook module-defined-hook module)
2717 ;; `module-defined-hook' is a hook that is run whenever a new module
2718 ;; is defined. Its members are called with one argument, the new
2720 (define module-defined-hook (make-hook 1))
2727 (define (make-autoload-interface module name bindings)
2728 (let ((b (lambda (a sym definep)
2729 (and (memq sym bindings)
2730 (let ((i (module-public-interface (resolve-module name))))
2732 (error "missing interface for module" name))
2733 (let ((autoload (memq a (module-uses module))))
2734 ;; Replace autoload-interface with actual interface if
2735 ;; that has not happened yet.
2736 (if (pair? autoload)
2737 (set-car! autoload i)))
2738 (module-local-variable i sym))))))
2739 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2740 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2741 (make-hash-table 0) #f #f #f)))
2743 (define (module-autoload! module . args)
2744 "Have @var{module} automatically load the module named @var{name} when one
2745 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2746 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2747 module '(ice-9 q) '(make-q q-length))}."
2748 (let loop ((args args))
2752 (error "invalid name+binding autoload list" args))
2754 (let ((name (car args))
2755 (bindings (cadr args)))
2756 (module-use! module (make-autoload-interface module
2758 (loop (cddr args)))))))
2763 ;;; {Autoloading modules}
2766 (define autoloads-in-progress '())
2768 ;; This function is called from "modules.c". If you change it, be
2769 ;; sure to update "modules.c" as well.
2771 (define* (try-module-autoload module-name #:optional version)
2772 (let* ((reverse-name (reverse module-name))
2773 (name (symbol->string (car reverse-name)))
2774 (dir-hint-module-name (reverse (cdr reverse-name)))
2775 (dir-hint (apply string-append
2777 (string-append (symbol->string elt) "/"))
2778 dir-hint-module-name))))
2779 (resolve-module dir-hint-module-name #f)
2780 (and (not (autoload-done-or-in-progress? dir-hint name))
2783 (lambda () (autoload-in-progress! dir-hint name))
2785 (with-fluids ((current-reader #f))
2786 (save-module-excursion
2788 ;; The initial environment when loading a module is a fresh
2790 (set-current-module (make-fresh-user-module))
2791 ;; Here we could allow some other search strategy (other than
2792 ;; primitive-load-path), for example using versions encoded
2793 ;; into the file system -- but then we would have to figure
2794 ;; out how to locate the compiled file, do auto-compilation,
2795 ;; etc. Punt for now, and don't use versions when locating
2797 (primitive-load-path (in-vicinity dir-hint name) #f)
2799 (lambda () (set-autoloaded! dir-hint name didit)))
2804 ;;; {Dynamic linking of modules}
2807 (define autoloads-done '((guile . guile)))
2809 (define (autoload-done-or-in-progress? p m)
2810 (let ((n (cons p m)))
2811 (->bool (or (member n autoloads-done)
2812 (member n autoloads-in-progress)))))
2814 (define (autoload-done! p m)
2815 (let ((n (cons p m)))
2816 (set! autoloads-in-progress
2817 (delete! n autoloads-in-progress))
2818 (or (member n autoloads-done)
2819 (set! autoloads-done (cons n autoloads-done)))))
2821 (define (autoload-in-progress! p m)
2822 (let ((n (cons p m)))
2823 (set! autoloads-done
2824 (delete! n autoloads-done))
2825 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2827 (define (set-autoloaded! p m done?)
2829 (autoload-done! p m)
2830 (let ((n (cons p m)))
2831 (set! autoloads-done (delete! n autoloads-done))
2832 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2836 ;;; {Run-time options}
2839 (define-syntax define-option-interface
2841 ((_ (interface (options enable disable) (option-set!)))
2848 (begin (interface arg) (interface))
2851 (apply (lambda (name value documentation)
2853 (let ((len (string-length (symbol->string name))))
2861 (display documentation)
2865 (define (enable . flags)
2866 (interface (append flags (interface)))
2868 (define (disable . flags)
2869 (let ((options (interface)))
2870 (for-each (lambda (flag) (set! options (delq! flag options)))
2874 (define-syntax-rule (option-set! opt val)
2875 (eval-when (eval load compile expand)
2876 (options (append (options) (list 'opt val)))))))))
2878 (define-option-interface
2879 (debug-options-interface
2880 (debug-options debug-enable debug-disable)
2883 (define-option-interface
2884 (read-options-interface
2885 (read-options read-enable read-disable)
2888 (define-option-interface
2889 (print-options-interface
2890 (print-options print-enable print-disable)
2895 ;;; {The Unspecified Value}
2897 ;;; Currently Guile represents unspecified values via one particular value,
2898 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2899 ;;; future if we could replace this with a return of 0 values, though.
2902 (define-syntax *unspecified*
2903 (identifier-syntax (if #f #f)))
2905 (define (unspecified? v) (eq? v *unspecified*))
2914 ;; Three fields: the procedure itself, the fluid, and the converter.
2915 (make-struct <applicable-struct-vtable> 0 'pwprpr))
2916 (set-struct-vtable-name! <parameter> '<parameter>)
2918 (define* (make-parameter init #:optional (conv (lambda (x) x)))
2919 (let ((fluid (make-fluid (conv init))))
2920 (make-struct <parameter> 0
2922 (() (fluid-ref fluid))
2923 ((x) (let ((prev (fluid-ref fluid)))
2924 (fluid-set! fluid (conv x))
2928 (define (parameter? x)
2929 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
2931 (define (parameter-fluid p)
2934 (scm-error 'wrong-type-arg "parameter-fluid"
2935 "Not a parameter: ~S" (list p) #f)))
2937 (define (parameter-converter p)
2940 (scm-error 'wrong-type-arg "parameter-fluid"
2941 "Not a parameter: ~S" (list p) #f)))
2943 (define-syntax parameterize
2946 ((_ ((param value) ...) body body* ...)
2947 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
2948 #'(let ((p param) ...)
2949 (if (not (parameter? p))
2950 (scm-error 'wrong-type-arg "parameterize"
2951 "Not a parameter: ~S" (list p) #f))
2953 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
2955 body body* ...)))))))
2959 ;;; Current ports as parameters.
2962 (let ((fluid->parameter
2963 (lambda (fluid conv)
2964 (make-struct <parameter> 0
2966 (() (fluid-ref fluid))
2967 ((x) (let ((prev (fluid-ref fluid)))
2968 (fluid-set! fluid (conv x))
2971 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
2973 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
2977 (module-remove! (current-module) 'fluid)))
2979 (port-parameterize! current-input-port %current-input-port-fluid
2980 input-port? "expected an input port")
2981 (port-parameterize! current-output-port %current-output-port-fluid
2982 output-port? "expected an output port")
2983 (port-parameterize! current-error-port %current-error-port-fluid
2984 output-port? "expected an output port"))
2992 (define current-warning-port
2993 (make-parameter (current-error-port)
2995 (if (output-port? x)
2997 (error "expected an output port" x)))))
3005 (define *repl-stack* (make-fluid '()))
3007 ;; Programs can call `batch-mode?' to see if they are running as part of a
3008 ;; script or if they are running interactively. REPL implementations ensure that
3009 ;; `batch-mode?' returns #f during their extent.
3011 (define (batch-mode?)
3012 (null? (fluid-ref *repl-stack*)))
3014 ;; Programs can re-enter batch mode, for example after a fork, by calling
3015 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3016 ;; to abort to the outermost prompt, and call a thunk there.
3018 (define (ensure-batch-mode!)
3019 (set! batch-mode? (lambda () #t)))
3021 (define (quit . args)
3022 (apply throw 'quit args))
3026 (define (gc-run-time)
3027 (cdr (assq 'gc-time-taken (gc-stats))))
3029 (define abort-hook (make-hook))
3030 (define before-error-hook (make-hook))
3031 (define after-error-hook (make-hook))
3032 (define before-backtrace-hook (make-hook))
3033 (define after-backtrace-hook (make-hook))
3035 (define before-read-hook (make-hook))
3036 (define after-read-hook (make-hook))
3037 (define before-eval-hook (make-hook 1))
3038 (define after-eval-hook (make-hook 1))
3039 (define before-print-hook (make-hook 1))
3040 (define after-print-hook (make-hook 1))
3042 ;;; This hook is run at the very end of an interactive session.
3044 (define exit-hook (make-hook))
3046 ;;; The default repl-reader function. We may override this if we've
3047 ;;; the readline library.
3049 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3050 (if (not (char-ready?))
3052 (display (if (string? prompt) prompt (prompt)))
3053 ;; An interesting situation. The printer resets the column to
3054 ;; 0 by printing a newline, but we then advance it by printing
3055 ;; the prompt. However the port-column of the output port
3056 ;; does not typically correspond with the actual column on the
3057 ;; screen, because the input is echoed back! Since the
3058 ;; input is line-buffered and thus ends with a newline, the
3059 ;; output will really start on column zero. So, here we zero
3060 ;; it out. See bug 9664.
3062 ;; Note that for similar reasons, the output-line will not
3063 ;; reflect the actual line on the screen. But given the
3064 ;; possibility of multiline input, the fix is not as
3065 ;; straightforward, so we don't bother.
3067 ;; Also note that the readline implementation papers over
3068 ;; these concerns, because it's readline itself printing the
3069 ;; prompt, and not Guile.
3070 (set-port-column! (current-output-port) 0)))
3072 (run-hook before-read-hook)
3073 ((or reader read) (current-input-port))))
3078 ;;; {IOTA functions: generating lists of numbers}
3082 (let loop ((count (1- n)) (result '()))
3083 (if (< count 0) result
3084 (loop (1- count) (cons count result)))))
3090 ;;; with `continue' and `break'.
3093 ;; The inliner will remove the prompts at compile-time if it finds that
3094 ;; `continue' or `break' are not used.
3096 (define-syntax while
3099 ((while cond body ...)
3100 #`(let ((break-tag (make-prompt-tag "break"))
3101 (continue-tag (make-prompt-tag "continue")))
3105 (define-syntax #,(datum->syntax #'while 'break)
3109 #'(abort-to-prompt break-tag arg (... ...)))
3112 (apply abort-to-prompt break-tag args))))))
3117 (define-syntax #,(datum->syntax #'while 'continue)
3121 #'(abort-to-prompt continue-tag))
3123 (syntax-violation 'continue "too many arguments" x))
3126 (abort-to-prompt continue-tag))))))
3127 (do () ((not cond) #f) body ...))
3128 (lambda (k) (lp)))))
3132 (apply values args)))))))))
3137 ;;; {Module System Macros}
3140 ;; Return a list of expressions that evaluate to the appropriate
3141 ;; arguments for resolve-interface according to SPEC.
3143 (eval-when (compile)
3144 (if (memq 'prefix (read-options))
3145 (error "boot-9 must be compiled with #:kw, not :kw")))
3147 (define (keyword-like-symbol->keyword sym)
3148 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3150 (define-syntax define-module
3152 (define (keyword-like? stx)
3153 (let ((dat (syntax->datum stx)))
3155 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3156 (define (->keyword sym)
3157 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3159 (define (parse-iface args)
3160 (let loop ((in args) (out '()))
3163 ;; The user wanted #:foo, but wrote :foo. Fix it.
3164 ((sym . in) (keyword-like? #'sym)
3165 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3166 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3167 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3168 ((#:renamer renamer . in)
3169 (loop #'in (cons* #',renamer #:renamer out)))
3171 (loop #'in (cons* #'val #'kw out))))))
3173 (define (parse args imp exp rex rep aut)
3174 ;; Just quote everything except #:use-module and #:use-syntax. We
3175 ;; need to know about all arguments regardless since we want to turn
3176 ;; symbols that look like keywords into real keywords, and the
3177 ;; keyword args in a define-module form are not regular
3178 ;; (i.e. no-backtrace doesn't take a value).
3179 (syntax-case args ()
3181 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3182 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3183 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3184 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3185 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3186 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3187 ;; The user wanted #:foo, but wrote :foo. Fix it.
3188 ((sym . args) (keyword-like? #'sym)
3189 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3190 imp exp rex rep aut))
3191 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3192 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3193 ((#:no-backtrace . args)
3195 (parse #'args imp exp rex rep aut))
3197 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3199 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3200 ((#:version (v ...) . args)
3201 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3202 ((#:duplicates (d ...) . args)
3203 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3204 ((#:filename f . args)
3205 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3206 ((#:use-module (name name* ...) . args)
3207 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3208 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3209 ((#:use-syntax (name name* ...) . args)
3210 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3211 #`(#:transformer '(name name* ...)
3212 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3213 ((#:use-module ((name name* ...) arg ...) . args)
3214 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3216 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3218 ((#:export (ex ...) . args)
3219 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3220 ((#:export-syntax (ex ...) . args)
3221 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3222 ((#:re-export (re ...) . args)
3223 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3224 ((#:re-export-syntax (re ...) . args)
3225 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3226 ((#:replace (r ...) . args)
3227 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3228 ((#:replace-syntax (r ...) . args)
3229 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3230 ((#:autoload name bindings . args)
3231 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3233 (syntax-violation 'define-module "unknown keyword or bad argument"
3237 ((_ (name name* ...) arg ...)
3238 (and-map symbol? (syntax->datum #'(name name* ...)))
3239 (with-syntax (((quoted-arg ...)
3240 (parse #'(arg ...) '() '() '() '() '()))
3241 ;; Ideally the filename is either a string or #f;
3242 ;; this hack is to work around a case in which
3243 ;; port-filename returns a symbol (`socket') for
3245 (filename (let ((f (assq-ref (or (syntax-source x) '())
3247 (and (string? f) f))))
3248 #'(eval-when (eval load compile expand)
3249 (let ((m (define-module* '(name name* ...)
3250 #:filename filename quoted-arg ...)))
3251 (set-current-module m)
3254 ;; The guts of the use-modules macro. Add the interfaces of the named
3255 ;; modules to the use-list of the current module, in order.
3257 ;; This function is called by "modules.c". If you change it, be sure
3258 ;; to change scm_c_use_module as well.
3260 (define (process-use-modules module-interface-args)
3261 (let ((interfaces (map (lambda (mif-args)
3262 (or (apply resolve-interface mif-args)
3263 (error "no such module" mif-args)))
3264 module-interface-args)))
3265 (call-with-deferred-observers
3267 (module-use-interfaces! (current-module) interfaces)))))
3269 (define-syntax use-modules
3271 (define (keyword-like? stx)
3272 (let ((dat (syntax->datum stx)))
3274 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3275 (define (->keyword sym)
3276 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3278 (define (quotify-iface args)
3279 (let loop ((in args) (out '()))
3282 ;; The user wanted #:foo, but wrote :foo. Fix it.
3283 ((sym . in) (keyword-like? #'sym)
3284 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3285 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3286 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3287 ((#:renamer renamer . in)
3288 (loop #'in (cons* #'renamer #:renamer out)))
3290 (loop #'in (cons* #''val #'kw out))))))
3292 (define (quotify specs)
3293 (let lp ((in specs) (out '()))
3296 (((name name* ...) . in)
3297 (and-map symbol? (syntax->datum #'(name name* ...)))
3298 (lp #'in (cons #''((name name* ...)) out)))
3299 ((((name name* ...) arg ...) . in)
3300 (and-map symbol? (syntax->datum #'(name name* ...)))
3301 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3302 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3307 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3308 #'(eval-when (eval load compile expand)
3309 (process-use-modules (list quoted-args ...))
3312 (define-syntax-rule (use-syntax spec ...)
3314 (eval-when (eval load compile expand)
3315 (issue-deprecation-warning
3316 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3317 (use-modules spec ...)))
3319 (include-from-path "ice-9/r6rs-libraries")
3321 (define-syntax-rule (define-private foo bar)
3324 (define-syntax define-public
3326 ((_ (name . args) . body)
3328 (define name (lambda args . body))
3335 (define-syntax-rule (defmacro-public name args body ...)
3337 (defmacro name args body ...)
3338 (export-syntax name)))
3340 ;; And now for the most important macro.
3341 (define-syntax-rule (λ formals body ...)
3342 (lambda formals body ...))
3345 ;; Export a local variable
3347 ;; This function is called from "modules.c". If you change it, be
3348 ;; sure to update "modules.c" as well.
3350 (define (module-export! m names)
3351 (let ((public-i (module-public-interface m)))
3352 (for-each (lambda (name)
3353 (let* ((internal-name (if (pair? name) (car name) name))
3354 (external-name (if (pair? name) (cdr name) name))
3355 (var (module-ensure-local-variable! m internal-name)))
3356 (module-add! public-i external-name var)))
3359 (define (module-replace! m names)
3360 (let ((public-i (module-public-interface m)))
3361 (for-each (lambda (name)
3362 (let* ((internal-name (if (pair? name) (car name) name))
3363 (external-name (if (pair? name) (cdr name) name))
3364 (var (module-ensure-local-variable! m internal-name)))
3365 ;; FIXME: use a bit on variables instead of object
3367 (set-object-property! var 'replace #t)
3368 (module-add! public-i external-name var)))
3371 ;; Export all local variables from a module
3373 (define (module-export-all! mod)
3374 (define (fresh-interface!)
3375 (let ((iface (make-module)))
3376 (set-module-name! iface (module-name mod))
3377 (set-module-version! iface (module-version mod))
3378 (set-module-kind! iface 'interface)
3379 (set-module-public-interface! mod iface)
3381 (let ((iface (or (module-public-interface mod)
3382 (fresh-interface!))))
3383 (set-module-obarray! iface (module-obarray mod))))
3385 ;; Re-export a imported variable
3387 (define (module-re-export! m names)
3388 (let ((public-i (module-public-interface m)))
3389 (for-each (lambda (name)
3390 (let* ((internal-name (if (pair? name) (car name) name))
3391 (external-name (if (pair? name) (cdr name) name))
3392 (var (module-variable m internal-name)))
3394 (error "Undefined variable:" internal-name))
3395 ((eq? var (module-local-variable m internal-name))
3396 (error "re-exporting local variable:" internal-name))
3398 (module-add! public-i external-name var)))))
3401 (define-syntax-rule (export name ...)
3402 (eval-when (eval load compile expand)
3403 (call-with-deferred-observers
3405 (module-export! (current-module) '(name ...))))))
3407 (define-syntax-rule (re-export name ...)
3408 (eval-when (eval load compile expand)
3409 (call-with-deferred-observers
3411 (module-re-export! (current-module) '(name ...))))))
3413 (define-syntax-rule (export! name ...)
3414 (eval-when (eval load compile expand)
3415 (call-with-deferred-observers
3417 (module-replace! (current-module) '(name ...))))))
3419 (define-syntax-rule (export-syntax name ...)
3422 (define-syntax-rule (re-export-syntax name ...)
3423 (re-export name ...))
3430 (define* (make-mutable-parameter init #:optional (converter identity))
3431 (let ((fluid (make-fluid (converter init))))
3433 (() (fluid-ref fluid))
3434 ((val) (fluid-set! fluid (converter val))))))
3439 ;;; {Handling of duplicate imported bindings}
3442 ;; Duplicate handlers take the following arguments:
3444 ;; module importing module
3445 ;; name conflicting name
3446 ;; int1 old interface where name occurs
3447 ;; val1 value of binding in old interface
3448 ;; int2 new interface where name occurs
3449 ;; val2 value of binding in new interface
3450 ;; var previous resolution or #f
3451 ;; val value of previous resolution
3453 ;; A duplicate handler can take three alternative actions:
3455 ;; 1. return #f => leave responsibility to next handler
3456 ;; 2. exit with an error
3457 ;; 3. return a variable resolving the conflict
3460 (define duplicate-handlers
3461 (let ((m (make-module 7)))
3463 (define (check module name int1 val1 int2 val2 var val)
3464 (scm-error 'misc-error
3466 "~A: `~A' imported from both ~A and ~A"
3467 (list (module-name module)
3473 (define (warn module name int1 val1 int2 val2 var val)
3474 (format (current-warning-port)
3475 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3476 (module-name module)
3482 (define (replace module name int1 val1 int2 val2 var val)
3483 (let ((old (or (and var (object-property var 'replace) var)
3484 (module-variable int1 name)))
3485 (new (module-variable int2 name)))
3486 (if (object-property old 'replace)
3487 (and (or (eq? old new)
3488 (not (object-property new 'replace)))
3490 (and (object-property new 'replace)
3493 (define (warn-override-core module name int1 val1 int2 val2 var val)
3494 (and (eq? int1 the-scm-module)
3496 (format (current-warning-port)
3497 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3498 (module-name module)
3501 (module-local-variable int2 name))))
3503 (define (first module name int1 val1 int2 val2 var val)
3504 (or var (module-local-variable int1 name)))
3506 (define (last module name int1 val1 int2 val2 var val)
3507 (module-local-variable int2 name))
3509 (define (noop module name int1 val1 int2 val2 var val)
3512 (set-module-name! m 'duplicate-handlers)
3513 (set-module-kind! m 'interface)
3514 (module-define! m 'check check)
3515 (module-define! m 'warn warn)
3516 (module-define! m 'replace replace)
3517 (module-define! m 'warn-override-core warn-override-core)
3518 (module-define! m 'first first)
3519 (module-define! m 'last last)
3520 (module-define! m 'merge-generics noop)
3521 (module-define! m 'merge-accessors noop)
3524 (define (lookup-duplicates-handlers handler-names)
3526 (map (lambda (handler-name)
3527 (or (module-symbol-local-binding
3528 duplicate-handlers handler-name #f)
3529 (error "invalid duplicate handler name:"
3531 (if (list? handler-names)
3533 (list handler-names)))))
3535 (define default-duplicate-binding-procedures
3536 (make-mutable-parameter #f))
3538 (define default-duplicate-binding-handler
3539 (make-mutable-parameter '(replace warn-override-core warn last)
3540 (lambda (handler-names)
3541 (default-duplicate-binding-procedures
3542 (lookup-duplicates-handlers handler-names))
3549 ;;; Load is tricky when combined with relative paths, compilation, and
3550 ;;; the file system. If a path is relative, what is it relative to? The
3551 ;;; path of the source file at the time it was compiled? The path of
3552 ;;; the compiled file? What if both or either were installed? And how
3553 ;;; do you get that information? Tricky, I say.
3555 ;;; To get around all of this, we're going to do something nasty, and
3556 ;;; turn `load' into a macro. That way it can know the path of the
3557 ;;; source file with respect to which it was invoked, so it can resolve
3558 ;;; relative paths with respect to the original source path.
3560 ;;; There is an exception, and that is that if the source file was in
3561 ;;; the load path when it was compiled, instead of looking up against
3562 ;;; the absolute source location, we load-from-path against the relative
3563 ;;; source location.
3566 (define %auto-compilation-options
3567 ;; Default `compile-file' option when auto-compiling.
3568 '(#:warnings (unbound-variable arity-mismatch format)))
3570 (define* (load-in-vicinity dir path #:optional reader)
3571 (define (canonical->suffix canon)
3573 ((string-prefix? "/" canon) canon)
3574 ((and (> (string-length canon) 2)
3575 (eqv? (string-ref canon 1) #\:))
3576 ;; Paths like C:... transform to /C...
3577 (string-append "/" (substring canon 0 1) (substring canon 2)))
3580 ;; Returns the .go file corresponding to `name'. Does not search load
3581 ;; paths, only the fallback path. If the .go file is missing or out of
3582 ;; date, and auto-compilation is enabled, will try auto-compilation, just
3583 ;; as primitive-load-path does internally. primitive-load is
3584 ;; unaffected. Returns #f if auto-compilation failed or was disabled.
3586 ;; NB: Unless we need to compile the file, this function should not cause
3587 ;; (system base compile) to be loaded up. For that reason compiled-file-name
3588 ;; partially duplicates functionality from (system base compile).
3590 (define (compiled-file-name canon-path)
3591 ;; FIXME: would probably be better just to append SHA1(canon-path)
3592 ;; to the %compile-fallback-path, to avoid deep directory stats.
3593 (and %compile-fallback-path
3595 %compile-fallback-path
3596 (canonical->suffix canon-path)
3597 (cond ((or (null? %load-compiled-extensions)
3598 (string-null? (car %load-compiled-extensions)))
3599 (warn "invalid %load-compiled-extensions"
3600 %load-compiled-extensions)
3602 (else (car %load-compiled-extensions))))))
3604 (define (fresh-compiled-file-name name go-path)
3607 (let* ((scmstat (stat name))
3608 (gostat (and (not %fresh-auto-compile)
3609 (stat go-path #f))))
3611 (or (> (stat:mtime gostat) (stat:mtime scmstat))
3612 (and (= (stat:mtime gostat) (stat:mtime scmstat))
3613 (>= (stat:mtimensec gostat)
3614 (stat:mtimensec scmstat)))))
3618 (format (current-warning-port)
3619 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
3622 (%load-should-auto-compile
3623 (%warn-auto-compilation-enabled)
3624 (format (current-warning-port) ";;; compiling ~a\n" name)
3627 (resolve-interface '(system base compile))
3630 #:opts %auto-compilation-options
3631 #:env (current-module))))
3632 (format (current-warning-port) ";;; compiled ~a\n" cfn)
3636 (format (current-warning-port)
3637 ";;; WARNING: compilation of ~a failed:\n" name)
3638 (for-each (lambda (s)
3639 (if (not (string-null? s))
3640 (format (current-warning-port) ";;; ~a\n" s)))
3642 (call-with-output-string
3643 (lambda (port) (print-exception port #f k args)))
3647 (define (absolute-path? path)
3648 (string-prefix? "/" path))
3650 (define (load-absolute abs-path)
3651 (let ((cfn (let ((canon (false-if-exception (canonicalize-path abs-path))))
3653 (let ((go-path (compiled-file-name canon)))
3655 (fresh-compiled-file-name abs-path go-path)))))))
3659 (%load-hook abs-path))
3660 (load-compiled cfn))
3661 (start-stack 'load-stack
3662 (primitive-load abs-path)))))
3664 (save-module-excursion
3666 (with-fluids ((current-reader reader)
3667 (%file-port-name-canonicalization 'relative))
3669 ((or (absolute-path? path))
3670 (load-absolute path))
3671 ((absolute-path? dir)
3672 (load-absolute (in-vicinity dir path)))
3674 (load-from-path (in-vicinity dir path))))))))
3677 (make-variable-transformer
3679 (let* ((src (syntax-source x))
3680 (file (and src (assq-ref src 'filename)))
3681 (dir (and (string? file) (dirname file))))
3684 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
3688 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
3692 ;;; {`cond-expand' for SRFI-0 support.}
3694 ;;; This syntactic form expands into different commands or
3695 ;;; definitions, depending on the features provided by the Scheme
3701 ;;; --> (cond-expand <cond-expand-clause>+)
3702 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3703 ;;; <cond-expand-clause>
3704 ;;; --> (<feature-requirement> <command-or-definition>*)
3705 ;;; <feature-requirement>
3706 ;;; --> <feature-identifier>
3707 ;;; | (and <feature-requirement>*)
3708 ;;; | (or <feature-requirement>*)
3709 ;;; | (not <feature-requirement>)
3710 ;;; <feature-identifier>
3711 ;;; --> <a symbol which is the name or alias of a SRFI>
3713 ;;; Additionally, this implementation provides the
3714 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3715 ;;; determine the implementation type and the supported standard.
3717 ;;; Currently, the following feature identifiers are supported:
3719 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61 srfi-105
3721 ;;; Remember to update the features list when adding more SRFIs.
3724 (define %cond-expand-features
3725 ;; Adjust the above comment when changing this.
3729 srfi-0 ;; cond-expand itself
3730 srfi-4 ;; homogenous numeric vectors
3731 srfi-6 ;; open-input-string etc, in the guile core
3732 srfi-13 ;; string library
3733 srfi-14 ;; character sets
3734 srfi-23 ;; `error` procedure
3735 srfi-39 ;; parameterize
3736 srfi-55 ;; require-extension
3737 srfi-61 ;; general cond clause
3738 srfi-105 ;; curly infix expressions
3741 ;; This table maps module public interfaces to the list of features.
3743 (define %cond-expand-table (make-hash-table 31))
3745 ;; Add one or more features to the `cond-expand' feature list of the
3748 (define (cond-expand-provide module features)
3749 (let ((mod (module-public-interface module)))
3751 (hashq-set! %cond-expand-table mod
3752 (append (hashq-ref %cond-expand-table mod '())
3755 (define-syntax cond-expand
3757 (define (module-has-feature? mod sym)
3758 (or-map (lambda (mod)
3759 (memq sym (hashq-ref %cond-expand-table mod '())))
3762 (define (condition-matches? condition)
3763 (syntax-case condition (and or not)
3765 (and-map condition-matches? #'(c ...)))
3767 (or-map condition-matches? #'(c ...)))
3769 (if (condition-matches? #'c) #f #t))
3772 (let ((sym (syntax->datum #'c)))
3773 (if (memq sym %cond-expand-features)
3775 (module-has-feature? (current-module) sym))))))
3777 (define (match clauses alternate)
3778 (syntax-case clauses ()
3779 (((condition form ...) . rest)
3780 (if (condition-matches? #'condition)
3782 (match #'rest alternate)))
3785 (syntax-case x (else)
3786 ((_ clause ... (else form ...))
3787 (match #'(clause ...)
3789 #'(begin form ...))))
3791 (match #'(clause ...)
3793 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
3795 ;; This procedure gets called from the startup code with a list of
3796 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3798 (define (use-srfis srfis)
3799 (process-use-modules
3801 (list (list 'srfi (string->symbol
3802 (string-append "srfi-" (number->string num))))))
3807 ;;; srfi-55: require-extension
3810 (define-syntax require-extension
3812 (syntax-case x (srfi)
3814 (and-map integer? (syntax->datum #'(n ...)))
3818 (datum->syntax x (symbol-append 'srfi- n)))
3820 (map number->string (syntax->datum #'(n ...)))))))
3821 #'(use-modules (srfi srfi-n) ...)))
3823 (identifier? #'type)
3824 (syntax-violation 'require-extension "Not a recognized extension type"
3828 ;;; Defining transparently inlinable procedures
3831 (define-syntax define-inlinable
3832 ;; Define a macro and a procedure such that direct calls are inlined, via
3833 ;; the macro expansion, whereas references in non-call contexts refer to
3834 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
3836 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
3838 (define prefix (string->symbol "% "))
3839 (define (make-procedure-name name)
3841 (symbol-append prefix (syntax->datum name)
3845 ((_ (name formals ...) body ...)
3846 (identifier? #'name)
3847 (with-syntax ((proc-name (make-procedure-name #'name))
3848 ((args ...) (generate-temporaries #'(formals ...))))
3850 (define (proc-name formals ...)
3851 (syntax-parameterize ((name (identifier-syntax proc-name)))
3853 (define-syntax-parameter name
3857 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
3858 (lambda (formals ...)
3863 #'proc-name))))))))))
3867 (define using-readline?
3868 (let ((using-readline? (make-fluid)))
3869 (make-procedure-with-setter
3870 (lambda () (fluid-ref using-readline?))
3871 (lambda (v) (fluid-set! using-readline? v)))))
3875 ;;; {Deprecated stuff}
3879 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3883 ;;; SRFI-4 in the default environment. FIXME: we should figure out how
3884 ;;; to deprecate this.
3888 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3892 ;;; A few identifiers that need to be defined in this file are really
3893 ;;; internal implementation details. We shove them off into internal
3894 ;;; modules, removing them from the (guile) module.
3897 (define-module (system syntax))
3900 (define (steal-bindings! from to ids)
3903 (let ((v (module-local-variable from sym)))
3904 (module-remove! from sym)
3905 (module-add! to sym v)))
3907 (module-export! to ids))
3909 (steal-bindings! the-root-module (resolve-module '(system syntax))
3910 '(syntax-local-binding
3912 syntax-locally-bound-identifiers
3913 syntax-session-id)))
3918 ;;; Place the user in the guile-user module.
3921 ;; Set filename to #f to prevent reload.
3922 (define-module (guile-user)
3923 #:autoload (system base compile) (compile compile-file)
3926 ;; Remain in the `(guile)' module at compilation-time so that the
3927 ;; `-Wunused-toplevel' warning works as expected.
3928 (eval-when (compile) (set-current-module the-root-module))
3930 ;;; boot-9.scm ends here