1 ;;; -*- mode: scheme; coding: utf-8; -*-
3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011
4 ;;;; Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 3 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
28 ;;; The module system (hence the hierarchical namespace) are defined in this
36 ;; Before compiling, make sure any symbols are resolved in the (guile)
37 ;; module, the primary location of those symbols, rather than in
38 ;; (guile-user), the default module that we compile in.
41 (set-current-module (resolve-module '(guile))))
48 ;; Define delimited continuation operators, and implement catch and throw in
51 (define make-prompt-tag
52 (lambda* (#:optional (stem "prompt"))
55 (define default-prompt-tag
56 ;; not sure if we should expose this to the user as a fluid
57 (let ((%default-prompt-tag (make-prompt-tag)))
59 %default-prompt-tag)))
61 (define (call-with-prompt tag thunk handler)
62 (@prompt tag (thunk) handler))
63 (define (abort-to-prompt tag . args)
67 ;; Define catch and with-throw-handler, using some common helper routines and a
68 ;; shared fluid. Hide the helpers in a lexical contour.
70 (define with-throw-handler #f)
72 ;; Ideally we'd like to be able to give these default values for all threads,
73 ;; even threads not created by Guile; but alack, that does not currently seem
74 ;; possible. So wrap the getters in thunks.
75 (define %running-exception-handlers (make-fluid))
76 (define %exception-handler (make-fluid))
78 (define (running-exception-handlers)
79 (or (fluid-ref %running-exception-handlers)
81 (fluid-set! %running-exception-handlers '())
83 (define (exception-handler)
84 (or (fluid-ref %exception-handler)
86 (fluid-set! %exception-handler default-exception-handler)
87 default-exception-handler)))
89 (define (default-exception-handler k . args)
93 ((not (pair? args)) 0)
94 ((integer? (car args)) (car args))
98 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
101 (define (default-throw-handler prompt-tag catch-k)
102 (let ((prev (exception-handler)))
103 (lambda (thrown-k . args)
104 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
105 (apply abort-to-prompt prompt-tag thrown-k args)
106 (apply prev thrown-k args)))))
108 (define (custom-throw-handler prompt-tag catch-k pre)
109 (let ((prev (exception-handler)))
110 (lambda (thrown-k . args)
111 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
112 (let ((running (running-exception-handlers)))
113 (with-fluids ((%running-exception-handlers (cons pre running)))
114 (if (not (memq pre running))
115 (apply pre thrown-k args))
118 (apply abort-to-prompt prompt-tag thrown-k args)
119 (apply prev thrown-k args))))
120 (apply prev thrown-k args)))))
123 (lambda* (k thunk handler #:optional pre-unwind-handler)
124 "Invoke @var{thunk} in the dynamic context of @var{handler} for
125 exceptions matching @var{key}. If thunk throws to the symbol
126 @var{key}, then @var{handler} is invoked this way:
128 (handler key args ...)
131 @var{key} is a symbol or @code{#t}.
133 @var{thunk} takes no arguments. If @var{thunk} returns
134 normally, that is the return value of @code{catch}.
136 Handler is invoked outside the scope of its own @code{catch}.
137 If @var{handler} again throws to the same key, a new handler
138 from further up the call chain is invoked.
140 If the key is @code{#t}, then a throw to @emph{any} symbol will
141 match this call to @code{catch}.
143 If a @var{pre-unwind-handler} is given and @var{thunk} throws
144 an exception that matches @var{key}, Guile calls the
145 @var{pre-unwind-handler} before unwinding the dynamic state and
146 invoking the main @var{handler}. @var{pre-unwind-handler} should
147 be a procedure with the same signature as @var{handler}, that
148 is @code{(lambda (key . args))}. It is typically used to save
149 the stack at the point where the exception occurred, but can also
150 query other parts of the dynamic state at that point, such as
153 A @var{pre-unwind-handler} can exit either normally or non-locally.
154 If it exits normally, Guile unwinds the stack and dynamic context
155 and then calls the normal (third argument) handler. If it exits
156 non-locally, that exit determines the continuation."
157 (if (not (or (symbol? k) (eqv? k #t)))
158 (scm-error "catch" 'wrong-type-arg
159 "Wrong type argument in position ~a: ~a"
160 (list 1 k) (list k)))
161 (let ((tag (make-prompt-tag "catch")))
167 (if pre-unwind-handler
168 (custom-throw-handler tag k pre-unwind-handler)
169 (default-throw-handler tag k))))
171 (lambda (cont k . args)
172 (apply handler k args))))))
174 (set! with-throw-handler
175 (lambda (k thunk pre-unwind-handler)
176 "Add @var{handler} to the dynamic context as a throw handler
177 for key @var{key}, then invoke @var{thunk}."
178 (if (not (or (symbol? k) (eqv? k #t)))
179 (scm-error "with-throw-handler" 'wrong-type-arg
180 "Wrong type argument in position ~a: ~a"
181 (list 1 k) (list k)))
182 (with-fluids ((%exception-handler
183 (custom-throw-handler #f k pre-unwind-handler)))
188 "Invoke the catch form matching @var{key}, passing @var{args} to the
191 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
193 If there is no handler at all, Guile prints an error and then exits."
194 (if (not (symbol? key))
195 ((exception-handler) 'wrong-type-arg "throw"
196 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
197 (apply (exception-handler) key args)))))
202 ;;; {R4RS compliance}
205 (primitive-load-path "ice-9/r4rs")
209 ;;; {Simple Debugging Tools}
212 ;; peek takes any number of arguments, writes them to the
213 ;; current ouput port, and returns the last argument.
214 ;; It is handy to wrap around an expression to look at
215 ;; a value each time is evaluated, e.g.:
217 ;; (+ 10 (troublesome-fn))
218 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
221 (define (peek . stuff)
226 (car (last-pair stuff)))
231 (define (warn . stuff)
232 (with-output-to-port (current-error-port)
235 (display ";;; WARNING ")
238 (car (last-pair stuff)))))
245 (define (provide sym)
246 (if (not (memq sym *features*))
247 (set! *features* (cons sym *features*))))
249 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
250 ;; provided? also checks to see if the module is available. We should do that
253 (define (provided? feature)
254 (and (memq feature *features*) #t))
261 (define (make-struct/no-tail vtable . args)
262 (apply make-struct vtable 0 args))
266 ;;; Boot versions of `map' and `for-each', enough to get the expander
275 (cons (f (car l)) (map1 (cdr l))))))
277 (let map2 ((l1 l1) (l2 l2))
280 (cons (f (car l1) (car l2))
281 (map2 (cdr l1) (cdr l2))))))
283 (let lp ((l1 l1) (rest rest))
286 (cons (apply f (car l1) (map car rest))
287 (lp (cdr l1) (map cdr rest))))))))
292 (let for-each1 ((l l))
296 (for-each1 (cdr l))))))
298 (let for-each2 ((l1 l1) (l2 l2))
301 (f (car l1) (car l2))
302 (for-each2 (cdr l1) (cdr l2))))))
304 (let lp ((l1 l1) (rest rest))
307 (apply f (car l1) (map car rest))
308 (lp (cdr l1) (map cdr rest))))))))
310 ;;; {and-map and or-map}
312 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
313 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
318 ;; Apply f to successive elements of l until exhaustion or f returns #f.
319 ;; If returning early, return #f. Otherwise, return the last value returned
320 ;; by f. If f has never been called because l is empty, return #t.
322 (define (and-map f lst)
323 (let loop ((result #t)
328 (loop (f (car l)) (cdr l))))))
332 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
333 ;; If returning early, return the return value of f.
335 (define (or-map f lst)
336 (let loop ((result #f)
340 (loop (f (car l)) (cdr l))))))
344 ;; let format alias simple-format until the more complete version is loaded
346 (define format simple-format)
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 (or (string-any-c-code char_pred s start (1- end))
356 (char_pred (string-ref s (1- end))))
357 (string-any-c-code char_pred s start end))))
359 ;; this is scheme wrapping the C code so the final pred call is a tail call,
362 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
363 (if (and (procedure? char_pred)
365 (<= end (string-length s))) ;; let c-code handle range error
366 (and (string-every-c-code char_pred s start (1- end))
367 (char_pred (string-ref s (1- end))))
368 (string-every-c-code char_pred s start end))))
370 ;; A variant of string-fill! that we keep for compatability
372 (define (substring-fill! str start end fill)
373 (string-fill! str fill start end))
377 ;; Define a minimal stub of the module API for psyntax, before modules
379 (define (module-name x)
381 (define (module-add! module sym var)
382 (hashq-set! (%get-pre-modules-obarray) sym var))
383 (define (module-define! module sym val)
384 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
386 (variable-set! v val)
387 (module-add! (current-module) sym (make-variable val)))))
388 (define (module-ref module sym)
389 (let ((v (module-variable module sym)))
390 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
391 (define (resolve-module . args)
394 ;; API provided by psyntax
395 (define syntax-violation #f)
396 (define datum->syntax #f)
397 (define syntax->datum #f)
398 (define syntax-source #f)
399 (define identifier? #f)
400 (define generate-temporaries #f)
401 (define bound-identifier=? #f)
402 (define free-identifier=? #f)
404 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
405 ;; expanded macros, to dispatch an input against a set of patterns.
406 (define $sc-dispatch #f)
409 (primitive-load-path "ice-9/psyntax-pp")
410 ;; The binding for `macroexpand' has now been overridden, making psyntax the
417 ((_ x y ...) (if x (and y ...) #f))))
423 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
425 ;; The "maybe-more" bits are something of a hack, so that we can support
426 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
429 (syntax-rules (=> else)
430 ((_ "maybe-more" test consequent)
431 (if test consequent))
433 ((_ "maybe-more" test consequent clause ...)
434 (if test consequent (cond clause ...)))
436 ((_ (else else1 else2 ...))
437 (begin else1 else2 ...))
439 ((_ (test => receiver) more-clause ...)
441 (cond "maybe-more" t (receiver t) more-clause ...)))
443 ((_ (generator guard => receiver) more-clause ...)
444 (call-with-values (lambda () generator)
447 (apply guard t) (apply receiver t) more-clause ...))))
449 ((_ (test => receiver ...) more-clause ...)
450 (syntax-violation 'cond "wrong number of receiver expressions"
451 '(test => receiver ...)))
452 ((_ (generator guard => receiver ...) more-clause ...)
453 (syntax-violation 'cond "wrong number of receiver expressions"
454 '(generator guard => receiver ...)))
456 ((_ (test) more-clause ...)
458 (cond "maybe-more" t t more-clause ...)))
460 ((_ (test body1 body2 ...) more-clause ...)
462 test (begin body1 body2 ...) more-clause ...))))
468 (let ((atom-key (key ...)))
469 (case atom-key clauses ...)))
471 (else result1 result2 ...))
472 (begin result1 result2 ...))
474 ((atoms ...) result1 result2 ...))
475 (if (memv key '(atoms ...))
476 (begin result1 result2 ...)))
478 ((atoms ...) result1 result2 ...)
480 (if (memv key '(atoms ...))
481 (begin result1 result2 ...)
482 (case key clause clauses ...)))))
486 ((do ((var init step ...) ...)
499 (loop (do "step" var step ...)
509 ((_ exp) (make-promise (lambda () exp)))))
511 (include-from-path "ice-9/quasisyntax")
513 (define-syntax current-source-location
517 (with-syntax ((s (datum->syntax x (syntax-source x))))
520 (define-syntax define-once
524 (if (module-locally-bound? (current-module) 'sym) sym val)))))
526 ;;; The real versions of `map' and `for-each', with cycle detection, and
527 ;;; that use reverse! instead of recursion in the case of `map'.
532 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
535 (if (eq? tortoise hare)
536 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
538 (map1 (cdr hare) (cdr tortoise) #f
539 (cons (f (car hare)) out)))
540 (map1 (cdr hare) tortoise #t
541 (cons (f (car hare)) out)))
544 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
548 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
553 (scm-error 'wrong-type-arg "map"
555 "List of wrong length: ~S"
559 (map2 (cdr h1) (cdr h2) t1 t2 #t
560 (cons (f (car h1) (car h2)) out)))
562 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
565 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
568 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
569 (cons (f (car h1) (car h2)) out)))))
571 ((and (null? h1) (null? h2))
575 (scm-error 'wrong-type-arg "map"
577 "List of wrong length: ~S"
581 (scm-error 'wrong-type-arg "map"
586 (let ((len (length l1)))
587 (let mapn ((rest rest))
589 (if (= (length (car rest)) len)
591 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
592 (list (car rest)) #f)))))
593 (let mapn ((l1 l1) (rest rest) (out '()))
596 (mapn (cdr l1) (map cdr rest)
597 (cons (apply f (car l1) (map car rest)) out)))))))
599 (define map-in-order map)
604 (let for-each1 ((hare l) (tortoise l) (move? #f))
607 (if (eq? tortoise hare)
608 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
612 (for-each1 (cdr hare) (cdr tortoise) #f)))
615 (for-each1 (cdr hare) tortoise #t)))
617 (if (not (null? hare))
618 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
622 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
624 ((and (pair? h1) (pair? h2))
627 (f (car h1) (car h2))
628 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
630 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
633 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
636 (f (car h1) (car h2))
637 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
640 (or (null? h2) (pair? h2))
641 (and (pair? h1) (null? h2)))
645 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
648 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
652 (let ((len (length l1)))
653 (let for-eachn ((rest rest))
655 (if (= (length (car rest)) len)
656 (for-eachn (cdr rest))
657 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
658 (list (car rest)) #f)))))
660 (let for-eachn ((l1 l1) (rest rest))
663 (apply f (car l1) (map car rest))
664 (for-eachn (cdr l1) (map cdr rest))))))))
670 ;;; Extensible exception printing.
673 (define set-exception-printer! #f)
674 ;; There is already a definition of print-exception from backtrace.c
675 ;; that we will override.
677 (let ((exception-printers '()))
678 (define (print-location frame port)
679 (let ((source (and=> frame frame-source)))
680 ;; source := (addr . (filename . (line . column)))
682 (let ((filename (or (cadr source) "<unnamed port>"))
683 (line (caddr source))
684 (col (cdddr source)))
685 (format port "~a:~a:~a: " filename (1+ line) col))
686 (format port "ERROR: "))))
688 (set! set-exception-printer!
690 (set! exception-printers (acons key proc exception-printers))))
692 (set! print-exception
693 (lambda (port frame key args)
694 (define (default-printer)
695 (format port "Throw to key `~a' with args `~s'." key args))
698 (let ((proc (frame-procedure frame)))
699 (print-location frame port)
700 (format port "In procedure ~a:\n"
701 (or (procedure-name proc) proc))))
703 (print-location frame port)
706 (let ((printer (assq-ref exception-printers key)))
708 (printer port key args default-printer)
711 (format port "Error while printing exception.")))
713 (force-output port))))
716 ;;; Printers for those keys thrown by Guile.
719 (define (scm-error-printer port key args default-printer)
720 ;; Abuse case-lambda as a pattern matcher, given that we don't have
721 ;; ice-9 match at this point.
723 ((subr msg args . rest)
725 (format port "In procedure ~a: " subr))
726 (apply format port msg (or args '())))
727 (_ (default-printer)))
730 (define (syntax-error-printer port key args default-printer)
732 ((who what where form subform . extra)
733 (format port "Syntax error:\n")
735 (let ((file (or (assq-ref where 'filename) "unknown file"))
736 (line (and=> (assq-ref where 'line) 1+))
737 (col (assq-ref where 'column)))
738 (format port "~a:~a:~a: " file line col))
739 (format port "unknown location: "))
741 (format port "~a: " who))
742 (format port "~a" what)
744 (format port " in subform ~s of ~s" subform form)
746 (format port " in form ~s" form))))
747 (_ (default-printer)))
750 (set-exception-printer! 'goops-error scm-error-printer)
751 (set-exception-printer! 'host-not-found scm-error-printer)
752 (set-exception-printer! 'keyword-argument-error scm-error-printer)
753 (set-exception-printer! 'misc-error scm-error-printer)
754 (set-exception-printer! 'no-data scm-error-printer)
755 (set-exception-printer! 'no-recovery scm-error-printer)
756 (set-exception-printer! 'null-pointer-error scm-error-printer)
757 (set-exception-printer! 'out-of-range scm-error-printer)
758 (set-exception-printer! 'program-error scm-error-printer)
759 (set-exception-printer! 'read-error scm-error-printer)
760 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
761 (set-exception-printer! 'signal scm-error-printer)
762 (set-exception-printer! 'stack-overflow scm-error-printer)
763 (set-exception-printer! 'system-error scm-error-printer)
764 (set-exception-printer! 'try-again scm-error-printer)
765 (set-exception-printer! 'unbound-variable scm-error-printer)
766 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
767 (set-exception-printer! 'wrong-type-arg scm-error-printer)
769 (set-exception-printer! 'syntax-error syntax-error-printer))
777 (define-syntax define-macro
781 ((_ (macro . args) doc body1 body ...)
782 (string? (syntax->datum #'doc))
783 #'(define-macro macro doc (lambda args body1 body ...)))
784 ((_ (macro . args) body ...)
785 #'(define-macro macro #f (lambda args body ...)))
786 ((_ macro doc transformer)
787 (or (string? (syntax->datum #'doc))
788 (not (syntax->datum #'doc)))
789 #'(define-syntax macro
792 #((macro-type . defmacro)
793 (defmacro-args args))
796 (let ((v (syntax->datum #'args)))
797 (datum->syntax y (apply transformer v)))))))))))
799 (define-syntax defmacro
801 "Define a defmacro, with the old lispy defun syntax."
803 ((_ macro args doc body1 body ...)
804 (string? (syntax->datum #'doc))
805 #'(define-macro macro doc (lambda args body1 body ...)))
806 ((_ macro args body ...)
807 #'(define-macro macro #f (lambda args body ...))))))
816 (define-syntax begin-deprecated
820 (if (include-deprecated-features)
821 #'(begin form form* ...)
826 ;;; {Trivial Functions}
829 (define (identity x) x)
831 (define (compose proc . rest)
832 "Compose PROC with the procedures in REST, such that the last one in
833 REST is applied first and PROC last, and return the resulting procedure.
834 The given procedures must have compatible arity."
837 (let ((g (apply compose rest)))
839 (call-with-values (lambda () (apply g args)) proc)))))
841 (define (negate proc)
842 "Return a procedure with the same arity as PROC that returns the `not'
845 (not (apply proc args))))
847 (define (const value)
848 "Return a procedure that accepts any number of arguments and returns
853 (define (and=> value procedure) (and value (procedure value)))
854 (define call/cc call-with-current-continuation)
856 (define-syntax false-if-exception
861 (lambda (k . args) #f)))))
865 ;;; {General Properties}
868 ;; Properties are a lispy way to associate random info with random objects.
869 ;; Traditionally properties are implemented as an alist or a plist actually
870 ;; pertaining to the object in question.
872 ;; These "object properties" have the advantage that they can be associated with
873 ;; any object, even if the object has no plist. Object properties are good when
874 ;; you are extending pre-existing objects in unexpected ways. They also present
875 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
876 ;; type that always has properties, it's often still best to store those
877 ;; properties within the object itself.
879 (define (make-object-property)
880 (define-syntax with-mutex
883 (dynamic-wind (lambda () (lock-mutex lock))
885 (lambda () (unlock-mutex lock))))))
886 (let ((prop (make-weak-key-hash-table))
888 (make-procedure-with-setter
889 (lambda (obj) (with-mutex lock (hashq-ref prop obj)))
890 (lambda (obj val) (with-mutex lock (hashq-set! prop obj val))))))
895 ;;; {Symbol Properties}
898 ;;; Symbol properties are something you see in old Lisp code. In most current
899 ;;; Guile code, symbols are not used as a data structure -- they are used as
900 ;;; keys into other data structures.
902 (define (symbol-property sym prop)
903 (let ((pair (assoc prop (symbol-pref sym))))
904 (and pair (cdr pair))))
906 (define (set-symbol-property! sym prop val)
907 (let ((pair (assoc prop (symbol-pref sym))))
910 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
912 (define (symbol-property-remove! sym prop)
913 (let ((pair (assoc prop (symbol-pref sym))))
915 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
922 (define (array-shape a)
923 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
924 (array-dimensions a)))
931 ;;; It's much better if you can use lambda* / define*, of course.
933 (define (kw-arg-ref args kw)
934 (let ((rem (member kw args)))
935 (and rem (pair? (cdr rem)) (cadr rem))))
942 (define (struct-layout s)
943 (struct-ref (struct-vtable s) vtable-index-layout))
950 ;; Printing records: by default, records are printed as
952 ;; #<type-name field1: val1 field2: val2 ...>
954 ;; You can change that by giving a custom printing function to
955 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
956 ;; will be called like
958 ;; (<printer> object port)
960 ;; It should print OBJECT to PORT.
962 (define (inherit-print-state old-port new-port)
963 (if (get-print-state old-port)
964 (port-with-print-state new-port (get-print-state old-port))
967 ;; 0: type-name, 1: fields, 2: constructor
968 (define record-type-vtable
969 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
970 ;; that we need to expose the bare vtable-vtable to Scheme.
971 (make-vtable-vtable "prprpw" 0
973 (cond ((eq? s record-type-vtable)
974 (display "#<record-type-vtable>" p))
976 (display "#<record-type " p)
977 (display (record-type-name s) p)
980 (define (record-type? obj)
981 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
983 (define* (make-record-type type-name fields #:optional printer)
984 ;; Pre-generate constructors for nfields < 20.
985 (define-syntax make-constructor
987 (define *max-static-argument-count* 20)
988 (define (make-formals n)
994 (string (integer->char (+ (char->integer #\a) i)))))
998 ((_ rtd exp) (not (identifier? #'exp))
1000 (make-constructor rtd n)))
1004 (if (< n *max-static-argument-count*)
1005 (cons (with-syntax (((formal ...) (make-formals n))
1008 (lambda (formal ...)
1009 (make-struct rtd 0 formal ...))))
1014 (if (= (length args) nfields)
1015 (apply make-struct rtd 0 args)
1016 (scm-error 'wrong-number-of-args
1017 (format #f "make-~a" type-name)
1018 "Wrong number of arguments" '() #f)))))))))
1020 (define (default-record-printer s p)
1022 (display (record-type-name (record-type-descriptor s)) p)
1023 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1026 ((not (null? fields))
1028 (display (car fields) p)
1030 (display (struct-ref s off) p)
1031 (loop (cdr fields) (+ 1 off)))))
1034 (let ((rtd (make-struct record-type-vtable 0
1036 (apply string-append
1037 (map (lambda (f) "pw") fields)))
1038 (or printer default-record-printer)
1040 (copy-tree fields))))
1041 (struct-set! rtd (+ vtable-offset-user 2)
1042 (make-constructor rtd (length fields)))
1043 ;; Temporary solution: Associate a name to the record type descriptor
1044 ;; so that the object system can create a wrapper class for it.
1045 (set-struct-vtable-name! rtd (if (symbol? type-name)
1047 (string->symbol type-name)))
1050 (define (record-type-name obj)
1051 (if (record-type? obj)
1052 (struct-ref obj vtable-offset-user)
1053 (error 'not-a-record-type obj)))
1055 (define (record-type-fields obj)
1056 (if (record-type? obj)
1057 (struct-ref obj (+ 1 vtable-offset-user))
1058 (error 'not-a-record-type obj)))
1060 (define* (record-constructor rtd #:optional field-names)
1061 (if (not field-names)
1062 (struct-ref rtd (+ 2 vtable-offset-user))
1064 `(lambda ,field-names
1065 (make-struct ',rtd 0 ,@(map (lambda (f)
1066 (if (memq f field-names)
1069 (record-type-fields rtd)))))))
1071 (define (record-predicate rtd)
1072 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1074 (define (%record-type-error rtd obj) ;; private helper
1075 (or (eq? rtd (record-type-descriptor obj))
1076 (scm-error 'wrong-type-arg "%record-type-check"
1077 "Wrong type record (want `~S'): ~S"
1078 (list (record-type-name rtd) obj)
1081 (define (record-accessor rtd field-name)
1082 (let ((pos (list-index (record-type-fields rtd) field-name)))
1084 (error 'no-such-field field-name))
1086 (if (eq? (struct-vtable obj) rtd)
1087 (struct-ref obj pos)
1088 (%record-type-error rtd obj)))))
1090 (define (record-modifier rtd field-name)
1091 (let ((pos (list-index (record-type-fields rtd) field-name)))
1093 (error 'no-such-field field-name))
1095 (if (eq? (struct-vtable obj) rtd)
1096 (struct-set! obj pos val)
1097 (%record-type-error rtd obj)))))
1099 (define (record? obj)
1100 (and (struct? obj) (record-type? (struct-vtable obj))))
1102 (define (record-type-descriptor obj)
1105 (error 'not-a-record obj)))
1114 (define (->bool x) (not (not x)))
1121 (define (symbol-append . args)
1122 (string->symbol (apply string-append (map symbol->string args))))
1124 (define (list->symbol . args)
1125 (string->symbol (apply list->string args)))
1127 (define (symbol . args)
1128 (string->symbol (apply string args)))
1135 (define (list-index l k)
1138 (and (not (null? l))
1141 (loop (+ n 1) (cdr l))))))
1145 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1146 ;; `stat' accessors.
1147 (primitive-load-path "ice-9/posix")
1149 (if (provided? 'socket)
1150 (primitive-load-path "ice-9/networking"))
1152 ;; For reference, Emacs file-exists-p uses stat in this same way.
1153 (define file-exists?
1154 (if (provided? 'posix)
1156 (->bool (stat str #f)))
1158 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
1160 (if port (begin (close-port port) #t)
1163 (define file-is-directory?
1164 (if (provided? 'posix)
1166 (eq? (stat:type (stat str)) 'directory))
1168 (let ((port (catch 'system-error
1169 (lambda () (open-file (string-append str "/.")
1172 (if port (begin (close-port port) #t)
1175 (define (system-error-errno args)
1176 (if (eq? (car args) 'system-error)
1177 (car (list-ref args 4))
1182 ;;; {Error Handling}
1188 (scm-error 'misc-error #f "?" #f #f))
1190 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1191 (scm-error 'misc-error #f msg (cons message args) #f)))))
1195 ;;; {Time Structures}
1198 (define (tm:sec obj) (vector-ref obj 0))
1199 (define (tm:min obj) (vector-ref obj 1))
1200 (define (tm:hour obj) (vector-ref obj 2))
1201 (define (tm:mday obj) (vector-ref obj 3))
1202 (define (tm:mon obj) (vector-ref obj 4))
1203 (define (tm:year obj) (vector-ref obj 5))
1204 (define (tm:wday obj) (vector-ref obj 6))
1205 (define (tm:yday obj) (vector-ref obj 7))
1206 (define (tm:isdst obj) (vector-ref obj 8))
1207 (define (tm:gmtoff obj) (vector-ref obj 9))
1208 (define (tm:zone obj) (vector-ref obj 10))
1210 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1211 (define (set-tm:min obj val) (vector-set! obj 1 val))
1212 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1213 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1214 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1215 (define (set-tm:year obj val) (vector-set! obj 5 val))
1216 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1217 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1218 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1219 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1220 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1222 (define (tms:clock obj) (vector-ref obj 0))
1223 (define (tms:utime obj) (vector-ref obj 1))
1224 (define (tms:stime obj) (vector-ref obj 2))
1225 (define (tms:cutime obj) (vector-ref obj 3))
1226 (define (tms:cstime obj) (vector-ref obj 4))
1230 ;;; {File Descriptors and Ports}
1233 (define file-position ftell)
1234 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1235 (seek port offset whence))
1237 (define (move->fdes fd/port fd)
1238 (cond ((integer? fd/port)
1239 (dup->fdes fd/port fd)
1243 (primitive-move->fdes fd/port fd)
1244 (set-port-revealed! fd/port 1)
1247 (define (release-port-handle port)
1248 (let ((revealed (port-revealed port)))
1250 (set-port-revealed! port (- revealed 1)))))
1255 (fdopen (dup->fdes port/fd) mode))
1256 ((port/fd mode new-fd)
1257 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1258 (set-port-revealed! port 1)
1264 (dup->port port/fd "r"))
1266 (dup->port port/fd "r" new-fd))))
1268 (define dup->outport
1271 (dup->port port/fd "w"))
1273 (dup->port port/fd "w" new-fd))))
1278 (if (integer? port/fd)
1280 (dup->port port/fd (port-mode port/fd))))
1282 (if (integer? port/fd)
1283 (dup->fdes port/fd new-fd)
1284 (dup->port port/fd (port-mode port/fd) new-fd)))))
1286 (define (duplicate-port port modes)
1287 (dup->port port modes))
1289 (define (fdes->inport fdes)
1290 (let loop ((rest-ports (fdes->ports fdes)))
1291 (cond ((null? rest-ports)
1292 (let ((result (fdopen fdes "r")))
1293 (set-port-revealed! result 1)
1295 ((input-port? (car rest-ports))
1296 (set-port-revealed! (car rest-ports)
1297 (+ (port-revealed (car rest-ports)) 1))
1300 (loop (cdr rest-ports))))))
1302 (define (fdes->outport fdes)
1303 (let loop ((rest-ports (fdes->ports fdes)))
1304 (cond ((null? rest-ports)
1305 (let ((result (fdopen fdes "w")))
1306 (set-port-revealed! result 1)
1308 ((output-port? (car rest-ports))
1309 (set-port-revealed! (car rest-ports)
1310 (+ (port-revealed (car rest-ports)) 1))
1313 (loop (cdr rest-ports))))))
1315 (define (port->fdes port)
1316 (set-port-revealed! port (+ (port-revealed port) 1))
1319 (define (setenv name value)
1321 (putenv (string-append name "=" value))
1324 (define (unsetenv name)
1325 "Remove the entry for NAME from the environment."
1333 (define (in-vicinity vicinity file)
1334 (let ((tail (let ((len (string-length vicinity)))
1337 (string-ref vicinity (- len 1))))))
1338 (string-append vicinity
1347 ;;; {Help for scm_shell}
1349 ;;; The argument-processing code used by Guile-based shells generates
1350 ;;; Scheme code based on the argument list. This page contains help
1351 ;;; functions for the code it generates.
1354 (define (command-line) (program-arguments))
1356 ;; This is mostly for the internal use of the code generated by
1357 ;; scm_compile_shell_switches.
1359 (define (load-user-init)
1360 (let* ((home (or (getenv "HOME")
1361 (false-if-exception (passwd:dir (getpwuid (getuid))))
1362 "/")) ;; fallback for cygwin etc.
1363 (init-file (in-vicinity home ".guile")))
1364 (if (file-exists? init-file)
1365 (primitive-load init-file))))
1369 ;;; {The interpreter stack}
1372 ;; %stacks defined in stacks.c
1373 (define (%start-stack tag thunk)
1374 (let ((prompt-tag (make-prompt-tag "start-stack")))
1378 (with-fluids ((%stacks (acons tag prompt-tag
1379 (or (fluid-ref %stacks) '()))))
1382 (%start-stack tag (lambda () (apply k args)))))))
1383 (define-syntax start-stack
1386 (%start-stack tag (lambda () exp)))))
1390 ;;; {Loading by paths}
1393 ;;; Load a Scheme source file named NAME, searching for it in the
1394 ;;; directories listed in %load-path, and applying each of the file
1395 ;;; name extensions listed in %load-extensions.
1396 (define (load-from-path name)
1397 (start-stack 'load-stack
1398 (primitive-load-path name)))
1400 (define %load-verbosely #f)
1401 (define (assert-load-verbosity v) (set! %load-verbosely v))
1403 (define (%load-announce file)
1405 (with-output-to-port (current-error-port)
1408 (display "loading ")
1413 (set! %load-hook %load-announce)
1417 ;;; {Reader Extensions}
1419 ;;; Reader code for various "#c" forms.
1422 (define read-eval? (make-fluid))
1423 (fluid-set! read-eval? #f)
1424 (read-hash-extend #\.
1426 (if (fluid-ref read-eval?)
1427 (eval (read port) (interaction-environment))
1429 "#. read expansion found and read-eval? is #f."))))
1433 ;;; {Low Level Modules}
1435 ;;; These are the low level data structures for modules.
1437 ;;; Every module object is of the type 'module-type', which is a record
1438 ;;; consisting of the following members:
1440 ;;; - eval-closure: the function that defines for its module the strategy that
1441 ;;; shall be followed when looking up symbols in the module.
1443 ;;; An eval-closure is a function taking two arguments: the symbol to be
1444 ;;; looked up and a boolean value telling whether a binding for the symbol
1445 ;;; should be created if it does not exist yet. If the symbol lookup
1446 ;;; succeeded (either because an existing binding was found or because a new
1447 ;;; binding was created), a variable object representing the binding is
1448 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1449 ;;; closure does not take the module to be searched as an argument: During
1450 ;;; construction of the eval-closure, the eval-closure has to store the
1451 ;;; module it belongs to in its environment. This means, that any
1452 ;;; eval-closure can belong to only one module.
1454 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1455 ;;; special cases of eval-closures are to be distinguished: During startup
1456 ;;; the module system is not yet activated. In this phase, no modules are
1457 ;;; defined and all bindings are automatically stored by the system in the
1458 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1459 ;;; functions which require an eval-closure as their argument need to be
1460 ;;; passed the value #f.
1462 ;;; The other two special cases of eval-closures are the
1463 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1464 ;;; behave equally for the case that no new binding is to be created. The
1465 ;;; difference between the two comes in, when the boolean argument to the
1466 ;;; eval-closure indicates that a new binding shall be created if it is not
1469 ;;; Given that no new binding shall be created, both standard eval-closures
1470 ;;; define the following standard strategy of searching bindings in the
1471 ;;; module: First, the module's obarray is searched for the symbol. Second,
1472 ;;; if no binding for the symbol was found in the module's obarray, the
1473 ;;; module's binder procedure is exececuted. If this procedure did not
1474 ;;; return a binding for the symbol, the modules referenced in the module's
1475 ;;; uses list are recursively searched for a binding of the symbol. If the
1476 ;;; binding can not be found in these modules also, the symbol lookup has
1479 ;;; If a new binding shall be created, the standard-interface-eval-closure
1480 ;;; immediately returns indicating failure. That is, it does not even try
1481 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1482 ;;; first search the obarray, and if no binding was found there, would
1483 ;;; create a new binding in the obarray, therefore not calling the binder
1484 ;;; procedure or searching the modules in the uses list.
1486 ;;; The explanation of the following members obarray, binder and uses
1487 ;;; assumes that the symbol lookup follows the strategy that is defined in
1488 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1490 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1491 ;;; hash table, the definitions are found that are local to the module (that
1492 ;;; is, not imported from other modules). When looking up bindings in the
1493 ;;; module, this hash table is searched first.
1495 ;;; - binder: either #f or a function taking a module and a symbol argument.
1496 ;;; If it is a function it is called after the obarray has been
1497 ;;; unsuccessfully searched for a binding. It then can provide bindings
1498 ;;; that would otherwise not be found locally in the module.
1500 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1501 ;;; These modules are the third place queried for bindings after the obarray
1502 ;;; has been unsuccessfully searched and the binder function did not deliver
1503 ;;; a result either.
1505 ;;; - transformer: either #f or a function taking a scheme expression as
1506 ;;; delivered by read. If it is a function, it will be called to perform
1507 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1508 ;;; expression. The output of the transformer function will then be passed
1509 ;;; to Guile's internal memoizer. This means that the output must be valid
1510 ;;; scheme code. The only exception is, that the output may make use of the
1511 ;;; syntax extensions provided to identify the modules that a binding
1514 ;;; - name: the name of the module. This is used for all kinds of printing
1515 ;;; outputs. In certain places the module name also serves as a way of
1516 ;;; identification. When adding a module to the uses list of another
1517 ;;; module, it is made sure that the new uses list will not contain two
1518 ;;; modules of the same name.
1520 ;;; - kind: classification of the kind of module. The value is (currently?)
1521 ;;; only used for printing. It has no influence on how a module is treated.
1522 ;;; Currently the following values are used when setting the module kind:
1523 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1524 ;;; is set, it defaults to 'module.
1526 ;;; - duplicates-handlers: a list of procedures that get called to make a
1527 ;;; choice between two duplicate bindings when name clashes occur. See the
1528 ;;; `duplicate-handlers' global variable below.
1530 ;;; - observers: a list of procedures that get called when the module is
1533 ;;; - weak-observers: a weak-key hash table of procedures that get called
1534 ;;; when the module is modified. See `module-observe-weak' for details.
1536 ;;; In addition, the module may (must?) contain a binding for
1537 ;;; `%module-public-interface'. This variable should be bound to a module
1538 ;;; representing the exported interface of a module. See the
1539 ;;; `module-public-interface' and `module-export!' procedures.
1541 ;;; !!! warning: The interface to lazy binder procedures is going
1542 ;;; to be changed in an incompatible way to permit all the basic
1543 ;;; module ops to be virtualized.
1545 ;;; (make-module size use-list lazy-binding-proc) => module
1546 ;;; module-{obarray,uses,binder}[|-set!]
1547 ;;; (module? obj) => [#t|#f]
1548 ;;; (module-locally-bound? module symbol) => [#t|#f]
1549 ;;; (module-bound? module symbol) => [#t|#f]
1550 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1551 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1552 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1553 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1554 ;;; (module-symbol-binding module symbol opt-value)
1555 ;;; => [ <obj> | opt-value | an error occurs ]
1556 ;;; (module-make-local-var! module symbol) => #<variable...>
1557 ;;; (module-add! module symbol var) => unspecified
1558 ;;; (module-remove! module symbol) => unspecified
1559 ;;; (module-for-each proc module) => unspecified
1560 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1561 ;;; (set-current-module module) => unspecified
1562 ;;; (current-module) => #<module...>
1568 ;;; {Printing Modules}
1571 ;; This is how modules are printed. You can re-define it.
1572 (define (%print-module mod port)
1574 (display (or (module-kind mod) "module") port)
1576 (display (module-name mod) port)
1578 (display (number->string (object-address mod) 16) port)
1582 ;; Locally extend the syntax to allow record accessors to be defined at
1583 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1584 ;; the setters, in order to allow for redefinition of the record type; not
1585 ;; relevant in the case of modules, but perhaps if we make this public, it
1588 ((define-record-type
1590 (define (make-id scope . fragments)
1591 (datum->syntax #'scope
1592 (apply symbol-append
1594 (if (symbol? x) x (syntax->datum x)))
1597 (define (getter rtd type-name field slot)
1598 #`(define #,(make-id rtd type-name '- field)
1600 (lambda (#,type-name)
1601 (if (eq? (struct-vtable #,type-name) rtd)
1602 (struct-ref #,type-name #,slot)
1603 (%record-type-error rtd #,type-name))))))
1605 (define (setter rtd type-name field slot)
1606 #`(define #,(make-id rtd 'set- type-name '- field '!)
1608 (lambda (#,type-name val)
1609 (if (eq? (struct-vtable #,type-name) rtd)
1610 (struct-set! #,type-name #,slot val)
1611 (%record-type-error rtd #,type-name))))))
1613 (define (accessors rtd type-name fields n exp)
1614 (syntax-case fields ()
1616 (((field #:no-accessors) field* ...) (identifier? #'field)
1617 (accessors rtd type-name #'(field* ...) (1+ n)
1619 (((field #:no-setter) field* ...) (identifier? #'field)
1620 (accessors rtd type-name #'(field* ...) (1+ n)
1622 #,(getter rtd type-name #'field n))))
1623 (((field #:no-getter) field* ...) (identifier? #'field)
1624 (accessors rtd type-name #'(field* ...) (1+ n)
1626 #,(setter rtd type-name #'field n))))
1627 ((field field* ...) (identifier? #'field)
1628 (accessors rtd type-name #'(field* ...) (1+ n)
1630 #,(getter rtd type-name #'field n)
1631 #,(setter rtd type-name #'field n))))))
1633 (define (predicate rtd type-name fields exp)
1635 rtd type-name fields 0
1638 (define (#,(make-id rtd type-name '?) obj)
1639 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1641 (define (field-list fields)
1642 (syntax-case fields ()
1644 (((f . opts) . rest) (identifier? #'f)
1645 (cons #'f (field-list #'rest)))
1646 ((f . rest) (identifier? #'f)
1647 (cons #'f (field-list #'rest)))))
1649 (define (constructor rtd type-name fields exp)
1650 (let ((ctor (make-id rtd type-name '-constructor))
1651 (args (field-list fields)))
1652 (predicate rtd type-name fields
1657 (make-struct rtd 0 #,@args))))
1658 (struct-set! #,rtd (+ vtable-offset-user 2)
1661 (define (type type-name printer fields)
1662 (define (make-layout)
1663 (let lp ((fields fields) (slots '()))
1664 (syntax-case fields ()
1665 (() (datum->syntax #'here
1667 (apply string-append slots))))
1668 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1670 (let ((rtd (make-id type-name type-name '-type)))
1671 (constructor rtd type-name fields
1674 (make-struct record-type-vtable 0
1678 '#,(field-list fields)))
1679 (set-struct-vtable-name! #,rtd '#,type-name)))))
1682 ((_ type-name printer (field ...))
1683 (type #'type-name #'printer #'(field ...)))))))
1687 ;; A module is characterized by an obarray in which local symbols
1688 ;; are interned, a list of modules, "uses", from which non-local
1689 ;; bindings can be inherited, and an optional lazy-binder which
1690 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1691 ;; bindings that would otherwise not be found locally in the module.
1693 ;; NOTE: If you change the set of fields or their order, you also need to
1694 ;; change the constants in libguile/modules.h.
1696 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1697 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1698 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1699 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1701 (define-record-type module
1702 (lambda (obj port) (%print-module obj port))
1707 (transformer #:no-getter)
1711 (import-obarray #:no-setter)
1713 (weak-observers #:no-setter)
1721 ;; make-module &opt size uses binder
1723 ;; Create a new module, perhaps with a particular size of obarray,
1724 ;; initial uses list, or binding procedure.
1726 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
1727 (define %default-import-size
1728 ;; Typical number of imported bindings actually used by a module.
1731 (if (not (integer? size))
1732 (error "Illegal size to make-module." size))
1733 (if (not (and (list? uses)
1734 (and-map module? uses)))
1735 (error "Incorrect use list." uses))
1736 (if (and binder (not (procedure? binder)))
1738 "Lazy-binder expected to be a procedure or #f." binder))
1740 (let ((module (module-constructor (make-hash-table size)
1741 uses binder #f macroexpand
1743 (make-hash-table %default-import-size)
1745 (make-weak-key-hash-table 31) #f
1746 (make-hash-table 7) #f #f #f)))
1748 ;; We can't pass this as an argument to module-constructor,
1749 ;; because we need it to close over a pointer to the module
1751 (set-module-eval-closure! module (standard-eval-closure module))
1758 ;;; {Observer protocol}
1761 (define (module-observe module proc)
1762 (set-module-observers! module (cons proc (module-observers module)))
1765 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1766 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1767 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1768 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1769 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1772 ;; The two-argument version is kept for backward compatibility: when called
1773 ;; with two arguments, the observer gets unregistered when closure PROC
1774 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1775 (hashq-set! (module-weak-observers module) observer-id proc))
1777 (define (module-unobserve token)
1778 (let ((module (car token))
1781 (hash-remove! (module-weak-observers module) id)
1782 (set-module-observers! module (delq1! id (module-observers module)))))
1785 (define module-defer-observers #f)
1786 (define module-defer-observers-mutex (make-mutex 'recursive))
1787 (define module-defer-observers-table (make-hash-table))
1789 (define (module-modified m)
1790 (if module-defer-observers
1791 (hash-set! module-defer-observers-table m #t)
1792 (module-call-observers m)))
1794 ;;; This function can be used to delay calls to observers so that they
1795 ;;; can be called once only in the face of massive updating of modules.
1797 (define (call-with-deferred-observers thunk)
1800 (lock-mutex module-defer-observers-mutex)
1801 (set! module-defer-observers #t))
1804 (set! module-defer-observers #f)
1805 (hash-for-each (lambda (m dummy)
1806 (module-call-observers m))
1807 module-defer-observers-table)
1808 (hash-clear! module-defer-observers-table)
1809 (unlock-mutex module-defer-observers-mutex))))
1811 (define (module-call-observers m)
1812 (for-each (lambda (proc) (proc m)) (module-observers m))
1814 ;; We assume that weak observers don't (un)register themselves as they are
1815 ;; called since this would preclude proper iteration over the hash table
1817 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1821 ;;; {Module Searching in General}
1823 ;;; We sometimes want to look for properties of a symbol
1824 ;;; just within the obarray of one module. If the property
1825 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1826 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1829 ;;; Other times, we want to test for a symbol property in the obarray
1830 ;;; of M and, if it is not found there, try each of the modules in the
1831 ;;; uses list of M. This is the normal way of testing for some
1832 ;;; property, so we state these properties without qualification as
1833 ;;; in: ``The symbol 'fnord is interned in module M because it is
1834 ;;; interned locally in module M2 which is a member of the uses list
1838 ;; module-search fn m
1840 ;; return the first non-#f result of FN applied to M and then to
1841 ;; the modules in the uses of m, and so on recursively. If all applications
1842 ;; return #f, then so does this function.
1844 (define (module-search fn m v)
1847 (or (module-search fn (car pos) v)
1850 (loop (module-uses m))))
1853 ;;; {Is a symbol bound in a module?}
1855 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1856 ;;; of S in M has been set to some well-defined value.
1859 ;; module-locally-bound? module symbol
1861 ;; Is a symbol bound (interned and defined) locally in a given module?
1863 (define (module-locally-bound? m v)
1864 (let ((var (module-local-variable m v)))
1866 (variable-bound? var))))
1868 ;; module-bound? module symbol
1870 ;; Is a symbol bound (interned and defined) anywhere in a given module
1873 (define (module-bound? m v)
1874 (let ((var (module-variable m v)))
1876 (variable-bound? var))))
1878 ;;; {Is a symbol interned in a module?}
1880 ;;; Symbol S in Module M is interned if S occurs in
1881 ;;; of S in M has been set to some well-defined value.
1883 ;;; It is possible to intern a symbol in a module without providing
1884 ;;; an initial binding for the corresponding variable. This is done
1886 ;;; (module-add! module symbol (make-undefined-variable))
1888 ;;; In that case, the symbol is interned in the module, but not
1889 ;;; bound there. The unbound symbol shadows any binding for that
1890 ;;; symbol that might otherwise be inherited from a member of the uses list.
1893 (define (module-obarray-get-handle ob key)
1894 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1896 (define (module-obarray-ref ob key)
1897 ((if (symbol? key) hashq-ref hash-ref) ob key))
1899 (define (module-obarray-set! ob key val)
1900 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1902 (define (module-obarray-remove! ob key)
1903 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1905 ;; module-symbol-locally-interned? module symbol
1907 ;; is a symbol interned (not neccessarily defined) locally in a given module
1908 ;; or its uses? Interned symbols shadow inherited bindings even if
1909 ;; they are not themselves bound to a defined value.
1911 (define (module-symbol-locally-interned? m v)
1912 (not (not (module-obarray-get-handle (module-obarray m) v))))
1914 ;; module-symbol-interned? module symbol
1916 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1917 ;; or its uses? Interned symbols shadow inherited bindings even if
1918 ;; they are not themselves bound to a defined value.
1920 (define (module-symbol-interned? m v)
1921 (module-search module-symbol-locally-interned? m v))
1924 ;;; {Mapping modules x symbols --> variables}
1927 ;; module-local-variable module symbol
1928 ;; return the local variable associated with a MODULE and SYMBOL.
1930 ;;; This function is very important. It is the only function that can
1931 ;;; return a variable from a module other than the mutators that store
1932 ;;; new variables in modules. Therefore, this function is the location
1933 ;;; of the "lazy binder" hack.
1935 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1936 ;;; to a variable, return that variable object.
1938 ;;; If the symbols is not found at first, but the module has a lazy binder,
1939 ;;; then try the binder.
1941 ;;; If the symbol is not found at all, return #f.
1943 ;;; (This is now written in C, see `modules.c'.)
1946 ;;; {Mapping modules x symbols --> bindings}
1948 ;;; These are similar to the mapping to variables, except that the
1949 ;;; variable is dereferenced.
1952 ;; module-symbol-binding module symbol opt-value
1954 ;; return the binding of a variable specified by name within
1955 ;; a given module, signalling an error if the variable is unbound.
1956 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1957 ;; return OPT-VALUE.
1959 (define (module-symbol-local-binding m v . opt-val)
1960 (let ((var (module-local-variable m v)))
1961 (if (and var (variable-bound? var))
1963 (if (not (null? opt-val))
1965 (error "Locally unbound variable." v)))))
1967 ;; module-symbol-binding module symbol opt-value
1969 ;; return the binding of a variable specified by name within
1970 ;; a given module, signalling an error if the variable is unbound.
1971 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1972 ;; return OPT-VALUE.
1974 (define (module-symbol-binding m v . opt-val)
1975 (let ((var (module-variable m v)))
1976 (if (and var (variable-bound? var))
1978 (if (not (null? opt-val))
1980 (error "Unbound variable." v)))))
1985 ;;; {Adding Variables to Modules}
1988 ;; module-make-local-var! module symbol
1990 ;; ensure a variable for V in the local namespace of M.
1991 ;; If no variable was already there, then create a new and uninitialzied
1994 ;; This function is used in modules.c.
1996 (define (module-make-local-var! m v)
1997 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2000 ;; Mark as modified since this function is called when
2001 ;; the standard eval closure defines a binding
2005 ;; Create a new local variable.
2006 (let ((local-var (make-undefined-variable)))
2007 (module-add! m v local-var)
2010 ;; module-ensure-local-variable! module symbol
2012 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2013 ;; there is no binding for SYMBOL, create a new uninitialized
2014 ;; variable. Return the local variable.
2016 (define (module-ensure-local-variable! module symbol)
2017 (or (module-local-variable module symbol)
2018 (let ((var (make-undefined-variable)))
2019 (module-add! module symbol var)
2022 ;; module-add! module symbol var
2024 ;; ensure a particular variable for V in the local namespace of M.
2026 (define (module-add! m v var)
2027 (if (not (variable? var))
2028 (error "Bad variable to module-add!" var))
2029 (module-obarray-set! (module-obarray m) v var)
2030 (module-modified m))
2034 ;; make sure that a symbol is undefined in the local namespace of M.
2036 (define (module-remove! m v)
2037 (module-obarray-remove! (module-obarray m) v)
2038 (module-modified m))
2040 (define (module-clear! m)
2041 (hash-clear! (module-obarray m))
2042 (module-modified m))
2044 ;; MODULE-FOR-EACH -- exported
2046 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2048 (define (module-for-each proc module)
2049 (hash-for-each proc (module-obarray module)))
2051 (define (module-map proc module)
2052 (hash-map->list proc (module-obarray module)))
2056 ;; Modules exist in a separate namespace from values, because you generally do
2057 ;; not want the name of a submodule, which you might not even use, to collide
2058 ;; with local variables that happen to be named the same as the submodule.
2060 (define (module-ref-submodule module name)
2061 (or (hashq-ref (module-submodules module) name)
2062 (and (module-submodule-binder module)
2063 ((module-submodule-binder module) module name))))
2065 (define (module-define-submodule! module name submodule)
2066 (hashq-set! (module-submodules module) name submodule))
2070 ;;; {Module-based Loading}
2073 (define (save-module-excursion thunk)
2074 (let ((inner-module (current-module))
2076 (dynamic-wind (lambda ()
2077 (set! outer-module (current-module))
2078 (set-current-module inner-module)
2079 (set! inner-module #f))
2082 (set! inner-module (current-module))
2083 (set-current-module outer-module)
2084 (set! outer-module #f)))))
2088 ;;; {MODULE-REF -- exported}
2091 ;; Returns the value of a variable called NAME in MODULE or any of its
2092 ;; used modules. If there is no such variable, then if the optional third
2093 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2095 (define (module-ref module name . rest)
2096 (let ((variable (module-variable module name)))
2097 (if (and variable (variable-bound? variable))
2098 (variable-ref variable)
2100 (error "No variable named" name 'in module)
2101 (car rest) ; default value
2104 ;; MODULE-SET! -- exported
2106 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2107 ;; to VALUE; if there is no such variable, an error is signaled.
2109 (define (module-set! module name value)
2110 (let ((variable (module-variable module name)))
2112 (variable-set! variable value)
2113 (error "No variable named" name 'in module))))
2115 ;; MODULE-DEFINE! -- exported
2117 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2118 ;; variable, it is added first.
2120 (define (module-define! module name value)
2121 (let ((variable (module-local-variable module name)))
2124 (variable-set! variable value)
2125 (module-modified module))
2126 (let ((variable (make-variable value)))
2127 (module-add! module name variable)))))
2129 ;; MODULE-DEFINED? -- exported
2131 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2134 (define (module-defined? module name)
2135 (let ((variable (module-variable module name)))
2136 (and variable (variable-bound? variable))))
2138 ;; MODULE-USE! module interface
2140 ;; Add INTERFACE to the list of interfaces used by MODULE.
2142 (define (module-use! module interface)
2143 (if (not (or (eq? module interface)
2144 (memq interface (module-uses module))))
2146 ;; Newly used modules must be appended rather than consed, so that
2147 ;; `module-variable' traverses the use list starting from the first
2149 (set-module-uses! module (append (module-uses module)
2151 (hash-clear! (module-import-obarray module))
2152 (module-modified module))))
2154 ;; MODULE-USE-INTERFACES! module interfaces
2156 ;; Same as MODULE-USE!, but only notifies module observers after all
2157 ;; interfaces are added to the inports list.
2159 (define (module-use-interfaces! module interfaces)
2160 (let* ((cur (module-uses module))
2161 (new (let lp ((in interfaces) (out '()))
2165 (let ((iface (car in)))
2166 (if (or (memq iface cur) (memq iface out))
2168 (cons iface out))))))))
2169 (set-module-uses! module (append cur new))
2170 (hash-clear! (module-import-obarray module))
2171 (module-modified module)))
2175 ;;; {Recursive Namespaces}
2177 ;;; A hierarchical namespace emerges if we consider some module to be
2178 ;;; root, and submodules of that module to be nested namespaces.
2180 ;;; The routines here manage variable names in hierarchical namespace.
2181 ;;; Each variable name is a list of elements, looked up in successively nested
2184 ;;; (nested-ref some-root-module '(foo bar baz))
2185 ;;; => <value of a variable named baz in the submodule bar of
2186 ;;; the submodule foo of some-root-module>
2191 ;;; ;; a-root is a module
2192 ;;; ;; name is a list of symbols
2194 ;;; nested-ref a-root name
2195 ;;; nested-set! a-root name val
2196 ;;; nested-define! a-root name val
2197 ;;; nested-remove! a-root name
2199 ;;; These functions manipulate values in namespaces. For referencing the
2200 ;;; namespaces themselves, use the following:
2202 ;;; nested-ref-module a-root name
2203 ;;; nested-define-module! a-root name mod
2205 ;;; (current-module) is a natural choice for a root so for convenience there are
2208 ;;; local-ref name == nested-ref (current-module) name
2209 ;;; local-set! name val == nested-set! (current-module) name val
2210 ;;; local-define name val == nested-define! (current-module) name val
2211 ;;; local-remove name == nested-remove! (current-module) name
2212 ;;; local-ref-module name == nested-ref-module (current-module) name
2213 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2217 (define (nested-ref root names)
2220 (let loop ((cur root)
2224 (module-ref cur head #f)
2225 (let ((cur (module-ref-submodule cur head)))
2227 (loop cur (car tail) (cdr tail))))))))
2229 (define (nested-set! root names val)
2230 (let loop ((cur root)
2234 (module-set! cur head val)
2235 (let ((cur (module-ref-submodule cur head)))
2237 (error "failed to resolve module" names)
2238 (loop cur (car tail) (cdr tail)))))))
2240 (define (nested-define! root names val)
2241 (let loop ((cur root)
2245 (module-define! cur head val)
2246 (let ((cur (module-ref-submodule cur head)))
2248 (error "failed to resolve module" names)
2249 (loop cur (car tail) (cdr tail)))))))
2251 (define (nested-remove! root names)
2252 (let loop ((cur root)
2256 (module-remove! cur head)
2257 (let ((cur (module-ref-submodule cur head)))
2259 (error "failed to resolve module" names)
2260 (loop cur (car tail) (cdr tail)))))))
2263 (define (nested-ref-module root names)
2264 (let loop ((cur root)
2268 (let ((cur (module-ref-submodule cur (car names))))
2270 (loop cur (cdr names)))))))
2272 (define (nested-define-module! root names module)
2274 (error "can't redefine root module" root module)
2275 (let loop ((cur root)
2279 (module-define-submodule! cur head module)
2280 (let ((cur (or (module-ref-submodule cur head)
2281 (let ((m (make-module 31)))
2282 (set-module-kind! m 'directory)
2283 (set-module-name! m (append (module-name cur)
2285 (module-define-submodule! cur head m)
2287 (loop cur (car tail) (cdr tail)))))))
2290 (define (local-ref names)
2291 (nested-ref (current-module) names))
2293 (define (local-set! names val)
2294 (nested-set! (current-module) names val))
2296 (define (local-define names val)
2297 (nested-define! (current-module) names val))
2299 (define (local-remove names)
2300 (nested-remove! (current-module) names))
2302 (define (local-ref-module names)
2303 (nested-ref-module (current-module) names))
2305 (define (local-define-module names mod)
2306 (nested-define-module! (current-module) names mod))
2312 ;;; {The (guile) module}
2314 ;;; The standard module, which has the core Guile bindings. Also called the
2315 ;;; "root module", as it is imported by many other modules, but it is not
2316 ;;; necessarily the root of anything; and indeed, the module named '() might be
2317 ;;; better thought of as a root.
2320 (define (set-system-module! m s)
2321 (set-procedure-property! (module-eval-closure m) 'system-module s))
2323 ;; The root module uses the pre-modules-obarray as its obarray. This
2324 ;; special obarray accumulates all bindings that have been established
2325 ;; before the module system is fully booted.
2327 ;; (The obarray continues to be used by code that has been closed over
2328 ;; before the module system has been booted.)
2330 (define the-root-module
2331 (let ((m (make-module 0)))
2332 (set-module-obarray! m (%get-pre-modules-obarray))
2333 (set-module-name! m '(guile))
2334 (set-system-module! m #t)
2337 ;; The root interface is a module that uses the same obarray as the
2338 ;; root module. It does not allow new definitions, tho.
2340 (define the-scm-module
2341 (let ((m (make-module 0)))
2342 (set-module-obarray! m (%get-pre-modules-obarray))
2343 (set-module-eval-closure! m (standard-interface-eval-closure m))
2344 (set-module-name! m '(guile))
2345 (set-module-kind! m 'interface)
2346 (set-system-module! m #t)
2348 ;; In Guile 1.8 and earlier M was its own public interface.
2349 (set-module-public-interface! m m)
2353 (set-module-public-interface! the-root-module the-scm-module)
2357 ;; Now that we have a root module, even though modules aren't fully booted,
2358 ;; expand the definition of resolve-module.
2360 (define (resolve-module name . args)
2361 (if (equal? name '(guile))
2363 (error "unexpected module to resolve during module boot" name)))
2365 ;; Cheat. These bindings are needed by modules.c, but we don't want
2366 ;; to move their real definition here because that would be unnatural.
2368 (define define-module* #f)
2369 (define process-use-modules #f)
2370 (define module-export! #f)
2371 (define default-duplicate-binding-procedures #f)
2373 ;; This boots the module system. All bindings needed by modules.c
2374 ;; must have been defined by now.
2376 (set-current-module the-root-module)
2381 ;; Now that modules are booted, give module-name its final definition.
2384 (let ((accessor (record-accessor module-type 'name)))
2387 (let ((name (list (gensym))))
2388 ;; Name MOD and bind it in the module root so that it's visible to
2389 ;; `resolve-module'. This is important as `psyntax' stores module
2390 ;; names and relies on being able to `resolve-module' them.
2391 (set-module-name! mod name)
2392 (nested-define-module! (resolve-module '() #f) name mod)
2395 (define (make-modules-in module name)
2396 (or (nested-ref-module module name)
2397 (let ((m (make-module 31)))
2398 (set-module-kind! m 'directory)
2399 (set-module-name! m (append (module-name module) name))
2400 (nested-define-module! module name m)
2403 (define (beautify-user-module! module)
2404 (let ((interface (module-public-interface module)))
2405 (if (or (not interface)
2406 (eq? interface module))
2407 (let ((interface (make-module 31)))
2408 (set-module-name! interface (module-name module))
2409 (set-module-version! interface (module-version module))
2410 (set-module-kind! interface 'interface)
2411 (set-module-public-interface! module interface))))
2412 (if (and (not (memq the-scm-module (module-uses module)))
2413 (not (eq? module the-root-module)))
2414 ;; Import the default set of bindings (from the SCM module) in MODULE.
2415 (module-use! module the-scm-module)))
2417 (define (version-matches? version-ref target)
2418 (define (sub-versions-match? v-refs t)
2419 (define (sub-version-matches? v-ref t)
2420 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2422 ((number? v-ref) (eqv? v-ref t))
2425 ((>=) (>= t (cadr v-ref)))
2426 ((<=) (<= t (cadr v-ref)))
2427 ((and) (and-map matches? (cdr v-ref)))
2428 ((or) (or-map matches? (cdr v-ref)))
2429 ((not) (not (matches? (cadr v-ref))))
2430 (else (error "Invalid sub-version reference" v-ref))))
2431 (else (error "Invalid sub-version reference" v-ref)))))
2433 (and (not (null? t))
2434 (sub-version-matches? (car v-refs) (car t))
2435 (sub-versions-match? (cdr v-refs) (cdr t)))))
2437 (let ((matches? (lambda (v) (version-matches? v target))))
2438 (or (null? version-ref)
2439 (case (car version-ref)
2440 ((and) (and-map matches? (cdr version-ref)))
2441 ((or) (or-map matches? (cdr version-ref)))
2442 ((not) (not (matches? (cadr version-ref))))
2443 (else (sub-versions-match? version-ref target))))))
2445 (define (make-fresh-user-module)
2446 (let ((m (make-module)))
2447 (beautify-user-module! m)
2450 ;; NOTE: This binding is used in libguile/modules.c.
2452 (define resolve-module
2453 (let ((root (make-module)))
2454 (set-module-name! root '())
2455 ;; Define the-root-module as '(guile).
2456 (module-define-submodule! root 'guile the-root-module)
2458 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2459 (let ((already (nested-ref-module root name)))
2462 (or (not autoload) (module-public-interface already)))
2463 ;; A hit, a palpable hit.
2465 (not (version-matches? version (module-version already))))
2466 (error "incompatible module version already loaded" name))
2469 ;; Try to autoload the module, and recurse.
2470 (try-load-module name version)
2471 (resolve-module name #f #:ensure ensure))
2473 ;; No module found (or if one was, it had no public interface), and
2474 ;; we're not autoloading. Make an empty module if #:ensure is true.
2477 (make-modules-in root name)))))))))
2480 (define (try-load-module name version)
2481 (try-module-autoload name version))
2483 (define (reload-module m)
2484 "Revisit the source file corresponding to the module @var{m}."
2485 (let ((f (module-filename m)))
2487 (save-module-excursion
2489 ;; Re-set the initial environment, as in try-module-autoload.
2490 (set-current-module (make-fresh-user-module))
2491 (primitive-load-path f)
2493 ;; Though we could guess, we *should* know it.
2494 (error "unknown file name for module" m))))
2496 (define (purify-module! module)
2497 "Removes bindings in MODULE which are inherited from the (guile) module."
2498 (let ((use-list (module-uses module)))
2499 (if (and (pair? use-list)
2500 (eq? (car (last-pair use-list)) the-scm-module))
2501 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2503 ;; Return a module that is an interface to the module designated by
2506 ;; `resolve-interface' takes four keyword arguments:
2508 ;; #:select SELECTION
2510 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2511 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2512 ;; is the name in the used module and SEEN is the name in the using
2513 ;; module. Note that SEEN is also passed through RENAMER, below. The
2514 ;; default is to select all bindings. If you specify no selection but
2515 ;; a renamer, only the bindings that already exist in the used module
2516 ;; are made available in the interface. Bindings that are added later
2517 ;; are not picked up.
2521 ;; BINDINGS is a list of bindings which should not be imported.
2525 ;; PREFIX is a symbol that will be appended to each exported name.
2526 ;; The default is to not perform any renaming.
2528 ;; #:renamer RENAMER
2530 ;; RENAMER is a procedure that takes a symbol and returns its new
2531 ;; name. The default is not perform any renaming.
2533 ;; Signal "no code for module" error if module name is not resolvable
2534 ;; or its public interface is not available. Signal "no binding"
2535 ;; error if selected binding does not exist in the used module.
2537 (define* (resolve-interface name #:key
2542 (symbol-prefix-proc prefix)
2545 (let* ((module (resolve-module name #t version #:ensure #f))
2546 (public-i (and module (module-public-interface module))))
2547 (and (or (not module) (not public-i))
2548 (error "no code for module" name))
2549 (if (and (not select) (null? hide) (eq? renamer identity))
2551 (let ((selection (or select (module-map (lambda (sym var) sym)
2553 (custom-i (make-module 31)))
2554 (set-module-kind! custom-i 'custom-interface)
2555 (set-module-name! custom-i name)
2556 ;; XXX - should use a lazy binder so that changes to the
2557 ;; used module are picked up automatically.
2558 (for-each (lambda (bspec)
2559 (let* ((direct? (symbol? bspec))
2560 (orig (if direct? bspec (car bspec)))
2561 (seen (if direct? bspec (cdr bspec)))
2562 (var (or (module-local-variable public-i orig)
2563 (module-local-variable module orig)
2565 ;; fixme: format manually for now
2567 #f "no binding `~A' in module ~A"
2569 (if (memq orig hide)
2570 (set! hide (delq! orig hide))
2571 (module-add! custom-i
2575 ;; Check that we are not hiding bindings which don't exist
2576 (for-each (lambda (binding)
2577 (if (not (module-local-variable public-i binding))
2580 #f "no binding `~A' to hide in module ~A"
2585 (define (symbol-prefix-proc prefix)
2587 (symbol-append prefix symbol)))
2589 ;; This function is called from "modules.c". If you change it, be
2590 ;; sure to update "modules.c" as well.
2592 (define* (define-module* name
2593 #:key filename pure version (duplicates '())
2594 (imports '()) (exports '()) (replacements '())
2595 (re-exports '()) (autoloads '()) transformer)
2596 (define (list-of pred l)
2598 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2599 (define (valid-export? x)
2600 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2601 (define (valid-autoload? x)
2602 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
2604 (define (resolve-imports imports)
2605 (define (resolve-import import-spec)
2606 (if (list? import-spec)
2607 (apply resolve-interface import-spec)
2608 (error "unexpected use-module specification" import-spec)))
2609 (let lp ((imports imports) (out '()))
2611 ((null? imports) (reverse! out))
2614 (cons (resolve-import (car imports)) out)))
2615 (else (error "unexpected tail of imports list" imports)))))
2617 ;; We could add a #:no-check arg, set by the define-module macro, if
2618 ;; these checks are taking too much time.
2620 (let ((module (resolve-module name #f)))
2621 (beautify-user-module! module)
2623 (set-module-filename! module filename))
2625 (purify-module! module))
2628 (if (not (list-of integer? version))
2629 (error "expected list of integers for version"))
2630 (set-module-version! module version)
2631 (set-module-version! (module-public-interface module) version)))
2632 (let ((imports (resolve-imports imports)))
2633 (call-with-deferred-observers
2636 (module-use-interfaces! module imports))
2637 (if (list-of valid-export? exports)
2639 (module-export! module exports))
2640 (error "expected exports to be a list of symbols or symbol pairs"))
2641 (if (list-of valid-export? replacements)
2642 (if (pair? replacements)
2643 (module-replace! module replacements))
2644 (error "expected replacements to be a list of symbols or symbol pairs"))
2645 (if (list-of valid-export? re-exports)
2646 (if (pair? re-exports)
2647 (module-re-export! module re-exports))
2648 (error "expected re-exports to be a list of symbols or symbol pairs"))
2650 (if (not (null? autoloads))
2651 (apply module-autoload! module autoloads))
2652 ;; Wait until modules have been loaded to resolve duplicates
2654 (if (pair? duplicates)
2655 (let ((handlers (lookup-duplicates-handlers duplicates)))
2656 (set-module-duplicates-handlers! module handlers))))))
2659 (if (and (pair? transformer) (list-of symbol? transformer))
2660 (let ((iface (resolve-interface transformer))
2661 (sym (car (last-pair transformer))))
2662 (set-module-transformer! module (module-ref iface sym)))
2663 (error "expected transformer to be a module name" transformer)))
2665 (run-hook module-defined-hook module)
2668 ;; `module-defined-hook' is a hook that is run whenever a new module
2669 ;; is defined. Its members are called with one argument, the new
2671 (define module-defined-hook (make-hook 1))
2678 (define (make-autoload-interface module name bindings)
2679 (let ((b (lambda (a sym definep)
2680 (and (memq sym bindings)
2681 (let ((i (module-public-interface (resolve-module name))))
2683 (error "missing interface for module" name))
2684 (let ((autoload (memq a (module-uses module))))
2685 ;; Replace autoload-interface with actual interface if
2686 ;; that has not happened yet.
2687 (if (pair? autoload)
2688 (set-car! autoload i)))
2689 (module-local-variable i sym))))))
2690 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2691 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2692 (make-hash-table 0) #f #f #f)))
2694 (define (module-autoload! module . args)
2695 "Have @var{module} automatically load the module named @var{name} when one
2696 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2697 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2698 module '(ice-9 q) '(make-q q-length))}."
2699 (let loop ((args args))
2703 (error "invalid name+binding autoload list" args))
2705 (let ((name (car args))
2706 (bindings (cadr args)))
2707 (module-use! module (make-autoload-interface module
2709 (loop (cddr args)))))))
2714 ;;; {Autoloading modules}
2717 (define autoloads-in-progress '())
2719 ;; This function is called from "modules.c". If you change it, be
2720 ;; sure to update "modules.c" as well.
2722 (define* (try-module-autoload module-name #:optional version)
2723 (let* ((reverse-name (reverse module-name))
2724 (name (symbol->string (car reverse-name)))
2725 (dir-hint-module-name (reverse (cdr reverse-name)))
2726 (dir-hint (apply string-append
2728 (string-append (symbol->string elt) "/"))
2729 dir-hint-module-name))))
2730 (resolve-module dir-hint-module-name #f)
2731 (and (not (autoload-done-or-in-progress? dir-hint name))
2734 (lambda () (autoload-in-progress! dir-hint name))
2736 (with-fluids ((current-reader #f))
2737 (save-module-excursion
2739 ;; The initial environment when loading a module is a fresh
2741 (set-current-module (make-fresh-user-module))
2742 ;; Here we could allow some other search strategy (other than
2743 ;; primitive-load-path), for example using versions encoded
2744 ;; into the file system -- but then we would have to figure
2745 ;; out how to locate the compiled file, do auto-compilation,
2746 ;; etc. Punt for now, and don't use versions when locating
2748 (primitive-load-path (in-vicinity dir-hint name) #f)
2750 (lambda () (set-autoloaded! dir-hint name didit)))
2755 ;;; {Dynamic linking of modules}
2758 (define autoloads-done '((guile . guile)))
2760 (define (autoload-done-or-in-progress? p m)
2761 (let ((n (cons p m)))
2762 (->bool (or (member n autoloads-done)
2763 (member n autoloads-in-progress)))))
2765 (define (autoload-done! p m)
2766 (let ((n (cons p m)))
2767 (set! autoloads-in-progress
2768 (delete! n autoloads-in-progress))
2769 (or (member n autoloads-done)
2770 (set! autoloads-done (cons n autoloads-done)))))
2772 (define (autoload-in-progress! p m)
2773 (let ((n (cons p m)))
2774 (set! autoloads-done
2775 (delete! n autoloads-done))
2776 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2778 (define (set-autoloaded! p m done?)
2780 (autoload-done! p m)
2781 (let ((n (cons p m)))
2782 (set! autoloads-done (delete! n autoloads-done))
2783 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2787 ;;; {Run-time options}
2790 (define-syntax define-option-interface
2792 ((_ (interface (options enable disable) (option-set!)))
2799 (begin (interface arg) (interface))
2802 (apply (lambda (name value documentation)
2804 (if (< (string-length (symbol->string name)) 8)
2809 (display documentation)
2813 (define (enable . flags)
2814 (interface (append flags (interface)))
2816 (define (disable . flags)
2817 (let ((options (interface)))
2818 (for-each (lambda (flag) (set! options (delq! flag options)))
2822 (define-syntax option-set!
2825 (eval-when (eval load compile expand)
2826 (options (append (options) (list 'opt val)))))))))))
2828 (define-option-interface
2829 (debug-options-interface
2830 (debug-options debug-enable debug-disable)
2833 (define-option-interface
2834 (read-options-interface
2835 (read-options read-enable read-disable)
2838 (define-option-interface
2839 (print-options-interface
2840 (print-options print-enable print-disable)
2845 ;;; {The Unspecified Value}
2847 ;;; Currently Guile represents unspecified values via one particular value,
2848 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2849 ;;; future if we could replace this with a return of 0 values, though.
2852 (define-syntax *unspecified*
2853 (identifier-syntax (if #f #f)))
2855 (define (unspecified? v) (eq? v *unspecified*))
2863 (define *repl-stack* (make-fluid))
2865 ;; Programs can call `batch-mode?' to see if they are running as part of a
2866 ;; script or if they are running interactively. REPL implementations ensure that
2867 ;; `batch-mode?' returns #f during their extent.
2869 (define (batch-mode?)
2870 (null? (or (fluid-ref *repl-stack*) '())))
2872 ;; Programs can re-enter batch mode, for example after a fork, by calling
2873 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
2874 ;; to abort to the outermost prompt, and call a thunk there.
2876 (define (ensure-batch-mode!)
2877 (set! batch-mode? (lambda () #t)))
2879 (define (quit . args)
2880 (apply throw 'quit args))
2884 (define (gc-run-time)
2885 (cdr (assq 'gc-time-taken (gc-stats))))
2887 (define abort-hook (make-hook))
2888 (define before-error-hook (make-hook))
2889 (define after-error-hook (make-hook))
2890 (define before-backtrace-hook (make-hook))
2891 (define after-backtrace-hook (make-hook))
2893 (define before-read-hook (make-hook))
2894 (define after-read-hook (make-hook))
2895 (define before-eval-hook (make-hook 1))
2896 (define after-eval-hook (make-hook 1))
2897 (define before-print-hook (make-hook 1))
2898 (define after-print-hook (make-hook 1))
2900 ;;; This hook is run at the very end of an interactive session.
2902 (define exit-hook (make-hook))
2904 ;;; The default repl-reader function. We may override this if we've
2905 ;;; the readline library.
2907 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
2908 (if (not (char-ready?))
2909 (display (if (string? prompt) prompt (prompt))))
2911 (run-hook before-read-hook)
2912 ((or reader read) (current-input-port))))
2917 ;;; {IOTA functions: generating lists of numbers}
2921 (let loop ((count (1- n)) (result '()))
2922 (if (< count 0) result
2923 (loop (1- count) (cons count result)))))
2929 ;;; with `continue' and `break'.
2932 ;; The inliner will remove the prompts at compile-time if it finds that
2933 ;; `continue' or `break' are not used.
2935 (define-syntax while
2938 ((while cond body ...)
2939 #`(let ((break-tag (make-prompt-tag "break"))
2940 (continue-tag (make-prompt-tag "continue")))
2944 (define-syntax #,(datum->syntax #'while 'break)
2948 #'(abort-to-prompt break-tag arg (... ...)))
2951 (apply abort-to-prompt break-tag args))))))
2956 (define-syntax #,(datum->syntax #'while 'continue)
2960 #'(abort-to-prompt continue-tag))
2962 (syntax-violation 'continue "too many arguments" x))
2965 (abort-to-prompt continue-tag))))))
2966 (do () ((not cond) #f) body ...))
2967 (lambda (k) (lp)))))
2971 (apply values args)))))))))
2976 ;;; {Module System Macros}
2979 ;; Return a list of expressions that evaluate to the appropriate
2980 ;; arguments for resolve-interface according to SPEC.
2982 (eval-when (compile)
2983 (if (memq 'prefix (read-options))
2984 (error "boot-9 must be compiled with #:kw, not :kw")))
2986 (define (keyword-like-symbol->keyword sym)
2987 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2989 (define-syntax define-module
2991 (define (keyword-like? stx)
2992 (let ((dat (syntax->datum stx)))
2994 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2995 (define (->keyword sym)
2996 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2998 (define (parse-iface args)
2999 (let loop ((in args) (out '()))
3002 ;; The user wanted #:foo, but wrote :foo. Fix it.
3003 ((sym . in) (keyword-like? #'sym)
3004 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3005 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3006 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3007 ((#:renamer renamer . in)
3008 (loop #'in (cons* #',renamer #:renamer out)))
3010 (loop #'in (cons* #'val #'kw out))))))
3012 (define (parse args imp exp rex rep aut)
3013 ;; Just quote everything except #:use-module and #:use-syntax. We
3014 ;; need to know about all arguments regardless since we want to turn
3015 ;; symbols that look like keywords into real keywords, and the
3016 ;; keyword args in a define-module form are not regular
3017 ;; (i.e. no-backtrace doesn't take a value).
3018 (syntax-case args ()
3020 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3021 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3022 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3023 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3024 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3025 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3026 ;; The user wanted #:foo, but wrote :foo. Fix it.
3027 ((sym . args) (keyword-like? #'sym)
3028 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3029 imp exp rex rep aut))
3030 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3031 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3032 ((#:no-backtrace . args)
3034 (parse #'args imp exp rex rep aut))
3036 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3038 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3039 ((#:version (v ...) . args)
3040 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3041 ((#:duplicates (d ...) . args)
3042 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3043 ((#:filename f . args)
3044 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3045 ((#:use-module (name name* ...) . args)
3046 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3047 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3048 ((#:use-syntax (name name* ...) . args)
3049 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3050 #`(#:transformer '(name name* ...)
3051 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3052 ((#:use-module ((name name* ...) arg ...) . args)
3053 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3055 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3057 ((#:export (ex ...) . args)
3058 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3059 ((#:export-syntax (ex ...) . args)
3060 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3061 ((#:re-export (re ...) . args)
3062 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3063 ((#:re-export-syntax (re ...) . args)
3064 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3065 ((#:replace (r ...) . args)
3066 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3067 ((#:replace-syntax (r ...) . args)
3068 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3069 ((#:autoload name bindings . args)
3070 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3072 (syntax-violation 'define-module "unknown keyword or bad argument"
3076 ((_ (name name* ...) arg ...)
3077 (and-map symbol? (syntax->datum #'(name name* ...)))
3078 (with-syntax (((quoted-arg ...)
3079 (parse #'(arg ...) '() '() '() '() '()))
3080 ;; Ideally the filename is either a string or #f;
3081 ;; this hack is to work around a case in which
3082 ;; port-filename returns a symbol (`socket') for
3084 (filename (let ((f (assq-ref (or (syntax-source x) '())
3086 (and (string? f) f))))
3087 #'(eval-when (eval load compile expand)
3088 (let ((m (define-module* '(name name* ...)
3089 #:filename filename quoted-arg ...)))
3090 (set-current-module m)
3093 ;; The guts of the use-modules macro. Add the interfaces of the named
3094 ;; modules to the use-list of the current module, in order.
3096 ;; This function is called by "modules.c". If you change it, be sure
3097 ;; to change scm_c_use_module as well.
3099 (define (process-use-modules module-interface-args)
3100 (let ((interfaces (map (lambda (mif-args)
3101 (or (apply resolve-interface mif-args)
3102 (error "no such module" mif-args)))
3103 module-interface-args)))
3104 (call-with-deferred-observers
3106 (module-use-interfaces! (current-module) interfaces)))))
3108 (define-syntax use-modules
3110 (define (keyword-like? stx)
3111 (let ((dat (syntax->datum stx)))
3113 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3114 (define (->keyword sym)
3115 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3117 (define (quotify-iface args)
3118 (let loop ((in args) (out '()))
3121 ;; The user wanted #:foo, but wrote :foo. Fix it.
3122 ((sym . in) (keyword-like? #'sym)
3123 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3124 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3125 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3126 ((#:renamer renamer . in)
3127 (loop #'in (cons* #'renamer #:renamer out)))
3129 (loop #'in (cons* #''val #'kw out))))))
3131 (define (quotify specs)
3132 (let lp ((in specs) (out '()))
3135 (((name name* ...) . in)
3136 (and-map symbol? (syntax->datum #'(name name* ...)))
3137 (lp #'in (cons #''((name name* ...)) out)))
3138 ((((name name* ...) arg ...) . in)
3139 (and-map symbol? (syntax->datum #'(name name* ...)))
3140 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3141 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3146 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3147 #'(eval-when (eval load compile expand)
3148 (process-use-modules (list quoted-args ...))
3151 (include-from-path "ice-9/r6rs-libraries")
3153 (define-syntax define-private
3158 (define-syntax define-public
3160 ((_ (name . args) . body)
3161 (define-public name (lambda args . body)))
3167 (define-syntax defmacro-public
3169 ((_ name args . body)
3171 (defmacro name args . body)
3172 (export-syntax name)))))
3174 ;; And now for the most important macro.
3177 ((_ formals body ...)
3178 (lambda formals body ...))))
3181 ;; Export a local variable
3183 ;; This function is called from "modules.c". If you change it, be
3184 ;; sure to update "modules.c" as well.
3186 (define (module-export! m names)
3187 (let ((public-i (module-public-interface m)))
3188 (for-each (lambda (name)
3189 (let* ((internal-name (if (pair? name) (car name) name))
3190 (external-name (if (pair? name) (cdr name) name))
3191 (var (module-ensure-local-variable! m internal-name)))
3192 (module-add! public-i external-name var)))
3195 (define (module-replace! m names)
3196 (let ((public-i (module-public-interface m)))
3197 (for-each (lambda (name)
3198 (let* ((internal-name (if (pair? name) (car name) name))
3199 (external-name (if (pair? name) (cdr name) name))
3200 (var (module-ensure-local-variable! m internal-name)))
3201 ;; FIXME: use a bit on variables instead of object
3203 (set-object-property! var 'replace #t)
3204 (module-add! public-i external-name var)))
3207 ;; Export all local variables from a module
3209 (define (module-export-all! mod)
3210 (define (fresh-interface!)
3211 (let ((iface (make-module)))
3212 (set-module-name! iface (module-name mod))
3213 (set-module-version! iface (module-version mod))
3214 (set-module-kind! iface 'interface)
3215 (set-module-public-interface! mod iface)
3217 (let ((iface (or (module-public-interface mod)
3218 (fresh-interface!))))
3219 (set-module-obarray! iface (module-obarray mod))))
3221 ;; Re-export a imported variable
3223 (define (module-re-export! m names)
3224 (let ((public-i (module-public-interface m)))
3225 (for-each (lambda (name)
3226 (let* ((internal-name (if (pair? name) (car name) name))
3227 (external-name (if (pair? name) (cdr name) name))
3228 (var (module-variable m internal-name)))
3230 (error "Undefined variable:" internal-name))
3231 ((eq? var (module-local-variable m internal-name))
3232 (error "re-exporting local variable:" internal-name))
3234 (module-add! public-i external-name var)))))
3237 (define-syntax export
3240 (eval-when (eval load compile expand)
3241 (call-with-deferred-observers
3243 (module-export! (current-module) '(name ...))))))))
3245 (define-syntax re-export
3248 (eval-when (eval load compile expand)
3249 (call-with-deferred-observers
3251 (module-re-export! (current-module) '(name ...))))))))
3253 (define-syntax export!
3256 (eval-when (eval load compile expand)
3257 (call-with-deferred-observers
3259 (module-replace! (current-module) '(name ...))))))))
3261 (define-syntax export-syntax
3264 (export name ...))))
3266 (define-syntax re-export-syntax
3269 (re-export name ...))))
3276 (define* (make-mutable-parameter init #:optional (converter identity))
3277 (let ((fluid (make-fluid)))
3278 (fluid-set! fluid (converter init))
3280 (() (fluid-ref fluid))
3281 ((val) (fluid-set! fluid (converter val))))))
3286 ;;; {Handling of duplicate imported bindings}
3289 ;; Duplicate handlers take the following arguments:
3291 ;; module importing module
3292 ;; name conflicting name
3293 ;; int1 old interface where name occurs
3294 ;; val1 value of binding in old interface
3295 ;; int2 new interface where name occurs
3296 ;; val2 value of binding in new interface
3297 ;; var previous resolution or #f
3298 ;; val value of previous resolution
3300 ;; A duplicate handler can take three alternative actions:
3302 ;; 1. return #f => leave responsibility to next handler
3303 ;; 2. exit with an error
3304 ;; 3. return a variable resolving the conflict
3307 (define duplicate-handlers
3308 (let ((m (make-module 7)))
3310 (define (check module name int1 val1 int2 val2 var val)
3311 (scm-error 'misc-error
3313 "~A: `~A' imported from both ~A and ~A"
3314 (list (module-name module)
3320 (define (warn module name int1 val1 int2 val2 var val)
3321 (format (current-error-port)
3322 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3323 (module-name module)
3329 (define (replace module name int1 val1 int2 val2 var val)
3330 (let ((old (or (and var (object-property var 'replace) var)
3331 (module-variable int1 name)))
3332 (new (module-variable int2 name)))
3333 (if (object-property old 'replace)
3334 (and (or (eq? old new)
3335 (not (object-property new 'replace)))
3337 (and (object-property new 'replace)
3340 (define (warn-override-core module name int1 val1 int2 val2 var val)
3341 (and (eq? int1 the-scm-module)
3343 (format (current-error-port)
3344 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3345 (module-name module)
3348 (module-local-variable int2 name))))
3350 (define (first module name int1 val1 int2 val2 var val)
3351 (or var (module-local-variable int1 name)))
3353 (define (last module name int1 val1 int2 val2 var val)
3354 (module-local-variable int2 name))
3356 (define (noop module name int1 val1 int2 val2 var val)
3359 (set-module-name! m 'duplicate-handlers)
3360 (set-module-kind! m 'interface)
3361 (module-define! m 'check check)
3362 (module-define! m 'warn warn)
3363 (module-define! m 'replace replace)
3364 (module-define! m 'warn-override-core warn-override-core)
3365 (module-define! m 'first first)
3366 (module-define! m 'last last)
3367 (module-define! m 'merge-generics noop)
3368 (module-define! m 'merge-accessors noop)
3371 (define (lookup-duplicates-handlers handler-names)
3373 (map (lambda (handler-name)
3374 (or (module-symbol-local-binding
3375 duplicate-handlers handler-name #f)
3376 (error "invalid duplicate handler name:"
3378 (if (list? handler-names)
3380 (list handler-names)))))
3382 (define default-duplicate-binding-procedures
3383 (make-mutable-parameter #f))
3385 (define default-duplicate-binding-handler
3386 (make-mutable-parameter '(replace warn-override-core warn last)
3387 (lambda (handler-names)
3388 (default-duplicate-binding-procedures
3389 (lookup-duplicates-handlers handler-names))
3396 ;;; Load is tricky when combined with relative paths, compilation, and
3397 ;;; the filesystem. If a path is relative, what is it relative to? The
3398 ;;; path of the source file at the time it was compiled? The path of
3399 ;;; the compiled file? What if both or either were installed? And how
3400 ;;; do you get that information? Tricky, I say.
3402 ;;; To get around all of this, we're going to do something nasty, and
3403 ;;; turn `load' into a macro. That way it can know the path of the
3404 ;;; source file with respect to which it was invoked, so it can resolve
3405 ;;; relative paths with respect to the original source path.
3407 ;;; There is an exception, and that is that if the source file was in
3408 ;;; the load path when it was compiled, instead of looking up against
3409 ;;; the absolute source location, we load-from-path against the relative
3410 ;;; source location.
3413 (define %auto-compilation-options
3414 ;; Default `compile-file' option when auto-compiling.
3415 '(#:warnings (unbound-variable arity-mismatch format)))
3417 (define* (load-in-vicinity dir path #:optional reader)
3418 (define (canonical->suffix canon)
3420 ((string-prefix? "/" canon) canon)
3421 ((and (> (string-length canon) 2)
3422 (eqv? (string-ref canon 1) #\:))
3423 ;; Paths like C:... transform to /C...
3424 (string-append "/" (substring canon 0 1) (substring canon 2)))
3427 ;; Returns the .go file corresponding to `name'. Does not search load
3428 ;; paths, only the fallback path. If the .go file is missing or out of
3429 ;; date, and auto-compilation is enabled, will try auto-compilation, just
3430 ;; as primitive-load-path does internally. primitive-load is
3431 ;; unaffected. Returns #f if auto-compilation failed or was disabled.
3433 ;; NB: Unless we need to compile the file, this function should not cause
3434 ;; (system base compile) to be loaded up. For that reason compiled-file-name
3435 ;; partially duplicates functionality from (system base compile).
3437 (define (compiled-file-name canon-path)
3438 ;; FIXME: would probably be better just to append SHA1(canon-path)
3439 ;; to the %compile-fallback-path, to avoid deep directory stats.
3440 (and %compile-fallback-path
3442 %compile-fallback-path
3443 (canonical->suffix canon-path)
3444 (cond ((or (null? %load-compiled-extensions)
3445 (string-null? (car %load-compiled-extensions)))
3446 (warn "invalid %load-compiled-extensions"
3447 %load-compiled-extensions)
3449 (else (car %load-compiled-extensions))))))
3451 (define (fresh-compiled-file-name name go-path)
3454 (let* ((scmstat (stat name))
3455 (gostat (and (not %fresh-auto-compile)
3456 (stat go-path #f))))
3458 (or (> (stat:mtime gostat) (stat:mtime scmstat))
3459 (and (= (stat:mtime gostat) (stat:mtime scmstat))
3460 (>= (stat:mtimensec gostat)
3461 (stat:mtimensec scmstat)))))
3465 (format (current-error-port)
3466 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
3469 (%load-should-auto-compile
3470 (%warn-auto-compilation-enabled)
3471 (format (current-error-port) ";;; compiling ~a\n" name)
3474 (resolve-interface '(system base compile))
3477 #:opts %auto-compilation-options
3478 #:env (current-module))))
3479 (format (current-error-port) ";;; compiled ~a\n" cfn)
3483 (format (current-error-port)
3484 ";;; WARNING: compilation of ~a failed:\n" name)
3485 (for-each (lambda (s)
3486 (if (not (string-null? s))
3487 (format (current-error-port) ";;; ~a\n" s)))
3489 (call-with-output-string
3490 (lambda (port) (print-exception port #f k args)))
3494 (define (absolute-path? path)
3495 (string-prefix? "/" path))
3497 (define (load-absolute abs-path)
3498 (let ((cfn (let ((canon (false-if-exception (canonicalize-path abs-path))))
3500 (let ((go-path (compiled-file-name canon)))
3502 (fresh-compiled-file-name abs-path go-path)))))))
3506 (%load-hook abs-path))
3507 (load-compiled cfn))
3508 (start-stack 'load-stack
3509 (primitive-load abs-path)))))
3511 (save-module-excursion
3513 (with-fluids ((current-reader reader)
3514 (%file-port-name-canonicalization 'relative))
3516 ((or (absolute-path? path))
3517 (load-absolute path))
3518 ((absolute-path? dir)
3519 (load-absolute (in-vicinity dir path)))
3521 (load-from-path (in-vicinity dir path))))))))
3524 (make-variable-transformer
3526 (let* ((src (syntax-source x))
3527 (file (and src (assq-ref src 'filename)))
3528 (dir (and (string? file) (dirname file))))
3531 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
3535 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
3539 ;;; {`cond-expand' for SRFI-0 support.}
3541 ;;; This syntactic form expands into different commands or
3542 ;;; definitions, depending on the features provided by the Scheme
3548 ;;; --> (cond-expand <cond-expand-clause>+)
3549 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3550 ;;; <cond-expand-clause>
3551 ;;; --> (<feature-requirement> <command-or-definition>*)
3552 ;;; <feature-requirement>
3553 ;;; --> <feature-identifier>
3554 ;;; | (and <feature-requirement>*)
3555 ;;; | (or <feature-requirement>*)
3556 ;;; | (not <feature-requirement>)
3557 ;;; <feature-identifier>
3558 ;;; --> <a symbol which is the name or alias of a SRFI>
3560 ;;; Additionally, this implementation provides the
3561 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3562 ;;; determine the implementation type and the supported standard.
3564 ;;; Currently, the following feature identifiers are supported:
3566 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3568 ;;; Remember to update the features list when adding more SRFIs.
3571 (define %cond-expand-features
3572 ;; Adjust the above comment when changing this.
3576 srfi-0 ;; cond-expand itself
3577 srfi-4 ;; homogenous numeric vectors
3578 srfi-6 ;; open-input-string etc, in the guile core
3579 srfi-13 ;; string library
3580 srfi-23 ;; `error` procedure
3581 srfi-14 ;; character sets
3582 srfi-55 ;; require-extension
3583 srfi-61 ;; general cond clause
3586 ;; This table maps module public interfaces to the list of features.
3588 (define %cond-expand-table (make-hash-table 31))
3590 ;; Add one or more features to the `cond-expand' feature list of the
3593 (define (cond-expand-provide module features)
3594 (let ((mod (module-public-interface module)))
3596 (hashq-set! %cond-expand-table mod
3597 (append (hashq-ref %cond-expand-table mod '())
3600 (define-syntax cond-expand
3602 (define (module-has-feature? mod sym)
3603 (or-map (lambda (mod)
3604 (memq sym (hashq-ref %cond-expand-table mod '())))
3607 (define (condition-matches? condition)
3608 (syntax-case condition (and or not)
3610 (and-map condition-matches? #'(c ...)))
3612 (or-map condition-matches? #'(c ...)))
3614 (if (condition-matches? #'c) #f #t))
3617 (let ((sym (syntax->datum #'c)))
3618 (if (memq sym %cond-expand-features)
3620 (module-has-feature? (current-module) sym))))))
3622 (define (match clauses alternate)
3623 (syntax-case clauses ()
3624 (((condition form ...) . rest)
3625 (if (condition-matches? #'condition)
3627 (match #'rest alternate)))
3630 (syntax-case x (else)
3631 ((_ clause ... (else form ...))
3632 (match #'(clause ...)
3634 #'(begin form ...))))
3636 (match #'(clause ...)
3638 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
3640 ;; This procedure gets called from the startup code with a list of
3641 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3643 (define (use-srfis srfis)
3644 (process-use-modules
3646 (list (list 'srfi (string->symbol
3647 (string-append "srfi-" (number->string num))))))
3652 ;;; srfi-55: require-extension
3655 (define-syntax require-extension
3657 (syntax-case x (srfi)
3659 (and-map integer? (syntax->datum #'(n ...)))
3663 (datum->syntax x (symbol-append 'srfi- n)))
3665 (map number->string (syntax->datum #'(n ...)))))))
3666 #'(use-modules (srfi srfi-n) ...)))
3668 (identifier? #'type)
3669 (syntax-violation 'require-extension "Not a recognized extension type"
3673 ;;; Defining transparently inlinable procedures
3676 (define-syntax define-inlinable
3677 ;; Define a macro and a procedure such that direct calls are inlined, via
3678 ;; the macro expansion, whereas references in non-call contexts refer to
3679 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
3681 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
3683 (define prefix (string->symbol "% "))
3684 (define (make-procedure-name name)
3686 (symbol-append prefix (syntax->datum name)
3690 ((_ (name formals ...) body ...)
3691 (identifier? #'name)
3692 (with-syntax ((proc-name (make-procedure-name #'name))
3693 ((args ...) (generate-temporaries #'(formals ...))))
3695 (define (proc-name formals ...)
3696 (fluid-let-syntax ((name (identifier-syntax proc-name)))
3702 #'((fluid-let-syntax ((name (identifier-syntax proc-name)))
3703 (lambda (formals ...)
3708 #'proc-name))))))))))
3712 (define using-readline?
3713 (let ((using-readline? (make-fluid)))
3714 (make-procedure-with-setter
3715 (lambda () (fluid-ref using-readline?))
3716 (lambda (v) (fluid-set! using-readline? v)))))
3720 ;;; {Deprecated stuff}
3724 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3728 ;;; Place the user in the guile-user module.
3732 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3734 ;; Set filename to #f to prevent reload.
3735 (define-module (guile-user)
3736 #:autoload (system base compile) (compile compile-file)
3739 ;; Remain in the `(guile)' module at compilation-time so that the
3740 ;; `-Wunused-toplevel' warning works as expected.
3741 (eval-when (compile) (set-current-module the-root-module))
3743 ;;; boot-9.scm ends here