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 (procedure-name proc) proc))))
785 (print-location frame port)
788 (let ((printer (assq-ref exception-printers key)))
790 (printer port key args default-printer)
793 (format port "Error while printing exception.")))
795 (force-output port))))
798 ;;; Printers for those keys thrown by Guile.
801 (define (scm-error-printer port key args default-printer)
802 ;; Abuse case-lambda as a pattern matcher, given that we don't have
803 ;; ice-9 match at this point.
805 ((subr msg args . rest)
807 (format port "In procedure ~a: " subr))
808 (apply format port msg (or args '())))
809 (_ (default-printer)))
812 (define (syntax-error-printer port key args default-printer)
814 ((who what where form subform . extra)
815 (format port "Syntax error:\n")
817 (let ((file (or (assq-ref where 'filename) "unknown file"))
818 (line (and=> (assq-ref where 'line) 1+))
819 (col (assq-ref where 'column)))
820 (format port "~a:~a:~a: " file line col))
821 (format port "unknown location: "))
823 (format port "~a: " who))
824 (format port "~a" what)
826 (format port " in subform ~s of ~s" subform form)
828 (format port " in form ~s" form))))
829 (_ (default-printer)))
832 (define (getaddrinfo-error-printer port key args default-printer)
833 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
835 (set-exception-printer! 'goops-error scm-error-printer)
836 (set-exception-printer! 'host-not-found scm-error-printer)
837 (set-exception-printer! 'keyword-argument-error scm-error-printer)
838 (set-exception-printer! 'misc-error scm-error-printer)
839 (set-exception-printer! 'no-data scm-error-printer)
840 (set-exception-printer! 'no-recovery scm-error-printer)
841 (set-exception-printer! 'null-pointer-error scm-error-printer)
842 (set-exception-printer! 'out-of-range scm-error-printer)
843 (set-exception-printer! 'program-error scm-error-printer)
844 (set-exception-printer! 'read-error scm-error-printer)
845 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
846 (set-exception-printer! 'signal scm-error-printer)
847 (set-exception-printer! 'stack-overflow scm-error-printer)
848 (set-exception-printer! 'system-error scm-error-printer)
849 (set-exception-printer! 'try-again scm-error-printer)
850 (set-exception-printer! 'unbound-variable scm-error-printer)
851 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
852 (set-exception-printer! 'wrong-type-arg scm-error-printer)
854 (set-exception-printer! 'syntax-error syntax-error-printer)
856 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
864 (define-syntax define-macro
868 ((_ (macro . args) doc body1 body ...)
869 (string? (syntax->datum #'doc))
870 #'(define-macro macro doc (lambda args body1 body ...)))
871 ((_ (macro . args) body ...)
872 #'(define-macro macro #f (lambda args body ...)))
873 ((_ macro doc transformer)
874 (or (string? (syntax->datum #'doc))
875 (not (syntax->datum #'doc)))
876 #'(define-syntax macro
879 #((macro-type . defmacro)
880 (defmacro-args args))
883 (let ((v (syntax->datum #'args)))
884 (datum->syntax y (apply transformer v)))))))))))
886 (define-syntax defmacro
888 "Define a defmacro, with the old lispy defun syntax."
890 ((_ macro args doc body1 body ...)
891 (string? (syntax->datum #'doc))
892 #'(define-macro macro doc (lambda args body1 body ...)))
893 ((_ macro args body ...)
894 #'(define-macro macro #f (lambda args body ...))))))
903 (define-syntax begin-deprecated
907 (if (include-deprecated-features)
908 #'(begin form form* ...)
913 ;;; {Trivial Functions}
916 (define (identity x) x)
918 (define (compose proc . rest)
919 "Compose PROC with the procedures in REST, such that the last one in
920 REST is applied first and PROC last, and return the resulting procedure.
921 The given procedures must have compatible arity."
924 (let ((g (apply compose rest)))
926 (call-with-values (lambda () (apply g args)) proc)))))
928 (define (negate proc)
929 "Return a procedure with the same arity as PROC that returns the `not'
932 (not (apply proc args))))
934 (define (const value)
935 "Return a procedure that accepts any number of arguments and returns
940 (define (and=> value procedure) (and value (procedure value)))
941 (define call/cc call-with-current-continuation)
943 (define-syntax-rule (false-if-exception expr)
946 (lambda (k . args) #f)))
950 ;;; {General Properties}
953 ;; Properties are a lispy way to associate random info with random objects.
954 ;; Traditionally properties are implemented as an alist or a plist actually
955 ;; pertaining to the object in question.
957 ;; These "object properties" have the advantage that they can be associated with
958 ;; any object, even if the object has no plist. Object properties are good when
959 ;; you are extending pre-existing objects in unexpected ways. They also present
960 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
961 ;; type that always has properties, it's often still best to store those
962 ;; properties within the object itself.
964 (define (make-object-property)
965 ;; Weak tables are thread-safe.
966 (let ((prop (make-weak-key-hash-table)))
967 (make-procedure-with-setter
968 (lambda (obj) (hashq-ref prop obj))
969 (lambda (obj val) (hashq-set! prop obj val)))))
974 ;;; {Symbol Properties}
977 ;;; Symbol properties are something you see in old Lisp code. In most current
978 ;;; Guile code, symbols are not used as a data structure -- they are used as
979 ;;; keys into other data structures.
981 (define (symbol-property sym prop)
982 (let ((pair (assoc prop (symbol-pref sym))))
983 (and pair (cdr pair))))
985 (define (set-symbol-property! sym prop val)
986 (let ((pair (assoc prop (symbol-pref sym))))
989 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
991 (define (symbol-property-remove! sym prop)
992 (let ((pair (assoc prop (symbol-pref sym))))
994 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
1001 (define (array-shape a)
1002 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1003 (array-dimensions a)))
1010 ;;; It's much better if you can use lambda* / define*, of course.
1012 (define (kw-arg-ref args kw)
1013 (let ((rem (member kw args)))
1014 (and rem (pair? (cdr rem)) (cadr rem))))
1021 (define (struct-layout s)
1022 (struct-ref (struct-vtable s) vtable-index-layout))
1029 ;; Printing records: by default, records are printed as
1031 ;; #<type-name field1: val1 field2: val2 ...>
1033 ;; You can change that by giving a custom printing function to
1034 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1035 ;; will be called like
1037 ;; (<printer> object port)
1039 ;; It should print OBJECT to PORT.
1041 (define (inherit-print-state old-port new-port)
1042 (if (get-print-state old-port)
1043 (port-with-print-state new-port (get-print-state old-port))
1046 ;; 0: type-name, 1: fields, 2: constructor
1047 (define record-type-vtable
1048 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1050 (display "#<record-type " p)
1051 (display (record-type-name s) p)
1053 (set-struct-vtable-name! s 'record-type)
1056 (define (record-type? obj)
1057 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1059 (define* (make-record-type type-name fields #:optional printer)
1060 ;; Pre-generate constructors for nfields < 20.
1061 (define-syntax make-constructor
1063 (define *max-static-argument-count* 20)
1064 (define (make-formals n)
1067 (cons (datum->syntax
1070 (string (integer->char (+ (char->integer #\a) i)))))
1074 ((_ rtd exp) (not (identifier? #'exp))
1076 (make-constructor rtd n)))
1080 (if (< n *max-static-argument-count*)
1081 (cons (with-syntax (((formal ...) (make-formals n))
1084 (lambda (formal ...)
1085 (make-struct rtd 0 formal ...))))
1090 (if (= (length args) nfields)
1091 (apply make-struct rtd 0 args)
1092 (scm-error 'wrong-number-of-args
1093 (format #f "make-~a" type-name)
1094 "Wrong number of arguments" '() #f)))))))))
1096 (define (default-record-printer s p)
1098 (display (record-type-name (record-type-descriptor s)) p)
1099 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1102 ((not (null? fields))
1104 (display (car fields) p)
1106 (display (struct-ref s off) p)
1107 (loop (cdr fields) (+ 1 off)))))
1110 (let ((rtd (make-struct record-type-vtable 0
1112 (apply string-append
1113 (map (lambda (f) "pw") fields)))
1114 (or printer default-record-printer)
1116 (copy-tree fields))))
1117 (struct-set! rtd (+ vtable-offset-user 2)
1118 (make-constructor rtd (length fields)))
1119 ;; Temporary solution: Associate a name to the record type descriptor
1120 ;; so that the object system can create a wrapper class for it.
1121 (set-struct-vtable-name! rtd (if (symbol? type-name)
1123 (string->symbol type-name)))
1126 (define (record-type-name obj)
1127 (if (record-type? obj)
1128 (struct-ref obj vtable-offset-user)
1129 (error 'not-a-record-type obj)))
1131 (define (record-type-fields obj)
1132 (if (record-type? obj)
1133 (struct-ref obj (+ 1 vtable-offset-user))
1134 (error 'not-a-record-type obj)))
1136 (define* (record-constructor rtd #:optional field-names)
1137 (if (not field-names)
1138 (struct-ref rtd (+ 2 vtable-offset-user))
1140 `(lambda ,field-names
1141 (make-struct ',rtd 0 ,@(map (lambda (f)
1142 (if (memq f field-names)
1145 (record-type-fields rtd)))))))
1147 (define (record-predicate rtd)
1148 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1150 (define (%record-type-error rtd obj) ;; private helper
1151 (or (eq? rtd (record-type-descriptor obj))
1152 (scm-error 'wrong-type-arg "%record-type-check"
1153 "Wrong type record (want `~S'): ~S"
1154 (list (record-type-name rtd) obj)
1157 (define (record-accessor rtd field-name)
1158 (let ((pos (list-index (record-type-fields rtd) field-name)))
1160 (error 'no-such-field field-name))
1162 (if (eq? (struct-vtable obj) rtd)
1163 (struct-ref obj pos)
1164 (%record-type-error rtd obj)))))
1166 (define (record-modifier rtd field-name)
1167 (let ((pos (list-index (record-type-fields rtd) field-name)))
1169 (error 'no-such-field field-name))
1171 (if (eq? (struct-vtable obj) rtd)
1172 (struct-set! obj pos val)
1173 (%record-type-error rtd obj)))))
1175 (define (record? obj)
1176 (and (struct? obj) (record-type? (struct-vtable obj))))
1178 (define (record-type-descriptor obj)
1181 (error 'not-a-record obj)))
1190 (define (->bool x) (not (not x)))
1197 (define (symbol-append . args)
1198 (string->symbol (apply string-append (map symbol->string args))))
1200 (define (list->symbol . args)
1201 (string->symbol (apply list->string args)))
1203 (define (symbol . args)
1204 (string->symbol (apply string args)))
1211 (define (list-index l k)
1214 (and (not (null? l))
1217 (loop (+ n 1) (cdr l))))))
1221 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1222 ;; `stat' accessors.
1223 (primitive-load-path "ice-9/posix")
1225 (if (provided? 'socket)
1226 (primitive-load-path "ice-9/networking"))
1228 ;; For reference, Emacs file-exists-p uses stat in this same way.
1229 (define file-exists?
1230 (if (provided? 'posix)
1232 (->bool (stat str #f)))
1234 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
1236 (if port (begin (close-port port) #t)
1239 (define file-is-directory?
1240 (if (provided? 'posix)
1242 (eq? (stat:type (stat str)) 'directory))
1244 (let ((port (catch 'system-error
1245 (lambda () (open-file (string-append str "/.")
1248 (if port (begin (close-port port) #t)
1251 (define (system-error-errno args)
1252 (if (eq? (car args) 'system-error)
1253 (car (list-ref args 4))
1258 ;;; {Error Handling}
1264 (scm-error 'misc-error #f "?" #f #f))
1266 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1267 (scm-error 'misc-error #f msg (cons message args) #f)))))
1271 ;;; {Time Structures}
1274 (define (tm:sec obj) (vector-ref obj 0))
1275 (define (tm:min obj) (vector-ref obj 1))
1276 (define (tm:hour obj) (vector-ref obj 2))
1277 (define (tm:mday obj) (vector-ref obj 3))
1278 (define (tm:mon obj) (vector-ref obj 4))
1279 (define (tm:year obj) (vector-ref obj 5))
1280 (define (tm:wday obj) (vector-ref obj 6))
1281 (define (tm:yday obj) (vector-ref obj 7))
1282 (define (tm:isdst obj) (vector-ref obj 8))
1283 (define (tm:gmtoff obj) (vector-ref obj 9))
1284 (define (tm:zone obj) (vector-ref obj 10))
1286 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1287 (define (set-tm:min obj val) (vector-set! obj 1 val))
1288 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1289 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1290 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1291 (define (set-tm:year obj val) (vector-set! obj 5 val))
1292 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1293 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1294 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1295 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1296 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1298 (define (tms:clock obj) (vector-ref obj 0))
1299 (define (tms:utime obj) (vector-ref obj 1))
1300 (define (tms:stime obj) (vector-ref obj 2))
1301 (define (tms:cutime obj) (vector-ref obj 3))
1302 (define (tms:cstime obj) (vector-ref obj 4))
1306 ;;; {File Descriptors and Ports}
1309 (define file-position ftell)
1310 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1311 (seek port offset whence))
1313 (define (move->fdes fd/port fd)
1314 (cond ((integer? fd/port)
1315 (dup->fdes fd/port fd)
1319 (primitive-move->fdes fd/port fd)
1320 (set-port-revealed! fd/port 1)
1323 (define (release-port-handle port)
1324 (let ((revealed (port-revealed port)))
1326 (set-port-revealed! port (- revealed 1)))))
1331 (fdopen (dup->fdes port/fd) mode))
1332 ((port/fd mode new-fd)
1333 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1334 (set-port-revealed! port 1)
1340 (dup->port port/fd "r"))
1342 (dup->port port/fd "r" new-fd))))
1344 (define dup->outport
1347 (dup->port port/fd "w"))
1349 (dup->port port/fd "w" new-fd))))
1354 (if (integer? port/fd)
1356 (dup->port port/fd (port-mode port/fd))))
1358 (if (integer? port/fd)
1359 (dup->fdes port/fd new-fd)
1360 (dup->port port/fd (port-mode port/fd) new-fd)))))
1362 (define (duplicate-port port modes)
1363 (dup->port port modes))
1365 (define (fdes->inport fdes)
1366 (let loop ((rest-ports (fdes->ports fdes)))
1367 (cond ((null? rest-ports)
1368 (let ((result (fdopen fdes "r")))
1369 (set-port-revealed! result 1)
1371 ((input-port? (car rest-ports))
1372 (set-port-revealed! (car rest-ports)
1373 (+ (port-revealed (car rest-ports)) 1))
1376 (loop (cdr rest-ports))))))
1378 (define (fdes->outport fdes)
1379 (let loop ((rest-ports (fdes->ports fdes)))
1380 (cond ((null? rest-ports)
1381 (let ((result (fdopen fdes "w")))
1382 (set-port-revealed! result 1)
1384 ((output-port? (car rest-ports))
1385 (set-port-revealed! (car rest-ports)
1386 (+ (port-revealed (car rest-ports)) 1))
1389 (loop (cdr rest-ports))))))
1391 (define (port->fdes port)
1392 (set-port-revealed! port (+ (port-revealed port) 1))
1395 (define (setenv name value)
1397 (putenv (string-append name "=" value))
1400 (define (unsetenv name)
1401 "Remove the entry for NAME from the environment."
1409 (define (in-vicinity vicinity file)
1410 (let ((tail (let ((len (string-length vicinity)))
1413 (string-ref vicinity (- len 1))))))
1414 (string-append vicinity
1423 ;;; {Help for scm_shell}
1425 ;;; The argument-processing code used by Guile-based shells generates
1426 ;;; Scheme code based on the argument list. This page contains help
1427 ;;; functions for the code it generates.
1430 (define (command-line) (program-arguments))
1432 ;; This is mostly for the internal use of the code generated by
1433 ;; scm_compile_shell_switches.
1435 (define (load-user-init)
1436 (let* ((home (or (getenv "HOME")
1437 (false-if-exception (passwd:dir (getpwuid (getuid))))
1438 "/")) ;; fallback for cygwin etc.
1439 (init-file (in-vicinity home ".guile")))
1440 (if (file-exists? init-file)
1441 (primitive-load init-file))))
1445 ;;; {The interpreter stack}
1448 ;; %stacks defined in stacks.c
1449 (define (%start-stack tag thunk)
1450 (let ((prompt-tag (make-prompt-tag "start-stack")))
1454 (with-fluids ((%stacks (acons tag prompt-tag
1455 (or (fluid-ref %stacks) '()))))
1458 (%start-stack tag (lambda () (apply k args)))))))
1460 (define-syntax-rule (start-stack tag exp)
1461 (%start-stack tag (lambda () exp)))
1465 ;;; {Loading by paths}
1468 ;;; Load a Scheme source file named NAME, searching for it in the
1469 ;;; directories listed in %load-path, and applying each of the file
1470 ;;; name extensions listed in %load-extensions.
1471 (define (load-from-path name)
1472 (start-stack 'load-stack
1473 (primitive-load-path name)))
1475 (define-syntax-rule (add-to-load-path elt)
1476 "Add ELT to Guile's load path, at compile-time and at run-time."
1477 (eval-when (compile load eval)
1478 (set! %load-path (cons elt %load-path))))
1480 (define %load-verbosely #f)
1481 (define (assert-load-verbosity v) (set! %load-verbosely v))
1483 (define (%load-announce file)
1485 (with-output-to-port (current-warning-port)
1488 (display "loading ")
1493 (set! %load-hook %load-announce)
1497 ;;; {Reader Extensions}
1499 ;;; Reader code for various "#c" forms.
1502 (define read-eval? (make-fluid #f))
1503 (read-hash-extend #\.
1505 (if (fluid-ref read-eval?)
1506 (eval (read port) (interaction-environment))
1508 "#. read expansion found and read-eval? is #f."))))
1512 ;;; {Low Level Modules}
1514 ;;; These are the low level data structures for modules.
1516 ;;; Every module object is of the type 'module-type', which is a record
1517 ;;; consisting of the following members:
1519 ;;; - eval-closure: the function that defines for its module the strategy that
1520 ;;; shall be followed when looking up symbols in the module.
1522 ;;; An eval-closure is a function taking two arguments: the symbol to be
1523 ;;; looked up and a boolean value telling whether a binding for the symbol
1524 ;;; should be created if it does not exist yet. If the symbol lookup
1525 ;;; succeeded (either because an existing binding was found or because a new
1526 ;;; binding was created), a variable object representing the binding is
1527 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1528 ;;; closure does not take the module to be searched as an argument: During
1529 ;;; construction of the eval-closure, the eval-closure has to store the
1530 ;;; module it belongs to in its environment. This means, that any
1531 ;;; eval-closure can belong to only one module.
1533 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1534 ;;; special cases of eval-closures are to be distinguished: During startup
1535 ;;; the module system is not yet activated. In this phase, no modules are
1536 ;;; defined and all bindings are automatically stored by the system in the
1537 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1538 ;;; functions which require an eval-closure as their argument need to be
1539 ;;; passed the value #f.
1541 ;;; The other two special cases of eval-closures are the
1542 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1543 ;;; behave equally for the case that no new binding is to be created. The
1544 ;;; difference between the two comes in, when the boolean argument to the
1545 ;;; eval-closure indicates that a new binding shall be created if it is not
1548 ;;; Given that no new binding shall be created, both standard eval-closures
1549 ;;; define the following standard strategy of searching bindings in the
1550 ;;; module: First, the module's obarray is searched for the symbol. Second,
1551 ;;; if no binding for the symbol was found in the module's obarray, the
1552 ;;; module's binder procedure is exececuted. If this procedure did not
1553 ;;; return a binding for the symbol, the modules referenced in the module's
1554 ;;; uses list are recursively searched for a binding of the symbol. If the
1555 ;;; binding can not be found in these modules also, the symbol lookup has
1558 ;;; If a new binding shall be created, the standard-interface-eval-closure
1559 ;;; immediately returns indicating failure. That is, it does not even try
1560 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1561 ;;; first search the obarray, and if no binding was found there, would
1562 ;;; create a new binding in the obarray, therefore not calling the binder
1563 ;;; procedure or searching the modules in the uses list.
1565 ;;; The explanation of the following members obarray, binder and uses
1566 ;;; assumes that the symbol lookup follows the strategy that is defined in
1567 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1569 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1570 ;;; hash table, the definitions are found that are local to the module (that
1571 ;;; is, not imported from other modules). When looking up bindings in the
1572 ;;; module, this hash table is searched first.
1574 ;;; - binder: either #f or a function taking a module and a symbol argument.
1575 ;;; If it is a function it is called after the obarray has been
1576 ;;; unsuccessfully searched for a binding. It then can provide bindings
1577 ;;; that would otherwise not be found locally in the module.
1579 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1580 ;;; These modules are the third place queried for bindings after the obarray
1581 ;;; has been unsuccessfully searched and the binder function did not deliver
1582 ;;; a result either.
1584 ;;; - transformer: either #f or a function taking a scheme expression as
1585 ;;; delivered by read. If it is a function, it will be called to perform
1586 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1587 ;;; expression. The output of the transformer function will then be passed
1588 ;;; to Guile's internal memoizer. This means that the output must be valid
1589 ;;; scheme code. The only exception is, that the output may make use of the
1590 ;;; syntax extensions provided to identify the modules that a binding
1593 ;;; - name: the name of the module. This is used for all kinds of printing
1594 ;;; outputs. In certain places the module name also serves as a way of
1595 ;;; identification. When adding a module to the uses list of another
1596 ;;; module, it is made sure that the new uses list will not contain two
1597 ;;; modules of the same name.
1599 ;;; - kind: classification of the kind of module. The value is (currently?)
1600 ;;; only used for printing. It has no influence on how a module is treated.
1601 ;;; Currently the following values are used when setting the module kind:
1602 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1603 ;;; is set, it defaults to 'module.
1605 ;;; - duplicates-handlers: a list of procedures that get called to make a
1606 ;;; choice between two duplicate bindings when name clashes occur. See the
1607 ;;; `duplicate-handlers' global variable below.
1609 ;;; - observers: a list of procedures that get called when the module is
1612 ;;; - weak-observers: a weak-key hash table of procedures that get called
1613 ;;; when the module is modified. See `module-observe-weak' for details.
1615 ;;; In addition, the module may (must?) contain a binding for
1616 ;;; `%module-public-interface'. This variable should be bound to a module
1617 ;;; representing the exported interface of a module. See the
1618 ;;; `module-public-interface' and `module-export!' procedures.
1620 ;;; !!! warning: The interface to lazy binder procedures is going
1621 ;;; to be changed in an incompatible way to permit all the basic
1622 ;;; module ops to be virtualized.
1624 ;;; (make-module size use-list lazy-binding-proc) => module
1625 ;;; module-{obarray,uses,binder}[|-set!]
1626 ;;; (module? obj) => [#t|#f]
1627 ;;; (module-locally-bound? module symbol) => [#t|#f]
1628 ;;; (module-bound? module symbol) => [#t|#f]
1629 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1630 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1631 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1632 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1633 ;;; (module-symbol-binding module symbol opt-value)
1634 ;;; => [ <obj> | opt-value | an error occurs ]
1635 ;;; (module-make-local-var! module symbol) => #<variable...>
1636 ;;; (module-add! module symbol var) => unspecified
1637 ;;; (module-remove! module symbol) => unspecified
1638 ;;; (module-for-each proc module) => unspecified
1639 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1640 ;;; (set-current-module module) => unspecified
1641 ;;; (current-module) => #<module...>
1647 ;;; {Printing Modules}
1650 ;; This is how modules are printed. You can re-define it.
1651 (define (%print-module mod port)
1653 (display (or (module-kind mod) "module") port)
1655 (display (module-name mod) port)
1657 (display (number->string (object-address mod) 16) port)
1661 ;; Locally extend the syntax to allow record accessors to be defined at
1662 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1663 ;; the setters, in order to allow for redefinition of the record type; not
1664 ;; relevant in the case of modules, but perhaps if we make this public, it
1667 ((define-record-type
1669 (define (make-id scope . fragments)
1670 (datum->syntax scope
1671 (apply symbol-append
1673 (if (symbol? x) x (syntax->datum x)))
1676 (define (getter rtd type-name field slot)
1677 #`(define #,(make-id rtd type-name '- field)
1679 (lambda (#,type-name)
1680 (if (eq? (struct-vtable #,type-name) rtd)
1681 (struct-ref #,type-name #,slot)
1682 (%record-type-error rtd #,type-name))))))
1684 (define (setter rtd type-name field slot)
1685 #`(define #,(make-id rtd 'set- type-name '- field '!)
1687 (lambda (#,type-name val)
1688 (if (eq? (struct-vtable #,type-name) rtd)
1689 (struct-set! #,type-name #,slot val)
1690 (%record-type-error rtd #,type-name))))))
1692 (define (accessors rtd type-name fields n exp)
1693 (syntax-case fields ()
1695 (((field #:no-accessors) field* ...) (identifier? #'field)
1696 (accessors rtd type-name #'(field* ...) (1+ n)
1698 (((field #:no-setter) field* ...) (identifier? #'field)
1699 (accessors rtd type-name #'(field* ...) (1+ n)
1701 #,(getter rtd type-name #'field n))))
1702 (((field #:no-getter) field* ...) (identifier? #'field)
1703 (accessors rtd type-name #'(field* ...) (1+ n)
1705 #,(setter rtd type-name #'field n))))
1706 ((field field* ...) (identifier? #'field)
1707 (accessors rtd type-name #'(field* ...) (1+ n)
1709 #,(getter rtd type-name #'field n)
1710 #,(setter rtd type-name #'field n))))))
1712 (define (predicate rtd type-name fields exp)
1714 rtd type-name fields 0
1717 (define (#,(make-id rtd type-name '?) obj)
1718 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1720 (define (field-list fields)
1721 (syntax-case fields ()
1723 (((f . opts) . rest) (identifier? #'f)
1724 (cons #'f (field-list #'rest)))
1725 ((f . rest) (identifier? #'f)
1726 (cons #'f (field-list #'rest)))))
1728 (define (constructor rtd type-name fields exp)
1729 (let ((ctor (make-id rtd type-name '-constructor))
1730 (args (field-list fields)))
1731 (predicate rtd type-name fields
1736 (make-struct rtd 0 #,@args))))
1737 (struct-set! #,rtd (+ vtable-offset-user 2)
1740 (define (type type-name printer fields)
1741 (define (make-layout)
1742 (let lp ((fields fields) (slots '()))
1743 (syntax-case fields ()
1744 (() (datum->syntax #'here
1746 (apply string-append slots))))
1747 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1749 (let ((rtd (make-id type-name type-name '-type)))
1750 (constructor rtd type-name fields
1753 (make-struct record-type-vtable 0
1757 '#,(field-list fields)))
1758 (set-struct-vtable-name! #,rtd '#,type-name)))))
1761 ((_ type-name printer (field ...))
1762 (type #'type-name #'printer #'(field ...)))))))
1766 ;; A module is characterized by an obarray in which local symbols
1767 ;; are interned, a list of modules, "uses", from which non-local
1768 ;; bindings can be inherited, and an optional lazy-binder which
1769 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1770 ;; bindings that would otherwise not be found locally in the module.
1772 ;; NOTE: If you change the set of fields or their order, you also need to
1773 ;; change the constants in libguile/modules.h.
1775 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1776 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1777 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1778 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1780 (define-record-type module
1781 (lambda (obj port) (%print-module obj port))
1786 (transformer #:no-getter)
1790 (import-obarray #:no-setter)
1792 (weak-observers #:no-setter)
1800 ;; make-module &opt size uses binder
1802 ;; Create a new module, perhaps with a particular size of obarray,
1803 ;; initial uses list, or binding procedure.
1805 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
1806 (if (not (integer? size))
1807 (error "Illegal size to make-module." size))
1808 (if (not (and (list? uses)
1809 (and-map module? uses)))
1810 (error "Incorrect use list." uses))
1811 (if (and binder (not (procedure? binder)))
1813 "Lazy-binder expected to be a procedure or #f." binder))
1815 (let ((module (module-constructor (make-hash-table size)
1816 uses binder #f macroexpand
1820 (make-weak-key-hash-table 31) #f
1821 (make-hash-table 7) #f #f #f)))
1823 ;; We can't pass this as an argument to module-constructor,
1824 ;; because we need it to close over a pointer to the module
1826 (set-module-eval-closure! module (standard-eval-closure module))
1833 ;;; {Observer protocol}
1836 (define (module-observe module proc)
1837 (set-module-observers! module (cons proc (module-observers module)))
1840 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1841 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1842 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1843 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1844 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1847 ;; The two-argument version is kept for backward compatibility: when called
1848 ;; with two arguments, the observer gets unregistered when closure PROC
1849 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1850 (hashq-set! (module-weak-observers module) observer-id proc))
1852 (define (module-unobserve token)
1853 (let ((module (car token))
1856 (hash-remove! (module-weak-observers module) id)
1857 (set-module-observers! module (delq1! id (module-observers module)))))
1860 (define module-defer-observers #f)
1861 (define module-defer-observers-mutex (make-mutex 'recursive))
1862 (define module-defer-observers-table (make-hash-table))
1864 (define (module-modified m)
1865 (if module-defer-observers
1866 (hash-set! module-defer-observers-table m #t)
1867 (module-call-observers m)))
1869 ;;; This function can be used to delay calls to observers so that they
1870 ;;; can be called once only in the face of massive updating of modules.
1872 (define (call-with-deferred-observers thunk)
1875 (lock-mutex module-defer-observers-mutex)
1876 (set! module-defer-observers #t))
1879 (set! module-defer-observers #f)
1880 (hash-for-each (lambda (m dummy)
1881 (module-call-observers m))
1882 module-defer-observers-table)
1883 (hash-clear! module-defer-observers-table)
1884 (unlock-mutex module-defer-observers-mutex))))
1886 (define (module-call-observers m)
1887 (for-each (lambda (proc) (proc m)) (module-observers m))
1889 ;; We assume that weak observers don't (un)register themselves as they are
1890 ;; called since this would preclude proper iteration over the hash table
1892 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1896 ;;; {Module Searching in General}
1898 ;;; We sometimes want to look for properties of a symbol
1899 ;;; just within the obarray of one module. If the property
1900 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1901 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1904 ;;; Other times, we want to test for a symbol property in the obarray
1905 ;;; of M and, if it is not found there, try each of the modules in the
1906 ;;; uses list of M. This is the normal way of testing for some
1907 ;;; property, so we state these properties without qualification as
1908 ;;; in: ``The symbol 'fnord is interned in module M because it is
1909 ;;; interned locally in module M2 which is a member of the uses list
1913 ;; module-search fn m
1915 ;; return the first non-#f result of FN applied to M and then to
1916 ;; the modules in the uses of m, and so on recursively. If all applications
1917 ;; return #f, then so does this function.
1919 (define (module-search fn m v)
1922 (or (module-search fn (car pos) v)
1925 (loop (module-uses m))))
1928 ;;; {Is a symbol bound in a module?}
1930 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1931 ;;; of S in M has been set to some well-defined value.
1934 ;; module-locally-bound? module symbol
1936 ;; Is a symbol bound (interned and defined) locally in a given module?
1938 (define (module-locally-bound? m v)
1939 (let ((var (module-local-variable m v)))
1941 (variable-bound? var))))
1943 ;; module-bound? module symbol
1945 ;; Is a symbol bound (interned and defined) anywhere in a given module
1948 (define (module-bound? m v)
1949 (let ((var (module-variable m v)))
1951 (variable-bound? var))))
1953 ;;; {Is a symbol interned in a module?}
1955 ;;; Symbol S in Module M is interned if S occurs in
1956 ;;; of S in M has been set to some well-defined value.
1958 ;;; It is possible to intern a symbol in a module without providing
1959 ;;; an initial binding for the corresponding variable. This is done
1961 ;;; (module-add! module symbol (make-undefined-variable))
1963 ;;; In that case, the symbol is interned in the module, but not
1964 ;;; bound there. The unbound symbol shadows any binding for that
1965 ;;; symbol that might otherwise be inherited from a member of the uses list.
1968 (define (module-obarray-get-handle ob key)
1969 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1971 (define (module-obarray-ref ob key)
1972 ((if (symbol? key) hashq-ref hash-ref) ob key))
1974 (define (module-obarray-set! ob key val)
1975 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1977 (define (module-obarray-remove! ob key)
1978 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1980 ;; module-symbol-locally-interned? module symbol
1982 ;; is a symbol interned (not neccessarily defined) locally in a given module
1983 ;; or its uses? Interned symbols shadow inherited bindings even if
1984 ;; they are not themselves bound to a defined value.
1986 (define (module-symbol-locally-interned? m v)
1987 (not (not (module-obarray-get-handle (module-obarray m) v))))
1989 ;; module-symbol-interned? module symbol
1991 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1992 ;; or its uses? Interned symbols shadow inherited bindings even if
1993 ;; they are not themselves bound to a defined value.
1995 (define (module-symbol-interned? m v)
1996 (module-search module-symbol-locally-interned? m v))
1999 ;;; {Mapping modules x symbols --> variables}
2002 ;; module-local-variable module symbol
2003 ;; return the local variable associated with a MODULE and SYMBOL.
2005 ;;; This function is very important. It is the only function that can
2006 ;;; return a variable from a module other than the mutators that store
2007 ;;; new variables in modules. Therefore, this function is the location
2008 ;;; of the "lazy binder" hack.
2010 ;;; If symbol is defined in MODULE, and if the definition binds symbol
2011 ;;; to a variable, return that variable object.
2013 ;;; If the symbols is not found at first, but the module has a lazy binder,
2014 ;;; then try the binder.
2016 ;;; If the symbol is not found at all, return #f.
2018 ;;; (This is now written in C, see `modules.c'.)
2021 ;;; {Mapping modules x symbols --> bindings}
2023 ;;; These are similar to the mapping to variables, except that the
2024 ;;; variable is dereferenced.
2027 ;; module-symbol-binding module symbol opt-value
2029 ;; return the binding of a variable specified by name within
2030 ;; a given module, signalling an error if the variable is unbound.
2031 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2032 ;; return OPT-VALUE.
2034 (define (module-symbol-local-binding m v . opt-val)
2035 (let ((var (module-local-variable m v)))
2036 (if (and var (variable-bound? var))
2038 (if (not (null? opt-val))
2040 (error "Locally unbound variable." v)))))
2042 ;; module-symbol-binding module symbol opt-value
2044 ;; return the binding of a variable specified by name within
2045 ;; a given module, signalling an error if the variable is unbound.
2046 ;; If the OPT-VALUE is passed, then instead of signalling an error,
2047 ;; return OPT-VALUE.
2049 (define (module-symbol-binding m v . opt-val)
2050 (let ((var (module-variable m v)))
2051 (if (and var (variable-bound? var))
2053 (if (not (null? opt-val))
2055 (error "Unbound variable." v)))))
2060 ;;; {Adding Variables to Modules}
2063 ;; module-make-local-var! module symbol
2065 ;; ensure a variable for V in the local namespace of M.
2066 ;; If no variable was already there, then create a new and uninitialzied
2069 ;; This function is used in modules.c.
2071 (define (module-make-local-var! m v)
2072 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2075 ;; Mark as modified since this function is called when
2076 ;; the standard eval closure defines a binding
2080 ;; Create a new local variable.
2081 (let ((local-var (make-undefined-variable)))
2082 (module-add! m v local-var)
2085 ;; module-ensure-local-variable! module symbol
2087 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2088 ;; there is no binding for SYMBOL, create a new uninitialized
2089 ;; variable. Return the local variable.
2091 (define (module-ensure-local-variable! module symbol)
2092 (or (module-local-variable module symbol)
2093 (let ((var (make-undefined-variable)))
2094 (module-add! module symbol var)
2097 ;; module-add! module symbol var
2099 ;; ensure a particular variable for V in the local namespace of M.
2101 (define (module-add! m v var)
2102 (if (not (variable? var))
2103 (error "Bad variable to module-add!" var))
2104 (module-obarray-set! (module-obarray m) v var)
2105 (module-modified m))
2109 ;; make sure that a symbol is undefined in the local namespace of M.
2111 (define (module-remove! m v)
2112 (module-obarray-remove! (module-obarray m) v)
2113 (module-modified m))
2115 (define (module-clear! m)
2116 (hash-clear! (module-obarray m))
2117 (module-modified m))
2119 ;; MODULE-FOR-EACH -- exported
2121 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2123 (define (module-for-each proc module)
2124 (hash-for-each proc (module-obarray module)))
2126 (define (module-map proc module)
2127 (hash-map->list proc (module-obarray module)))
2131 ;; Modules exist in a separate namespace from values, because you generally do
2132 ;; not want the name of a submodule, which you might not even use, to collide
2133 ;; with local variables that happen to be named the same as the submodule.
2135 (define (module-ref-submodule module name)
2136 (or (hashq-ref (module-submodules module) name)
2137 (and (module-submodule-binder module)
2138 ((module-submodule-binder module) module name))))
2140 (define (module-define-submodule! module name submodule)
2141 (hashq-set! (module-submodules module) name submodule))
2145 ;;; {Module-based Loading}
2148 (define (save-module-excursion thunk)
2149 (let ((inner-module (current-module))
2151 (dynamic-wind (lambda ()
2152 (set! outer-module (current-module))
2153 (set-current-module inner-module)
2154 (set! inner-module #f))
2157 (set! inner-module (current-module))
2158 (set-current-module outer-module)
2159 (set! outer-module #f)))))
2163 ;;; {MODULE-REF -- exported}
2166 ;; Returns the value of a variable called NAME in MODULE or any of its
2167 ;; used modules. If there is no such variable, then if the optional third
2168 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2170 (define (module-ref module name . rest)
2171 (let ((variable (module-variable module name)))
2172 (if (and variable (variable-bound? variable))
2173 (variable-ref variable)
2175 (error "No variable named" name 'in module)
2176 (car rest) ; default value
2179 ;; MODULE-SET! -- exported
2181 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2182 ;; to VALUE; if there is no such variable, an error is signaled.
2184 (define (module-set! module name value)
2185 (let ((variable (module-variable module name)))
2187 (variable-set! variable value)
2188 (error "No variable named" name 'in module))))
2190 ;; MODULE-DEFINE! -- exported
2192 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2193 ;; variable, it is added first.
2195 (define (module-define! module name value)
2196 (let ((variable (module-local-variable module name)))
2199 (variable-set! variable value)
2200 (module-modified module))
2201 (let ((variable (make-variable value)))
2202 (module-add! module name variable)))))
2204 ;; MODULE-DEFINED? -- exported
2206 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2209 (define (module-defined? module name)
2210 (let ((variable (module-variable module name)))
2211 (and variable (variable-bound? variable))))
2213 ;; MODULE-USE! module interface
2215 ;; Add INTERFACE to the list of interfaces used by MODULE.
2217 (define (module-use! module interface)
2218 (if (not (or (eq? module interface)
2219 (memq interface (module-uses module))))
2221 ;; Newly used modules must be appended rather than consed, so that
2222 ;; `module-variable' traverses the use list starting from the first
2224 (set-module-uses! module (append (module-uses module)
2226 (hash-clear! (module-import-obarray module))
2227 (module-modified module))))
2229 ;; MODULE-USE-INTERFACES! module interfaces
2231 ;; Same as MODULE-USE!, but only notifies module observers after all
2232 ;; interfaces are added to the inports list.
2234 (define (module-use-interfaces! module interfaces)
2235 (let* ((cur (module-uses module))
2236 (new (let lp ((in interfaces) (out '()))
2240 (let ((iface (car in)))
2241 (if (or (memq iface cur) (memq iface out))
2243 (cons iface out))))))))
2244 (set-module-uses! module (append cur new))
2245 (hash-clear! (module-import-obarray module))
2246 (module-modified module)))
2250 ;;; {Recursive Namespaces}
2252 ;;; A hierarchical namespace emerges if we consider some module to be
2253 ;;; root, and submodules of that module to be nested namespaces.
2255 ;;; The routines here manage variable names in hierarchical namespace.
2256 ;;; Each variable name is a list of elements, looked up in successively nested
2259 ;;; (nested-ref some-root-module '(foo bar baz))
2260 ;;; => <value of a variable named baz in the submodule bar of
2261 ;;; the submodule foo of some-root-module>
2266 ;;; ;; a-root is a module
2267 ;;; ;; name is a list of symbols
2269 ;;; nested-ref a-root name
2270 ;;; nested-set! a-root name val
2271 ;;; nested-define! a-root name val
2272 ;;; nested-remove! a-root name
2274 ;;; These functions manipulate values in namespaces. For referencing the
2275 ;;; namespaces themselves, use the following:
2277 ;;; nested-ref-module a-root name
2278 ;;; nested-define-module! a-root name mod
2280 ;;; (current-module) is a natural choice for a root so for convenience there are
2283 ;;; local-ref name == nested-ref (current-module) name
2284 ;;; local-set! name val == nested-set! (current-module) name val
2285 ;;; local-define name val == nested-define! (current-module) name val
2286 ;;; local-remove name == nested-remove! (current-module) name
2287 ;;; local-ref-module name == nested-ref-module (current-module) name
2288 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2292 (define (nested-ref root names)
2295 (let loop ((cur root)
2299 (module-ref cur head #f)
2300 (let ((cur (module-ref-submodule cur head)))
2302 (loop cur (car tail) (cdr tail))))))))
2304 (define (nested-set! root names val)
2305 (let loop ((cur root)
2309 (module-set! cur head val)
2310 (let ((cur (module-ref-submodule cur head)))
2312 (error "failed to resolve module" names)
2313 (loop cur (car tail) (cdr tail)))))))
2315 (define (nested-define! root names val)
2316 (let loop ((cur root)
2320 (module-define! cur head val)
2321 (let ((cur (module-ref-submodule cur head)))
2323 (error "failed to resolve module" names)
2324 (loop cur (car tail) (cdr tail)))))))
2326 (define (nested-remove! root names)
2327 (let loop ((cur root)
2331 (module-remove! cur head)
2332 (let ((cur (module-ref-submodule cur head)))
2334 (error "failed to resolve module" names)
2335 (loop cur (car tail) (cdr tail)))))))
2338 (define (nested-ref-module root names)
2339 (let loop ((cur root)
2343 (let ((cur (module-ref-submodule cur (car names))))
2345 (loop cur (cdr names)))))))
2347 (define (nested-define-module! root names module)
2349 (error "can't redefine root module" root module)
2350 (let loop ((cur root)
2354 (module-define-submodule! cur head module)
2355 (let ((cur (or (module-ref-submodule cur head)
2356 (let ((m (make-module 31)))
2357 (set-module-kind! m 'directory)
2358 (set-module-name! m (append (module-name cur)
2360 (module-define-submodule! cur head m)
2362 (loop cur (car tail) (cdr tail)))))))
2365 (define (local-ref names)
2366 (nested-ref (current-module) names))
2368 (define (local-set! names val)
2369 (nested-set! (current-module) names val))
2371 (define (local-define names val)
2372 (nested-define! (current-module) names val))
2374 (define (local-remove names)
2375 (nested-remove! (current-module) names))
2377 (define (local-ref-module names)
2378 (nested-ref-module (current-module) names))
2380 (define (local-define-module names mod)
2381 (nested-define-module! (current-module) names mod))
2387 ;;; {The (guile) module}
2389 ;;; The standard module, which has the core Guile bindings. Also called the
2390 ;;; "root module", as it is imported by many other modules, but it is not
2391 ;;; necessarily the root of anything; and indeed, the module named '() might be
2392 ;;; better thought of as a root.
2395 (define (set-system-module! m s)
2396 (set-procedure-property! (module-eval-closure m) 'system-module s))
2398 ;; The root module uses the pre-modules-obarray as its obarray. This
2399 ;; special obarray accumulates all bindings that have been established
2400 ;; before the module system is fully booted.
2402 ;; (The obarray continues to be used by code that has been closed over
2403 ;; before the module system has been booted.)
2405 (define the-root-module
2406 (let ((m (make-module 0)))
2407 (set-module-obarray! m (%get-pre-modules-obarray))
2408 (set-module-name! m '(guile))
2409 (set-system-module! m #t)
2412 ;; The root interface is a module that uses the same obarray as the
2413 ;; root module. It does not allow new definitions, tho.
2415 (define the-scm-module
2416 (let ((m (make-module 0)))
2417 (set-module-obarray! m (%get-pre-modules-obarray))
2418 (set-module-eval-closure! m (standard-interface-eval-closure m))
2419 (set-module-name! m '(guile))
2420 (set-module-kind! m 'interface)
2421 (set-system-module! m #t)
2423 ;; In Guile 1.8 and earlier M was its own public interface.
2424 (set-module-public-interface! m m)
2428 (set-module-public-interface! the-root-module the-scm-module)
2432 ;; Now that we have a root module, even though modules aren't fully booted,
2433 ;; expand the definition of resolve-module.
2435 (define (resolve-module name . args)
2436 (if (equal? name '(guile))
2438 (error "unexpected module to resolve during module boot" name)))
2440 ;; Cheat. These bindings are needed by modules.c, but we don't want
2441 ;; to move their real definition here because that would be unnatural.
2443 (define define-module* #f)
2444 (define process-use-modules #f)
2445 (define module-export! #f)
2446 (define default-duplicate-binding-procedures #f)
2448 ;; This boots the module system. All bindings needed by modules.c
2449 ;; must have been defined by now.
2451 (set-current-module the-root-module)
2456 ;; Now that modules are booted, give module-name its final definition.
2459 (let ((accessor (record-accessor module-type 'name)))
2462 (let ((name (list (gensym))))
2463 ;; Name MOD and bind it in the module root so that it's visible to
2464 ;; `resolve-module'. This is important as `psyntax' stores module
2465 ;; names and relies on being able to `resolve-module' them.
2466 (set-module-name! mod name)
2467 (nested-define-module! (resolve-module '() #f) name mod)
2470 (define (make-modules-in module name)
2471 (or (nested-ref-module module name)
2472 (let ((m (make-module 31)))
2473 (set-module-kind! m 'directory)
2474 (set-module-name! m (append (module-name module) name))
2475 (nested-define-module! module name m)
2478 (define (beautify-user-module! module)
2479 (let ((interface (module-public-interface module)))
2480 (if (or (not interface)
2481 (eq? interface module))
2482 (let ((interface (make-module 31)))
2483 (set-module-name! interface (module-name module))
2484 (set-module-version! interface (module-version module))
2485 (set-module-kind! interface 'interface)
2486 (set-module-public-interface! module interface))))
2487 (if (and (not (memq the-scm-module (module-uses module)))
2488 (not (eq? module the-root-module)))
2489 ;; Import the default set of bindings (from the SCM module) in MODULE.
2490 (module-use! module the-scm-module)))
2492 (define (version-matches? version-ref target)
2493 (define (sub-versions-match? v-refs t)
2494 (define (sub-version-matches? v-ref t)
2495 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2497 ((number? v-ref) (eqv? v-ref t))
2500 ((>=) (>= t (cadr v-ref)))
2501 ((<=) (<= t (cadr v-ref)))
2502 ((and) (and-map matches? (cdr v-ref)))
2503 ((or) (or-map matches? (cdr v-ref)))
2504 ((not) (not (matches? (cadr v-ref))))
2505 (else (error "Invalid sub-version reference" v-ref))))
2506 (else (error "Invalid sub-version reference" v-ref)))))
2508 (and (not (null? t))
2509 (sub-version-matches? (car v-refs) (car t))
2510 (sub-versions-match? (cdr v-refs) (cdr t)))))
2512 (let ((matches? (lambda (v) (version-matches? v target))))
2513 (or (null? version-ref)
2514 (case (car version-ref)
2515 ((and) (and-map matches? (cdr version-ref)))
2516 ((or) (or-map matches? (cdr version-ref)))
2517 ((not) (not (matches? (cadr version-ref))))
2518 (else (sub-versions-match? version-ref target))))))
2520 (define (make-fresh-user-module)
2521 (let ((m (make-module)))
2522 (beautify-user-module! m)
2525 ;; NOTE: This binding is used in libguile/modules.c.
2527 (define resolve-module
2528 (let ((root (make-module)))
2529 (set-module-name! root '())
2530 ;; Define the-root-module as '(guile).
2531 (module-define-submodule! root 'guile the-root-module)
2533 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2534 (let ((already (nested-ref-module root name)))
2537 (or (not autoload) (module-public-interface already)))
2538 ;; A hit, a palpable hit.
2540 (not (version-matches? version (module-version already))))
2541 (error "incompatible module version already loaded" name))
2544 ;; Try to autoload the module, and recurse.
2545 (try-load-module name version)
2546 (resolve-module name #f #:ensure ensure))
2548 ;; No module found (or if one was, it had no public interface), and
2549 ;; we're not autoloading. Make an empty module if #:ensure is true.
2552 (make-modules-in root name)))))))))
2555 (define (try-load-module name version)
2556 (try-module-autoload name version))
2558 (define (reload-module m)
2559 "Revisit the source file corresponding to the module @var{m}."
2560 (let ((f (module-filename m)))
2562 (save-module-excursion
2564 ;; Re-set the initial environment, as in try-module-autoload.
2565 (set-current-module (make-fresh-user-module))
2566 (primitive-load-path f)
2568 ;; Though we could guess, we *should* know it.
2569 (error "unknown file name for module" m))))
2571 (define (purify-module! module)
2572 "Removes bindings in MODULE which are inherited from the (guile) module."
2573 (let ((use-list (module-uses module)))
2574 (if (and (pair? use-list)
2575 (eq? (car (last-pair use-list)) the-scm-module))
2576 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2578 ;; Return a module that is an interface to the module designated by
2581 ;; `resolve-interface' takes four keyword arguments:
2583 ;; #:select SELECTION
2585 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2586 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2587 ;; is the name in the used module and SEEN is the name in the using
2588 ;; module. Note that SEEN is also passed through RENAMER, below. The
2589 ;; default is to select all bindings. If you specify no selection but
2590 ;; a renamer, only the bindings that already exist in the used module
2591 ;; are made available in the interface. Bindings that are added later
2592 ;; are not picked up.
2596 ;; BINDINGS is a list of bindings which should not be imported.
2600 ;; PREFIX is a symbol that will be appended to each exported name.
2601 ;; The default is to not perform any renaming.
2603 ;; #:renamer RENAMER
2605 ;; RENAMER is a procedure that takes a symbol and returns its new
2606 ;; name. The default is not perform any renaming.
2608 ;; Signal "no code for module" error if module name is not resolvable
2609 ;; or its public interface is not available. Signal "no binding"
2610 ;; error if selected binding does not exist in the used module.
2612 (define* (resolve-interface name #:key
2617 (symbol-prefix-proc prefix)
2620 (let* ((module (resolve-module name #t version #:ensure #f))
2621 (public-i (and module (module-public-interface module))))
2622 (and (or (not module) (not public-i))
2623 (error "no code for module" name))
2624 (if (and (not select) (null? hide) (eq? renamer identity))
2626 (let ((selection (or select (module-map (lambda (sym var) sym)
2628 (custom-i (make-module 31)))
2629 (set-module-kind! custom-i 'custom-interface)
2630 (set-module-name! custom-i name)
2631 ;; XXX - should use a lazy binder so that changes to the
2632 ;; used module are picked up automatically.
2633 (for-each (lambda (bspec)
2634 (let* ((direct? (symbol? bspec))
2635 (orig (if direct? bspec (car bspec)))
2636 (seen (if direct? bspec (cdr bspec)))
2637 (var (or (module-local-variable public-i orig)
2638 (module-local-variable module orig)
2640 ;; fixme: format manually for now
2642 #f "no binding `~A' in module ~A"
2644 (if (memq orig hide)
2645 (set! hide (delq! orig hide))
2646 (module-add! custom-i
2650 ;; Check that we are not hiding bindings which don't exist
2651 (for-each (lambda (binding)
2652 (if (not (module-local-variable public-i binding))
2655 #f "no binding `~A' to hide in module ~A"
2660 (define (symbol-prefix-proc prefix)
2662 (symbol-append prefix symbol)))
2664 ;; This function is called from "modules.c". If you change it, be
2665 ;; sure to update "modules.c" as well.
2667 (define* (define-module* name
2668 #:key filename pure version (duplicates '())
2669 (imports '()) (exports '()) (replacements '())
2670 (re-exports '()) (autoloads '()) transformer)
2671 (define (list-of pred l)
2673 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2674 (define (valid-export? x)
2675 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2676 (define (valid-autoload? x)
2677 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
2679 (define (resolve-imports imports)
2680 (define (resolve-import import-spec)
2681 (if (list? import-spec)
2682 (apply resolve-interface import-spec)
2683 (error "unexpected use-module specification" import-spec)))
2684 (let lp ((imports imports) (out '()))
2686 ((null? imports) (reverse! out))
2689 (cons (resolve-import (car imports)) out)))
2690 (else (error "unexpected tail of imports list" imports)))))
2692 ;; We could add a #:no-check arg, set by the define-module macro, if
2693 ;; these checks are taking too much time.
2695 (let ((module (resolve-module name #f)))
2696 (beautify-user-module! module)
2698 (set-module-filename! module filename))
2700 (purify-module! module))
2703 (if (not (list-of integer? version))
2704 (error "expected list of integers for version"))
2705 (set-module-version! module version)
2706 (set-module-version! (module-public-interface module) version)))
2707 (let ((imports (resolve-imports imports)))
2708 (call-with-deferred-observers
2711 (module-use-interfaces! module imports))
2712 (if (list-of valid-export? exports)
2714 (module-export! module exports))
2715 (error "expected exports to be a list of symbols or symbol pairs"))
2716 (if (list-of valid-export? replacements)
2717 (if (pair? replacements)
2718 (module-replace! module replacements))
2719 (error "expected replacements to be a list of symbols or symbol pairs"))
2720 (if (list-of valid-export? re-exports)
2721 (if (pair? re-exports)
2722 (module-re-export! module re-exports))
2723 (error "expected re-exports to be a list of symbols or symbol pairs"))
2725 (if (not (null? autoloads))
2726 (apply module-autoload! module autoloads))
2727 ;; Wait until modules have been loaded to resolve duplicates
2729 (if (pair? duplicates)
2730 (let ((handlers (lookup-duplicates-handlers duplicates)))
2731 (set-module-duplicates-handlers! module handlers))))))
2734 (if (and (pair? transformer) (list-of symbol? transformer))
2735 (let ((iface (resolve-interface transformer))
2736 (sym (car (last-pair transformer))))
2737 (set-module-transformer! module (module-ref iface sym)))
2738 (error "expected transformer to be a module name" transformer)))
2740 (run-hook module-defined-hook module)
2743 ;; `module-defined-hook' is a hook that is run whenever a new module
2744 ;; is defined. Its members are called with one argument, the new
2746 (define module-defined-hook (make-hook 1))
2753 (define (make-autoload-interface module name bindings)
2754 (let ((b (lambda (a sym definep)
2755 (and (memq sym bindings)
2756 (let ((i (module-public-interface (resolve-module name))))
2758 (error "missing interface for module" name))
2759 (let ((autoload (memq a (module-uses module))))
2760 ;; Replace autoload-interface with actual interface if
2761 ;; that has not happened yet.
2762 (if (pair? autoload)
2763 (set-car! autoload i)))
2764 (module-local-variable i sym))))))
2765 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2766 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2767 (make-hash-table 0) #f #f #f)))
2769 (define (module-autoload! module . args)
2770 "Have @var{module} automatically load the module named @var{name} when one
2771 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2772 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2773 module '(ice-9 q) '(make-q q-length))}."
2774 (let loop ((args args))
2778 (error "invalid name+binding autoload list" args))
2780 (let ((name (car args))
2781 (bindings (cadr args)))
2782 (module-use! module (make-autoload-interface module
2784 (loop (cddr args)))))))
2789 ;;; {Autoloading modules}
2792 (define autoloads-in-progress '())
2794 ;; This function is called from "modules.c". If you change it, be
2795 ;; sure to update "modules.c" as well.
2797 (define* (try-module-autoload module-name #:optional version)
2798 (let* ((reverse-name (reverse module-name))
2799 (name (symbol->string (car reverse-name)))
2800 (dir-hint-module-name (reverse (cdr reverse-name)))
2801 (dir-hint (apply string-append
2803 (string-append (symbol->string elt) "/"))
2804 dir-hint-module-name))))
2805 (resolve-module dir-hint-module-name #f)
2806 (and (not (autoload-done-or-in-progress? dir-hint name))
2809 (lambda () (autoload-in-progress! dir-hint name))
2811 (with-fluids ((current-reader #f))
2812 (save-module-excursion
2814 ;; The initial environment when loading a module is a fresh
2816 (set-current-module (make-fresh-user-module))
2817 ;; Here we could allow some other search strategy (other than
2818 ;; primitive-load-path), for example using versions encoded
2819 ;; into the file system -- but then we would have to figure
2820 ;; out how to locate the compiled file, do auto-compilation,
2821 ;; etc. Punt for now, and don't use versions when locating
2823 (primitive-load-path (in-vicinity dir-hint name) #f)
2825 (lambda () (set-autoloaded! dir-hint name didit)))
2830 ;;; {Dynamic linking of modules}
2833 (define autoloads-done '((guile . guile)))
2835 (define (autoload-done-or-in-progress? p m)
2836 (let ((n (cons p m)))
2837 (->bool (or (member n autoloads-done)
2838 (member n autoloads-in-progress)))))
2840 (define (autoload-done! p m)
2841 (let ((n (cons p m)))
2842 (set! autoloads-in-progress
2843 (delete! n autoloads-in-progress))
2844 (or (member n autoloads-done)
2845 (set! autoloads-done (cons n autoloads-done)))))
2847 (define (autoload-in-progress! p m)
2848 (let ((n (cons p m)))
2849 (set! autoloads-done
2850 (delete! n autoloads-done))
2851 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2853 (define (set-autoloaded! p m done?)
2855 (autoload-done! p m)
2856 (let ((n (cons p m)))
2857 (set! autoloads-done (delete! n autoloads-done))
2858 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2862 ;;; {Run-time options}
2865 (define-syntax define-option-interface
2867 ((_ (interface (options enable disable) (option-set!)))
2874 (begin (interface arg) (interface))
2877 (apply (lambda (name value documentation)
2879 (if (< (string-length (symbol->string name)) 8)
2884 (display documentation)
2888 (define (enable . flags)
2889 (interface (append flags (interface)))
2891 (define (disable . flags)
2892 (let ((options (interface)))
2893 (for-each (lambda (flag) (set! options (delq! flag options)))
2897 (define-syntax-rule (option-set! opt val)
2898 (eval-when (eval load compile expand)
2899 (options (append (options) (list 'opt val)))))))))
2901 (define-option-interface
2902 (debug-options-interface
2903 (debug-options debug-enable debug-disable)
2906 (define-option-interface
2907 (read-options-interface
2908 (read-options read-enable read-disable)
2911 (define-option-interface
2912 (print-options-interface
2913 (print-options print-enable print-disable)
2918 ;;; {The Unspecified Value}
2920 ;;; Currently Guile represents unspecified values via one particular value,
2921 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2922 ;;; future if we could replace this with a return of 0 values, though.
2925 (define-syntax *unspecified*
2926 (identifier-syntax (if #f #f)))
2928 (define (unspecified? v) (eq? v *unspecified*))
2937 ;; Three fields: the procedure itself, the fluid, and the converter.
2938 (make-struct <applicable-struct-vtable> 0 'pwprpr))
2939 (set-struct-vtable-name! <parameter> '<parameter>)
2941 (define* (make-parameter init #:optional (conv (lambda (x) x)))
2942 (let ((fluid (make-fluid (conv init))))
2943 (make-struct <parameter> 0
2945 (() (fluid-ref fluid))
2946 ((x) (let ((prev (fluid-ref fluid)))
2947 (fluid-set! fluid (conv x))
2951 (define (parameter? x)
2952 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
2954 (define (parameter-fluid p)
2957 (scm-error 'wrong-type-arg "parameter-fluid"
2958 "Not a parameter: ~S" (list p) #f)))
2960 (define (parameter-converter p)
2963 (scm-error 'wrong-type-arg "parameter-fluid"
2964 "Not a parameter: ~S" (list p) #f)))
2966 (define-syntax parameterize
2969 ((_ ((param value) ...) body body* ...)
2970 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
2971 #'(let ((p param) ...)
2972 (if (not (parameter? p))
2973 (scm-error 'wrong-type-arg "parameterize"
2974 "Not a parameter: ~S" (list p) #f))
2976 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
2978 body body* ...)))))))
2982 ;;; Current ports as parameters.
2985 (let ((fluid->parameter
2986 (lambda (fluid conv)
2987 (make-struct <parameter> 0
2989 (() (fluid-ref fluid))
2990 ((x) (let ((prev (fluid-ref fluid)))
2991 (fluid-set! fluid (conv x))
2994 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
2996 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
3000 (module-remove! (current-module) 'fluid)))
3002 (port-parameterize! current-input-port %current-input-port-fluid
3003 input-port? "expected an input port")
3004 (port-parameterize! current-output-port %current-output-port-fluid
3005 output-port? "expected an output port")
3006 (port-parameterize! current-error-port %current-error-port-fluid
3007 output-port? "expected an output port"))
3015 (define current-warning-port
3016 (make-parameter (current-error-port)
3018 (if (output-port? x)
3020 (error "expected an output port" x)))))
3028 (define *repl-stack* (make-fluid '()))
3030 ;; Programs can call `batch-mode?' to see if they are running as part of a
3031 ;; script or if they are running interactively. REPL implementations ensure that
3032 ;; `batch-mode?' returns #f during their extent.
3034 (define (batch-mode?)
3035 (null? (fluid-ref *repl-stack*)))
3037 ;; Programs can re-enter batch mode, for example after a fork, by calling
3038 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3039 ;; to abort to the outermost prompt, and call a thunk there.
3041 (define (ensure-batch-mode!)
3042 (set! batch-mode? (lambda () #t)))
3044 (define (quit . args)
3045 (apply throw 'quit args))
3049 (define (gc-run-time)
3050 (cdr (assq 'gc-time-taken (gc-stats))))
3052 (define abort-hook (make-hook))
3053 (define before-error-hook (make-hook))
3054 (define after-error-hook (make-hook))
3055 (define before-backtrace-hook (make-hook))
3056 (define after-backtrace-hook (make-hook))
3058 (define before-read-hook (make-hook))
3059 (define after-read-hook (make-hook))
3060 (define before-eval-hook (make-hook 1))
3061 (define after-eval-hook (make-hook 1))
3062 (define before-print-hook (make-hook 1))
3063 (define after-print-hook (make-hook 1))
3065 ;;; This hook is run at the very end of an interactive session.
3067 (define exit-hook (make-hook))
3069 ;;; The default repl-reader function. We may override this if we've
3070 ;;; the readline library.
3072 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3073 (if (not (char-ready?))
3075 (display (if (string? prompt) prompt (prompt)))
3076 ;; An interesting situation. The printer resets the column to
3077 ;; 0 by printing a newline, but we then advance it by printing
3078 ;; the prompt. However the port-column of the output port
3079 ;; does not typically correspond with the actual column on the
3080 ;; screen, because the input is echoed back! Since the
3081 ;; input is line-buffered and thus ends with a newline, the
3082 ;; output will really start on column zero. So, here we zero
3083 ;; it out. See bug 9664.
3085 ;; Note that for similar reasons, the output-line will not
3086 ;; reflect the actual line on the screen. But given the
3087 ;; possibility of multiline input, the fix is not as
3088 ;; straightforward, so we don't bother.
3090 ;; Also note that the readline implementation papers over
3091 ;; these concerns, because it's readline itself printing the
3092 ;; prompt, and not Guile.
3093 (set-port-column! (current-output-port) 0)))
3095 (run-hook before-read-hook)
3096 ((or reader read) (current-input-port))))
3101 ;;; {IOTA functions: generating lists of numbers}
3105 (let loop ((count (1- n)) (result '()))
3106 (if (< count 0) result
3107 (loop (1- count) (cons count result)))))
3113 ;;; with `continue' and `break'.
3116 ;; The inliner will remove the prompts at compile-time if it finds that
3117 ;; `continue' or `break' are not used.
3119 (define-syntax while
3122 ((while cond body ...)
3123 #`(let ((break-tag (make-prompt-tag "break"))
3124 (continue-tag (make-prompt-tag "continue")))
3128 (define-syntax #,(datum->syntax #'while 'break)
3132 #'(abort-to-prompt break-tag arg (... ...)))
3135 (apply abort-to-prompt break-tag args))))))
3140 (define-syntax #,(datum->syntax #'while 'continue)
3144 #'(abort-to-prompt continue-tag))
3146 (syntax-violation 'continue "too many arguments" x))
3149 (abort-to-prompt continue-tag))))))
3150 (do () ((not cond) #f) body ...))
3151 (lambda (k) (lp)))))
3155 (apply values args)))))))))
3160 ;;; {Module System Macros}
3163 ;; Return a list of expressions that evaluate to the appropriate
3164 ;; arguments for resolve-interface according to SPEC.
3166 (eval-when (compile)
3167 (if (memq 'prefix (read-options))
3168 (error "boot-9 must be compiled with #:kw, not :kw")))
3170 (define (keyword-like-symbol->keyword sym)
3171 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3173 (define-syntax define-module
3175 (define (keyword-like? stx)
3176 (let ((dat (syntax->datum stx)))
3178 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3179 (define (->keyword sym)
3180 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3182 (define (parse-iface args)
3183 (let loop ((in args) (out '()))
3186 ;; The user wanted #:foo, but wrote :foo. Fix it.
3187 ((sym . in) (keyword-like? #'sym)
3188 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3189 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3190 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3191 ((#:renamer renamer . in)
3192 (loop #'in (cons* #',renamer #:renamer out)))
3194 (loop #'in (cons* #'val #'kw out))))))
3196 (define (parse args imp exp rex rep aut)
3197 ;; Just quote everything except #:use-module and #:use-syntax. We
3198 ;; need to know about all arguments regardless since we want to turn
3199 ;; symbols that look like keywords into real keywords, and the
3200 ;; keyword args in a define-module form are not regular
3201 ;; (i.e. no-backtrace doesn't take a value).
3202 (syntax-case args ()
3204 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3205 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3206 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3207 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3208 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3209 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3210 ;; The user wanted #:foo, but wrote :foo. Fix it.
3211 ((sym . args) (keyword-like? #'sym)
3212 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3213 imp exp rex rep aut))
3214 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3215 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3216 ((#:no-backtrace . args)
3218 (parse #'args imp exp rex rep aut))
3220 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3222 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3223 ((#:version (v ...) . args)
3224 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3225 ((#:duplicates (d ...) . args)
3226 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3227 ((#:filename f . args)
3228 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3229 ((#:use-module (name name* ...) . args)
3230 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3231 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3232 ((#:use-syntax (name name* ...) . args)
3233 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3234 #`(#:transformer '(name name* ...)
3235 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3236 ((#:use-module ((name name* ...) arg ...) . args)
3237 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3239 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3241 ((#:export (ex ...) . args)
3242 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3243 ((#:export-syntax (ex ...) . args)
3244 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3245 ((#:re-export (re ...) . args)
3246 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3247 ((#:re-export-syntax (re ...) . args)
3248 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3249 ((#:replace (r ...) . args)
3250 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3251 ((#:replace-syntax (r ...) . args)
3252 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3253 ((#:autoload name bindings . args)
3254 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3256 (syntax-violation 'define-module "unknown keyword or bad argument"
3260 ((_ (name name* ...) arg ...)
3261 (and-map symbol? (syntax->datum #'(name name* ...)))
3262 (with-syntax (((quoted-arg ...)
3263 (parse #'(arg ...) '() '() '() '() '()))
3264 ;; Ideally the filename is either a string or #f;
3265 ;; this hack is to work around a case in which
3266 ;; port-filename returns a symbol (`socket') for
3268 (filename (let ((f (assq-ref (or (syntax-source x) '())
3270 (and (string? f) f))))
3271 #'(eval-when (eval load compile expand)
3272 (let ((m (define-module* '(name name* ...)
3273 #:filename filename quoted-arg ...)))
3274 (set-current-module m)
3277 ;; The guts of the use-modules macro. Add the interfaces of the named
3278 ;; modules to the use-list of the current module, in order.
3280 ;; This function is called by "modules.c". If you change it, be sure
3281 ;; to change scm_c_use_module as well.
3283 (define (process-use-modules module-interface-args)
3284 (let ((interfaces (map (lambda (mif-args)
3285 (or (apply resolve-interface mif-args)
3286 (error "no such module" mif-args)))
3287 module-interface-args)))
3288 (call-with-deferred-observers
3290 (module-use-interfaces! (current-module) interfaces)))))
3292 (define-syntax use-modules
3294 (define (keyword-like? stx)
3295 (let ((dat (syntax->datum stx)))
3297 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3298 (define (->keyword sym)
3299 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3301 (define (quotify-iface args)
3302 (let loop ((in args) (out '()))
3305 ;; The user wanted #:foo, but wrote :foo. Fix it.
3306 ((sym . in) (keyword-like? #'sym)
3307 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3308 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3309 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3310 ((#:renamer renamer . in)
3311 (loop #'in (cons* #'renamer #:renamer out)))
3313 (loop #'in (cons* #''val #'kw out))))))
3315 (define (quotify specs)
3316 (let lp ((in specs) (out '()))
3319 (((name name* ...) . in)
3320 (and-map symbol? (syntax->datum #'(name name* ...)))
3321 (lp #'in (cons #''((name name* ...)) out)))
3322 ((((name name* ...) arg ...) . in)
3323 (and-map symbol? (syntax->datum #'(name name* ...)))
3324 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3325 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3330 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3331 #'(eval-when (eval load compile expand)
3332 (process-use-modules (list quoted-args ...))
3335 (include-from-path "ice-9/r6rs-libraries")
3337 (define-syntax-rule (define-private foo bar)
3340 (define-syntax define-public
3342 ((_ (name . args) . body)
3343 (define-public name (lambda args . body)))
3349 (define-syntax-rule (defmacro-public name args body ...)
3351 (defmacro name args body ...)
3352 (export-syntax name)))
3354 ;; And now for the most important macro.
3355 (define-syntax-rule (λ formals body ...)
3356 (lambda formals body ...))
3359 ;; Export a local variable
3361 ;; This function is called from "modules.c". If you change it, be
3362 ;; sure to update "modules.c" as well.
3364 (define (module-export! m names)
3365 (let ((public-i (module-public-interface m)))
3366 (for-each (lambda (name)
3367 (let* ((internal-name (if (pair? name) (car name) name))
3368 (external-name (if (pair? name) (cdr name) name))
3369 (var (module-ensure-local-variable! m internal-name)))
3370 (module-add! public-i external-name var)))
3373 (define (module-replace! m names)
3374 (let ((public-i (module-public-interface m)))
3375 (for-each (lambda (name)
3376 (let* ((internal-name (if (pair? name) (car name) name))
3377 (external-name (if (pair? name) (cdr name) name))
3378 (var (module-ensure-local-variable! m internal-name)))
3379 ;; FIXME: use a bit on variables instead of object
3381 (set-object-property! var 'replace #t)
3382 (module-add! public-i external-name var)))
3385 ;; Export all local variables from a module
3387 (define (module-export-all! mod)
3388 (define (fresh-interface!)
3389 (let ((iface (make-module)))
3390 (set-module-name! iface (module-name mod))
3391 (set-module-version! iface (module-version mod))
3392 (set-module-kind! iface 'interface)
3393 (set-module-public-interface! mod iface)
3395 (let ((iface (or (module-public-interface mod)
3396 (fresh-interface!))))
3397 (set-module-obarray! iface (module-obarray mod))))
3399 ;; Re-export a imported variable
3401 (define (module-re-export! m names)
3402 (let ((public-i (module-public-interface m)))
3403 (for-each (lambda (name)
3404 (let* ((internal-name (if (pair? name) (car name) name))
3405 (external-name (if (pair? name) (cdr name) name))
3406 (var (module-variable m internal-name)))
3408 (error "Undefined variable:" internal-name))
3409 ((eq? var (module-local-variable m internal-name))
3410 (error "re-exporting local variable:" internal-name))
3412 (module-add! public-i external-name var)))))
3415 (define-syntax-rule (export name ...)
3416 (eval-when (eval load compile expand)
3417 (call-with-deferred-observers
3419 (module-export! (current-module) '(name ...))))))
3421 (define-syntax-rule (re-export name ...)
3422 (eval-when (eval load compile expand)
3423 (call-with-deferred-observers
3425 (module-re-export! (current-module) '(name ...))))))
3427 (define-syntax-rule (export! name ...)
3428 (eval-when (eval load compile expand)
3429 (call-with-deferred-observers
3431 (module-replace! (current-module) '(name ...))))))
3433 (define-syntax-rule (export-syntax name ...)
3436 (define-syntax-rule (re-export-syntax name ...)
3437 (re-export name ...))
3444 (define* (make-mutable-parameter init #:optional (converter identity))
3445 (let ((fluid (make-fluid (converter init))))
3447 (() (fluid-ref fluid))
3448 ((val) (fluid-set! fluid (converter val))))))
3453 ;;; {Handling of duplicate imported bindings}
3456 ;; Duplicate handlers take the following arguments:
3458 ;; module importing module
3459 ;; name conflicting name
3460 ;; int1 old interface where name occurs
3461 ;; val1 value of binding in old interface
3462 ;; int2 new interface where name occurs
3463 ;; val2 value of binding in new interface
3464 ;; var previous resolution or #f
3465 ;; val value of previous resolution
3467 ;; A duplicate handler can take three alternative actions:
3469 ;; 1. return #f => leave responsibility to next handler
3470 ;; 2. exit with an error
3471 ;; 3. return a variable resolving the conflict
3474 (define duplicate-handlers
3475 (let ((m (make-module 7)))
3477 (define (check module name int1 val1 int2 val2 var val)
3478 (scm-error 'misc-error
3480 "~A: `~A' imported from both ~A and ~A"
3481 (list (module-name module)
3487 (define (warn module name int1 val1 int2 val2 var val)
3488 (format (current-warning-port)
3489 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3490 (module-name module)
3496 (define (replace module name int1 val1 int2 val2 var val)
3497 (let ((old (or (and var (object-property var 'replace) var)
3498 (module-variable int1 name)))
3499 (new (module-variable int2 name)))
3500 (if (object-property old 'replace)
3501 (and (or (eq? old new)
3502 (not (object-property new 'replace)))
3504 (and (object-property new 'replace)
3507 (define (warn-override-core module name int1 val1 int2 val2 var val)
3508 (and (eq? int1 the-scm-module)
3510 (format (current-warning-port)
3511 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3512 (module-name module)
3515 (module-local-variable int2 name))))
3517 (define (first module name int1 val1 int2 val2 var val)
3518 (or var (module-local-variable int1 name)))
3520 (define (last module name int1 val1 int2 val2 var val)
3521 (module-local-variable int2 name))
3523 (define (noop module name int1 val1 int2 val2 var val)
3526 (set-module-name! m 'duplicate-handlers)
3527 (set-module-kind! m 'interface)
3528 (module-define! m 'check check)
3529 (module-define! m 'warn warn)
3530 (module-define! m 'replace replace)
3531 (module-define! m 'warn-override-core warn-override-core)
3532 (module-define! m 'first first)
3533 (module-define! m 'last last)
3534 (module-define! m 'merge-generics noop)
3535 (module-define! m 'merge-accessors noop)
3538 (define (lookup-duplicates-handlers handler-names)
3540 (map (lambda (handler-name)
3541 (or (module-symbol-local-binding
3542 duplicate-handlers handler-name #f)
3543 (error "invalid duplicate handler name:"
3545 (if (list? handler-names)
3547 (list handler-names)))))
3549 (define default-duplicate-binding-procedures
3550 (make-mutable-parameter #f))
3552 (define default-duplicate-binding-handler
3553 (make-mutable-parameter '(replace warn-override-core warn last)
3554 (lambda (handler-names)
3555 (default-duplicate-binding-procedures
3556 (lookup-duplicates-handlers handler-names))
3563 ;;; Load is tricky when combined with relative paths, compilation, and
3564 ;;; the file system. If a path is relative, what is it relative to? The
3565 ;;; path of the source file at the time it was compiled? The path of
3566 ;;; the compiled file? What if both or either were installed? And how
3567 ;;; do you get that information? Tricky, I say.
3569 ;;; To get around all of this, we're going to do something nasty, and
3570 ;;; turn `load' into a macro. That way it can know the path of the
3571 ;;; source file with respect to which it was invoked, so it can resolve
3572 ;;; relative paths with respect to the original source path.
3574 ;;; There is an exception, and that is that if the source file was in
3575 ;;; the load path when it was compiled, instead of looking up against
3576 ;;; the absolute source location, we load-from-path against the relative
3577 ;;; source location.
3580 (define %auto-compilation-options
3581 ;; Default `compile-file' option when auto-compiling.
3582 '(#:warnings (unbound-variable arity-mismatch format)))
3584 (define* (load-in-vicinity dir path #:optional reader)
3585 (define (canonical->suffix canon)
3587 ((string-prefix? "/" canon) canon)
3588 ((and (> (string-length canon) 2)
3589 (eqv? (string-ref canon 1) #\:))
3590 ;; Paths like C:... transform to /C...
3591 (string-append "/" (substring canon 0 1) (substring canon 2)))
3594 ;; Returns the .go file corresponding to `name'. Does not search load
3595 ;; paths, only the fallback path. If the .go file is missing or out of
3596 ;; date, and auto-compilation is enabled, will try auto-compilation, just
3597 ;; as primitive-load-path does internally. primitive-load is
3598 ;; unaffected. Returns #f if auto-compilation failed or was disabled.
3600 ;; NB: Unless we need to compile the file, this function should not cause
3601 ;; (system base compile) to be loaded up. For that reason compiled-file-name
3602 ;; partially duplicates functionality from (system base compile).
3604 (define (compiled-file-name canon-path)
3605 ;; FIXME: would probably be better just to append SHA1(canon-path)
3606 ;; to the %compile-fallback-path, to avoid deep directory stats.
3607 (and %compile-fallback-path
3609 %compile-fallback-path
3610 (canonical->suffix canon-path)
3611 (cond ((or (null? %load-compiled-extensions)
3612 (string-null? (car %load-compiled-extensions)))
3613 (warn "invalid %load-compiled-extensions"
3614 %load-compiled-extensions)
3616 (else (car %load-compiled-extensions))))))
3618 (define (fresh-compiled-file-name name go-path)
3621 (let* ((scmstat (stat name))
3622 (gostat (and (not %fresh-auto-compile)
3623 (stat go-path #f))))
3625 (or (> (stat:mtime gostat) (stat:mtime scmstat))
3626 (and (= (stat:mtime gostat) (stat:mtime scmstat))
3627 (>= (stat:mtimensec gostat)
3628 (stat:mtimensec scmstat)))))
3632 (format (current-warning-port)
3633 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
3636 (%load-should-auto-compile
3637 (%warn-auto-compilation-enabled)
3638 (format (current-warning-port) ";;; compiling ~a\n" name)
3641 (resolve-interface '(system base compile))
3644 #:opts %auto-compilation-options
3645 #:env (current-module))))
3646 (format (current-warning-port) ";;; compiled ~a\n" cfn)
3650 (format (current-warning-port)
3651 ";;; WARNING: compilation of ~a failed:\n" name)
3652 (for-each (lambda (s)
3653 (if (not (string-null? s))
3654 (format (current-warning-port) ";;; ~a\n" s)))
3656 (call-with-output-string
3657 (lambda (port) (print-exception port #f k args)))
3661 (define (absolute-path? path)
3662 (string-prefix? "/" path))
3664 (define (load-absolute abs-path)
3665 (let ((cfn (let ((canon (false-if-exception (canonicalize-path abs-path))))
3667 (let ((go-path (compiled-file-name canon)))
3669 (fresh-compiled-file-name abs-path go-path)))))))
3673 (%load-hook abs-path))
3674 (load-compiled cfn))
3675 (start-stack 'load-stack
3676 (primitive-load abs-path)))))
3678 (save-module-excursion
3680 (with-fluids ((current-reader reader)
3681 (%file-port-name-canonicalization 'relative))
3683 ((or (absolute-path? path))
3684 (load-absolute path))
3685 ((absolute-path? dir)
3686 (load-absolute (in-vicinity dir path)))
3688 (load-from-path (in-vicinity dir path))))))))
3691 (make-variable-transformer
3693 (let* ((src (syntax-source x))
3694 (file (and src (assq-ref src 'filename)))
3695 (dir (and (string? file) (dirname file))))
3698 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
3702 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
3706 ;;; {`cond-expand' for SRFI-0 support.}
3708 ;;; This syntactic form expands into different commands or
3709 ;;; definitions, depending on the features provided by the Scheme
3715 ;;; --> (cond-expand <cond-expand-clause>+)
3716 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3717 ;;; <cond-expand-clause>
3718 ;;; --> (<feature-requirement> <command-or-definition>*)
3719 ;;; <feature-requirement>
3720 ;;; --> <feature-identifier>
3721 ;;; | (and <feature-requirement>*)
3722 ;;; | (or <feature-requirement>*)
3723 ;;; | (not <feature-requirement>)
3724 ;;; <feature-identifier>
3725 ;;; --> <a symbol which is the name or alias of a SRFI>
3727 ;;; Additionally, this implementation provides the
3728 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3729 ;;; determine the implementation type and the supported standard.
3731 ;;; Currently, the following feature identifiers are supported:
3733 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3735 ;;; Remember to update the features list when adding more SRFIs.
3738 (define %cond-expand-features
3739 ;; Adjust the above comment when changing this.
3743 srfi-0 ;; cond-expand itself
3744 srfi-4 ;; homogenous numeric vectors
3745 srfi-6 ;; open-input-string etc, in the guile core
3746 srfi-13 ;; string library
3747 srfi-14 ;; character sets
3748 srfi-23 ;; `error` procedure
3749 srfi-39 ;; parameterize
3750 srfi-55 ;; require-extension
3751 srfi-61 ;; general cond clause
3754 ;; This table maps module public interfaces to the list of features.
3756 (define %cond-expand-table (make-hash-table 31))
3758 ;; Add one or more features to the `cond-expand' feature list of the
3761 (define (cond-expand-provide module features)
3762 (let ((mod (module-public-interface module)))
3764 (hashq-set! %cond-expand-table mod
3765 (append (hashq-ref %cond-expand-table mod '())
3768 (define-syntax cond-expand
3770 (define (module-has-feature? mod sym)
3771 (or-map (lambda (mod)
3772 (memq sym (hashq-ref %cond-expand-table mod '())))
3775 (define (condition-matches? condition)
3776 (syntax-case condition (and or not)
3778 (and-map condition-matches? #'(c ...)))
3780 (or-map condition-matches? #'(c ...)))
3782 (if (condition-matches? #'c) #f #t))
3785 (let ((sym (syntax->datum #'c)))
3786 (if (memq sym %cond-expand-features)
3788 (module-has-feature? (current-module) sym))))))
3790 (define (match clauses alternate)
3791 (syntax-case clauses ()
3792 (((condition form ...) . rest)
3793 (if (condition-matches? #'condition)
3795 (match #'rest alternate)))
3798 (syntax-case x (else)
3799 ((_ clause ... (else form ...))
3800 (match #'(clause ...)
3802 #'(begin form ...))))
3804 (match #'(clause ...)
3806 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
3808 ;; This procedure gets called from the startup code with a list of
3809 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3811 (define (use-srfis srfis)
3812 (process-use-modules
3814 (list (list 'srfi (string->symbol
3815 (string-append "srfi-" (number->string num))))))
3820 ;;; srfi-55: require-extension
3823 (define-syntax require-extension
3825 (syntax-case x (srfi)
3827 (and-map integer? (syntax->datum #'(n ...)))
3831 (datum->syntax x (symbol-append 'srfi- n)))
3833 (map number->string (syntax->datum #'(n ...)))))))
3834 #'(use-modules (srfi srfi-n) ...)))
3836 (identifier? #'type)
3837 (syntax-violation 'require-extension "Not a recognized extension type"
3841 ;;; Defining transparently inlinable procedures
3844 (define-syntax define-inlinable
3845 ;; Define a macro and a procedure such that direct calls are inlined, via
3846 ;; the macro expansion, whereas references in non-call contexts refer to
3847 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
3849 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
3851 (define prefix (string->symbol "% "))
3852 (define (make-procedure-name name)
3854 (symbol-append prefix (syntax->datum name)
3858 ((_ (name formals ...) body ...)
3859 (identifier? #'name)
3860 (with-syntax ((proc-name (make-procedure-name #'name))
3861 ((args ...) (generate-temporaries #'(formals ...))))
3863 (define (proc-name formals ...)
3864 (syntax-parameterize ((name (identifier-syntax proc-name)))
3866 (define-syntax-parameter name
3870 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
3871 (lambda (formals ...)
3876 #'proc-name))))))))))
3880 (define using-readline?
3881 (let ((using-readline? (make-fluid)))
3882 (make-procedure-with-setter
3883 (lambda () (fluid-ref using-readline?))
3884 (lambda (v) (fluid-set! using-readline? v)))))
3888 ;;; {Deprecated stuff}
3892 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3896 ;;; SRFI-4 in the default environment. FIXME: we should figure out how
3897 ;;; to deprecate this.
3901 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3905 ;;; A few identifiers that need to be defined in this file are really
3906 ;;; internal implementation details. We shove them off into internal
3907 ;;; modules, removing them from the (guile) module.
3910 (define-module (system syntax))
3913 (define (steal-bindings! from to ids)
3916 (let ((v (module-local-variable from sym)))
3917 (module-remove! from sym)
3918 (module-add! to sym v)))
3920 (module-export! to ids))
3922 (steal-bindings! the-root-module (resolve-module '(system syntax))
3923 '(syntax-local-binding
3925 syntax-locally-bound-identifiers
3926 syntax-session-id)))
3931 ;;; Place the user in the guile-user module.
3934 ;; Set filename to #f to prevent reload.
3935 (define-module (guile-user)
3936 #:autoload (system base compile) (compile compile-file)
3939 ;; Remain in the `(guile)' module at compilation-time so that the
3940 ;; `-Wunused-toplevel' warning works as expected.
3941 (eval-when (compile) (set-current-module the-root-module))
3943 ;;; boot-9.scm ends here