1 ;;; -*- mode: scheme; coding: utf-8; -*-
3 ;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 ;;;; 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
5 ;;;; Free Software Foundation, Inc.
7 ;;;; This library is free software; you can redistribute it and/or
8 ;;;; modify it under the terms of the GNU Lesser General Public
9 ;;;; License as published by the Free Software Foundation; either
10 ;;;; version 3 of the License, or (at your option) any later version.
12 ;;;; This library is distributed in the hope that it will be useful,
13 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 ;;;; Lesser General Public License for more details.
17 ;;;; You should have received a copy of the GNU Lesser General Public
18 ;;;; License along with this library; if not, write to the Free Software
19 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 ;;; This file is the first thing loaded into Guile. It adds many mundane
27 ;;; definitions and a few that are interesting.
29 ;;; The module system (hence the hierarchical namespace) are defined in this
37 ;; Before compiling, make sure any symbols are resolved in the (guile)
38 ;; module, the primary location of those symbols, rather than in
39 ;; (guile-user), the default module that we compile in.
42 (set-current-module (resolve-module '(guile))))
49 ;; Define delimited continuation operators, and implement catch and throw in
52 (define make-prompt-tag
53 (lambda* (#:optional (stem "prompt"))
56 (define default-prompt-tag
57 ;; not sure if we should expose this to the user as a fluid
58 (let ((%default-prompt-tag (make-prompt-tag)))
60 %default-prompt-tag)))
62 (define (call-with-prompt tag thunk handler)
63 (@prompt tag (thunk) handler))
64 (define (abort-to-prompt tag . args)
68 ;; Define catch and with-throw-handler, using some common helper routines and a
69 ;; shared fluid. Hide the helpers in a lexical contour.
71 (define with-throw-handler #f)
73 (define (default-exception-handler k . args)
77 ((not (pair? args)) 0)
78 ((integer? (car args)) (car args))
82 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
85 (define %running-exception-handlers (make-fluid '()))
86 (define %exception-handler (make-fluid default-exception-handler))
88 (define (default-throw-handler prompt-tag catch-k)
89 (let ((prev (fluid-ref %exception-handler)))
90 (lambda (thrown-k . args)
91 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
92 (apply abort-to-prompt prompt-tag thrown-k args)
93 (apply prev thrown-k args)))))
95 (define (custom-throw-handler prompt-tag catch-k pre)
96 (let ((prev (fluid-ref %exception-handler)))
97 (lambda (thrown-k . args)
98 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
99 (let ((running (fluid-ref %running-exception-handlers)))
100 (with-fluids ((%running-exception-handlers (cons pre running)))
101 (if (not (memq pre running))
102 (apply pre thrown-k args))
105 (apply abort-to-prompt prompt-tag thrown-k args)
106 (apply prev thrown-k args))))
107 (apply prev thrown-k args)))))
110 (lambda* (k thunk handler #:optional pre-unwind-handler)
111 "Invoke @var{thunk} in the dynamic context of @var{handler} for
112 exceptions matching @var{key}. If thunk throws to the symbol
113 @var{key}, then @var{handler} is invoked this way:
115 (handler key args ...)
118 @var{key} is a symbol or @code{#t}.
120 @var{thunk} takes no arguments. If @var{thunk} returns
121 normally, that is the return value of @code{catch}.
123 Handler is invoked outside the scope of its own @code{catch}.
124 If @var{handler} again throws to the same key, a new handler
125 from further up the call chain is invoked.
127 If the key is @code{#t}, then a throw to @emph{any} symbol will
128 match this call to @code{catch}.
130 If a @var{pre-unwind-handler} is given and @var{thunk} throws
131 an exception that matches @var{key}, Guile calls the
132 @var{pre-unwind-handler} before unwinding the dynamic state and
133 invoking the main @var{handler}. @var{pre-unwind-handler} should
134 be a procedure with the same signature as @var{handler}, that
135 is @code{(lambda (key . args))}. It is typically used to save
136 the stack at the point where the exception occurred, but can also
137 query other parts of the dynamic state at that point, such as
140 A @var{pre-unwind-handler} can exit either normally or non-locally.
141 If it exits normally, Guile unwinds the stack and dynamic context
142 and then calls the normal (third argument) handler. If it exits
143 non-locally, that exit determines the continuation."
144 (if (not (or (symbol? k) (eqv? k #t)))
145 (scm-error 'wrong-type-arg "catch"
146 "Wrong type argument in position ~a: ~a"
147 (list 1 k) (list k)))
148 (let ((tag (make-prompt-tag "catch")))
154 (if pre-unwind-handler
155 (custom-throw-handler tag k pre-unwind-handler)
156 (default-throw-handler tag k))))
158 (lambda (cont k . args)
159 (apply handler k args))))))
161 (set! with-throw-handler
162 (lambda (k thunk pre-unwind-handler)
163 "Add @var{handler} to the dynamic context as a throw handler
164 for key @var{key}, then invoke @var{thunk}."
165 (if (not (or (symbol? k) (eqv? k #t)))
166 (scm-error 'wrong-type-arg "with-throw-handler"
167 "Wrong type argument in position ~a: ~a"
168 (list 1 k) (list k)))
169 (with-fluids ((%exception-handler
170 (custom-throw-handler #f k pre-unwind-handler)))
175 "Invoke the catch form matching @var{key}, passing @var{args} to the
178 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
180 If there is no handler at all, Guile prints an error and then exits."
181 (if (not (symbol? key))
182 ((fluid-ref %exception-handler) 'wrong-type-arg "throw"
183 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
184 (apply (fluid-ref %exception-handler) key args)))))
189 ;;; {R4RS compliance}
192 (primitive-load-path "ice-9/r4rs")
196 ;;; {Simple Debugging Tools}
199 ;; peek takes any number of arguments, writes them to the
200 ;; current ouput port, and returns the last argument.
201 ;; It is handy to wrap around an expression to look at
202 ;; a value each time is evaluated, e.g.:
204 ;; (+ 10 (troublesome-fn))
205 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
208 (define (peek . stuff)
213 (car (last-pair stuff)))
217 ;; Temporary definition; replaced later.
218 (define current-warning-port current-error-port)
220 (define (warn . stuff)
221 (with-output-to-port (current-warning-port)
224 (display ";;; WARNING ")
227 (car (last-pair stuff)))))
234 (define (provide sym)
235 (if (not (memq sym *features*))
236 (set! *features* (cons sym *features*))))
238 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
239 ;; provided? also checks to see if the module is available. We should do that
242 (define (provided? feature)
243 (and (memq feature *features*) #t))
250 (define (make-struct/no-tail vtable . args)
251 (apply make-struct vtable 0 args))
255 ;;; Boot versions of `map' and `for-each', enough to get the expander
264 (cons (f (car l)) (map1 (cdr l))))))
266 (let map2 ((l1 l1) (l2 l2))
269 (cons (f (car l1) (car l2))
270 (map2 (cdr l1) (cdr l2))))))
272 (let lp ((l1 l1) (rest rest))
275 (cons (apply f (car l1) (map car rest))
276 (lp (cdr l1) (map cdr rest))))))))
281 (let for-each1 ((l l))
285 (for-each1 (cdr l))))))
287 (let for-each2 ((l1 l1) (l2 l2))
290 (f (car l1) (car l2))
291 (for-each2 (cdr l1) (cdr l2))))))
293 (let lp ((l1 l1) (rest rest))
296 (apply f (car l1) (map car rest))
297 (lp (cdr l1) (map cdr rest))))))))
299 ;;; {and-map and or-map}
301 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
302 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
307 ;; Apply f to successive elements of l until exhaustion or f returns #f.
308 ;; If returning early, return #f. Otherwise, return the last value returned
309 ;; by f. If f has never been called because l is empty, return #t.
311 (define (and-map f lst)
312 (let loop ((result #t)
317 (loop (f (car l)) (cdr l))))))
321 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
322 ;; If returning early, return the return value of f.
324 (define (or-map f lst)
325 (let loop ((result #f)
329 (loop (f (car l)) (cdr l))))))
333 ;; let format alias simple-format until the more complete version is loaded
335 (define format simple-format)
337 ;; this is scheme wrapping the C code so the final pred call is a tail call,
340 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
341 (if (and (procedure? char_pred)
343 (<= end (string-length s))) ;; let c-code handle range error
344 (or (string-any-c-code char_pred s start (1- end))
345 (char_pred (string-ref s (1- end))))
346 (string-any-c-code char_pred s start end))))
348 ;; this is scheme wrapping the C code so the final pred call is a tail call,
351 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
352 (if (and (procedure? char_pred)
354 (<= end (string-length s))) ;; let c-code handle range error
355 (and (string-every-c-code char_pred s start (1- end))
356 (char_pred (string-ref s (1- end))))
357 (string-every-c-code char_pred s start end))))
359 ;; A variant of string-fill! that we keep for compatability
361 (define (substring-fill! str start end fill)
362 (string-fill! str fill start end))
366 ;; Define a minimal stub of the module API for psyntax, before modules
368 (define (module-name x)
370 (define (module-add! module sym var)
371 (hashq-set! (%get-pre-modules-obarray) sym var))
372 (define (module-define! module sym val)
373 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
375 (variable-set! v val)
376 (module-add! (current-module) sym (make-variable val)))))
377 (define (module-ref module sym)
378 (let ((v (module-variable module sym)))
379 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
380 (define (resolve-module . args)
383 ;; API provided by psyntax
384 (define syntax-violation #f)
385 (define datum->syntax #f)
386 (define syntax->datum #f)
387 (define syntax-source #f)
388 (define identifier? #f)
389 (define generate-temporaries #f)
390 (define bound-identifier=? #f)
391 (define free-identifier=? #f)
392 (define syntax-local-binding #f)
393 (define syntax-locally-bound-identifiers #f)
395 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
396 ;; expanded macros, to dispatch an input against a set of patterns.
397 (define $sc-dispatch #f)
400 (primitive-load-path "ice-9/psyntax-pp")
401 ;; The binding for `macroexpand' has now been overridden, making psyntax the
408 ((_ x y ...) (if x (and y ...) #f))))
414 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
416 (define-syntax-rule (when test stmt stmt* ...)
417 (if test (begin stmt stmt* ...)))
419 (define-syntax-rule (unless test stmt stmt* ...)
420 (if (not test) (begin stmt stmt* ...)))
422 ;; The "maybe-more" bits are something of a hack, so that we can support
423 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
426 (syntax-rules (=> else)
427 ((_ "maybe-more" test consequent)
428 (if test consequent))
430 ((_ "maybe-more" test consequent clause ...)
431 (if test consequent (cond clause ...)))
433 ((_ (else else1 else2 ...))
434 (begin else1 else2 ...))
436 ((_ (test => receiver) more-clause ...)
438 (cond "maybe-more" t (receiver t) more-clause ...)))
440 ((_ (generator guard => receiver) more-clause ...)
441 (call-with-values (lambda () generator)
444 (apply guard t) (apply receiver t) more-clause ...))))
446 ((_ (test => receiver ...) more-clause ...)
447 (syntax-violation 'cond "wrong number of receiver expressions"
448 '(test => receiver ...)))
449 ((_ (generator guard => receiver ...) more-clause ...)
450 (syntax-violation 'cond "wrong number of receiver expressions"
451 '(generator guard => receiver ...)))
453 ((_ (test) more-clause ...)
455 (cond "maybe-more" t t more-clause ...)))
457 ((_ (test body1 body2 ...) more-clause ...)
459 test (begin body1 body2 ...) more-clause ...))))
465 (let ((atom-key (key ...)))
466 (case atom-key clauses ...)))
468 (else result1 result2 ...))
469 (begin result1 result2 ...))
471 ((atoms ...) result1 result2 ...))
472 (if (memv key '(atoms ...))
473 (begin result1 result2 ...)))
475 ((atoms ...) result1 result2 ...)
477 (if (memv key '(atoms ...))
478 (begin result1 result2 ...)
479 (case key clause clauses ...)))))
483 ((do ((var init step ...) ...)
496 (loop (do "step" var step ...)
504 (define-syntax-rule (delay exp)
505 (make-promise (lambda () exp)))
507 (include-from-path "ice-9/quasisyntax")
509 (define-syntax current-source-location
513 (with-syntax ((s (datum->syntax x (syntax-source x))))
516 ;; We provide this accessor out of convenience. current-line and
517 ;; current-column aren't so interesting, because they distort what they
518 ;; are measuring; better to use syntax-source from a macro.
520 (define-syntax current-filename
522 "A macro that expands to the current filename: the filename that
523 the (current-filename) form appears in. Expands to #f if this
524 information is unavailable."
526 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
528 (define-syntax-rule (define-once sym val)
530 (if (module-locally-bound? (current-module) 'sym) sym val)))
532 ;;; The real versions of `map' and `for-each', with cycle detection, and
533 ;;; that use reverse! instead of recursion in the case of `map'.
538 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
541 (if (eq? tortoise hare)
542 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
544 (map1 (cdr hare) (cdr tortoise) #f
545 (cons (f (car hare)) out)))
546 (map1 (cdr hare) tortoise #t
547 (cons (f (car hare)) out)))
550 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
554 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
559 (scm-error 'wrong-type-arg "map"
561 "List of wrong length: ~S"
565 (map2 (cdr h1) (cdr h2) t1 t2 #t
566 (cons (f (car h1) (car h2)) out)))
568 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
571 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
574 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
575 (cons (f (car h1) (car h2)) out)))))
577 ((and (null? h1) (null? h2))
581 (scm-error 'wrong-type-arg "map"
583 "List of wrong length: ~S"
587 (scm-error 'wrong-type-arg "map"
592 (let ((len (length l1)))
593 (let mapn ((rest rest))
595 (if (= (length (car rest)) len)
597 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
598 (list (car rest)) #f)))))
599 (let mapn ((l1 l1) (rest rest) (out '()))
602 (mapn (cdr l1) (map cdr rest)
603 (cons (apply f (car l1) (map car rest)) out)))))))
605 (define map-in-order map)
610 (let for-each1 ((hare l) (tortoise l) (move? #f))
613 (if (eq? tortoise hare)
614 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
618 (for-each1 (cdr hare) (cdr tortoise) #f)))
621 (for-each1 (cdr hare) tortoise #t)))
623 (if (not (null? hare))
624 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
628 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
630 ((and (pair? h1) (pair? h2))
633 (f (car h1) (car h2))
634 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
636 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
639 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
642 (f (car h1) (car h2))
643 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
646 (or (null? h2) (pair? h2))
647 (and (pair? h1) (null? h2)))
651 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
654 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
658 (let ((len (length l1)))
659 (let for-eachn ((rest rest))
661 (if (= (length (car rest)) len)
662 (for-eachn (cdr rest))
663 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
664 (list (car rest)) #f)))))
666 (let for-eachn ((l1 l1) (rest rest))
669 (apply f (car l1) (map car rest))
670 (for-eachn (cdr l1) (map cdr rest))))))))
676 ;;; Extensible exception printing.
679 (define set-exception-printer! #f)
680 ;; There is already a definition of print-exception from backtrace.c
681 ;; that we will override.
683 (let ((exception-printers '()))
684 (define (print-location frame port)
685 (let ((source (and=> frame frame-source)))
686 ;; source := (addr . (filename . (line . column)))
688 (let ((filename (or (cadr source) "<unnamed port>"))
689 (line (caddr source))
690 (col (cdddr source)))
691 (format port "~a:~a:~a: " filename (1+ line) col))
692 (format port "ERROR: "))))
694 (set! set-exception-printer!
696 (set! exception-printers (acons key proc exception-printers))))
698 (set! print-exception
699 (lambda (port frame key args)
700 (define (default-printer)
701 (format port "Throw to key `~a' with args `~s'." key args))
704 (let ((proc (frame-procedure frame)))
705 (print-location frame port)
706 (format port "In procedure ~a:\n"
707 (or (procedure-name proc) proc))))
709 (print-location frame port)
712 (let ((printer (assq-ref exception-printers key)))
714 (printer port key args default-printer)
717 (format port "Error while printing exception.")))
719 (force-output port))))
722 ;;; Printers for those keys thrown by Guile.
725 (define (scm-error-printer port key args default-printer)
726 ;; Abuse case-lambda as a pattern matcher, given that we don't have
727 ;; ice-9 match at this point.
729 ((subr msg args . rest)
731 (format port "In procedure ~a: " subr))
732 (apply format port msg (or args '())))
733 (_ (default-printer)))
736 (define (syntax-error-printer port key args default-printer)
738 ((who what where form subform . extra)
739 (format port "Syntax error:\n")
741 (let ((file (or (assq-ref where 'filename) "unknown file"))
742 (line (and=> (assq-ref where 'line) 1+))
743 (col (assq-ref where 'column)))
744 (format port "~a:~a:~a: " file line col))
745 (format port "unknown location: "))
747 (format port "~a: " who))
748 (format port "~a" what)
750 (format port " in subform ~s of ~s" subform form)
752 (format port " in form ~s" form))))
753 (_ (default-printer)))
756 (define (getaddrinfo-error-printer port key args default-printer)
757 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
759 (set-exception-printer! 'goops-error scm-error-printer)
760 (set-exception-printer! 'host-not-found scm-error-printer)
761 (set-exception-printer! 'keyword-argument-error scm-error-printer)
762 (set-exception-printer! 'misc-error scm-error-printer)
763 (set-exception-printer! 'no-data scm-error-printer)
764 (set-exception-printer! 'no-recovery scm-error-printer)
765 (set-exception-printer! 'null-pointer-error scm-error-printer)
766 (set-exception-printer! 'out-of-range scm-error-printer)
767 (set-exception-printer! 'program-error scm-error-printer)
768 (set-exception-printer! 'read-error scm-error-printer)
769 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
770 (set-exception-printer! 'signal scm-error-printer)
771 (set-exception-printer! 'stack-overflow scm-error-printer)
772 (set-exception-printer! 'system-error scm-error-printer)
773 (set-exception-printer! 'try-again scm-error-printer)
774 (set-exception-printer! 'unbound-variable scm-error-printer)
775 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
776 (set-exception-printer! 'wrong-type-arg scm-error-printer)
778 (set-exception-printer! 'syntax-error syntax-error-printer)
780 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
788 (define-syntax define-macro
792 ((_ (macro . args) doc body1 body ...)
793 (string? (syntax->datum #'doc))
794 #'(define-macro macro doc (lambda args body1 body ...)))
795 ((_ (macro . args) body ...)
796 #'(define-macro macro #f (lambda args body ...)))
797 ((_ macro doc transformer)
798 (or (string? (syntax->datum #'doc))
799 (not (syntax->datum #'doc)))
800 #'(define-syntax macro
803 #((macro-type . defmacro)
804 (defmacro-args args))
807 (let ((v (syntax->datum #'args)))
808 (datum->syntax y (apply transformer v)))))))))))
810 (define-syntax defmacro
812 "Define a defmacro, with the old lispy defun syntax."
814 ((_ macro args doc body1 body ...)
815 (string? (syntax->datum #'doc))
816 #'(define-macro macro doc (lambda args body1 body ...)))
817 ((_ macro args body ...)
818 #'(define-macro macro #f (lambda args body ...))))))
827 (define-syntax begin-deprecated
831 (if (include-deprecated-features)
832 #'(begin form form* ...)
837 ;;; {Trivial Functions}
840 (define (identity x) x)
842 (define (compose proc . rest)
843 "Compose PROC with the procedures in REST, such that the last one in
844 REST is applied first and PROC last, and return the resulting procedure.
845 The given procedures must have compatible arity."
848 (let ((g (apply compose rest)))
850 (call-with-values (lambda () (apply g args)) proc)))))
852 (define (negate proc)
853 "Return a procedure with the same arity as PROC that returns the `not'
856 (not (apply proc args))))
858 (define (const value)
859 "Return a procedure that accepts any number of arguments and returns
864 (define (and=> value procedure) (and value (procedure value)))
865 (define call/cc call-with-current-continuation)
867 (define-syntax-rule (false-if-exception expr)
870 (lambda (k . args) #f)))
874 ;;; {General Properties}
877 ;; Properties are a lispy way to associate random info with random objects.
878 ;; Traditionally properties are implemented as an alist or a plist actually
879 ;; pertaining to the object in question.
881 ;; These "object properties" have the advantage that they can be associated with
882 ;; any object, even if the object has no plist. Object properties are good when
883 ;; you are extending pre-existing objects in unexpected ways. They also present
884 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
885 ;; type that always has properties, it's often still best to store those
886 ;; properties within the object itself.
888 (define (make-object-property)
889 (define-syntax-rule (with-mutex lock exp)
890 (dynamic-wind (lambda () (lock-mutex lock))
892 (lambda () (unlock-mutex lock))))
893 (let ((prop (make-weak-key-hash-table))
895 (make-procedure-with-setter
896 (lambda (obj) (with-mutex lock (hashq-ref prop obj)))
897 (lambda (obj val) (with-mutex lock (hashq-set! prop obj val))))))
902 ;;; {Symbol Properties}
905 ;;; Symbol properties are something you see in old Lisp code. In most current
906 ;;; Guile code, symbols are not used as a data structure -- they are used as
907 ;;; keys into other data structures.
909 (define (symbol-property sym prop)
910 (let ((pair (assoc prop (symbol-pref sym))))
911 (and pair (cdr pair))))
913 (define (set-symbol-property! sym prop val)
914 (let ((pair (assoc prop (symbol-pref sym))))
917 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
919 (define (symbol-property-remove! sym prop)
920 (let ((pair (assoc prop (symbol-pref sym))))
922 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
929 (define (array-shape a)
930 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
931 (array-dimensions a)))
938 ;;; It's much better if you can use lambda* / define*, of course.
940 (define (kw-arg-ref args kw)
941 (let ((rem (member kw args)))
942 (and rem (pair? (cdr rem)) (cadr rem))))
949 (define (struct-layout s)
950 (struct-ref (struct-vtable s) vtable-index-layout))
957 ;; Printing records: by default, records are printed as
959 ;; #<type-name field1: val1 field2: val2 ...>
961 ;; You can change that by giving a custom printing function to
962 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
963 ;; will be called like
965 ;; (<printer> object port)
967 ;; It should print OBJECT to PORT.
969 (define (inherit-print-state old-port new-port)
970 (if (get-print-state old-port)
971 (port-with-print-state new-port (get-print-state old-port))
974 ;; 0: type-name, 1: fields, 2: constructor
975 (define record-type-vtable
976 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
977 ;; that we need to expose the bare vtable-vtable to Scheme.
978 (make-vtable-vtable "prprpw" 0
980 (cond ((eq? s record-type-vtable)
981 (display "#<record-type-vtable>" p))
983 (display "#<record-type " p)
984 (display (record-type-name s) p)
987 (define (record-type? obj)
988 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
990 (define* (make-record-type type-name fields #:optional printer)
991 ;; Pre-generate constructors for nfields < 20.
992 (define-syntax make-constructor
994 (define *max-static-argument-count* 20)
995 (define (make-formals n)
1001 (string (integer->char (+ (char->integer #\a) i)))))
1005 ((_ rtd exp) (not (identifier? #'exp))
1007 (make-constructor rtd n)))
1011 (if (< n *max-static-argument-count*)
1012 (cons (with-syntax (((formal ...) (make-formals n))
1015 (lambda (formal ...)
1016 (make-struct rtd 0 formal ...))))
1021 (if (= (length args) nfields)
1022 (apply make-struct rtd 0 args)
1023 (scm-error 'wrong-number-of-args
1024 (format #f "make-~a" type-name)
1025 "Wrong number of arguments" '() #f)))))))))
1027 (define (default-record-printer s p)
1029 (display (record-type-name (record-type-descriptor s)) p)
1030 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1033 ((not (null? fields))
1035 (display (car fields) p)
1037 (display (struct-ref s off) p)
1038 (loop (cdr fields) (+ 1 off)))))
1041 (let ((rtd (make-struct record-type-vtable 0
1043 (apply string-append
1044 (map (lambda (f) "pw") fields)))
1045 (or printer default-record-printer)
1047 (copy-tree fields))))
1048 (struct-set! rtd (+ vtable-offset-user 2)
1049 (make-constructor rtd (length fields)))
1050 ;; Temporary solution: Associate a name to the record type descriptor
1051 ;; so that the object system can create a wrapper class for it.
1052 (set-struct-vtable-name! rtd (if (symbol? type-name)
1054 (string->symbol type-name)))
1057 (define (record-type-name obj)
1058 (if (record-type? obj)
1059 (struct-ref obj vtable-offset-user)
1060 (error 'not-a-record-type obj)))
1062 (define (record-type-fields obj)
1063 (if (record-type? obj)
1064 (struct-ref obj (+ 1 vtable-offset-user))
1065 (error 'not-a-record-type obj)))
1067 (define* (record-constructor rtd #:optional field-names)
1068 (if (not field-names)
1069 (struct-ref rtd (+ 2 vtable-offset-user))
1071 `(lambda ,field-names
1072 (make-struct ',rtd 0 ,@(map (lambda (f)
1073 (if (memq f field-names)
1076 (record-type-fields rtd)))))))
1078 (define (record-predicate rtd)
1079 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1081 (define (%record-type-error rtd obj) ;; private helper
1082 (or (eq? rtd (record-type-descriptor obj))
1083 (scm-error 'wrong-type-arg "%record-type-check"
1084 "Wrong type record (want `~S'): ~S"
1085 (list (record-type-name rtd) obj)
1088 (define (record-accessor rtd field-name)
1089 (let ((pos (list-index (record-type-fields rtd) field-name)))
1091 (error 'no-such-field field-name))
1093 (if (eq? (struct-vtable obj) rtd)
1094 (struct-ref obj pos)
1095 (%record-type-error rtd obj)))))
1097 (define (record-modifier rtd field-name)
1098 (let ((pos (list-index (record-type-fields rtd) field-name)))
1100 (error 'no-such-field field-name))
1102 (if (eq? (struct-vtable obj) rtd)
1103 (struct-set! obj pos val)
1104 (%record-type-error rtd obj)))))
1106 (define (record? obj)
1107 (and (struct? obj) (record-type? (struct-vtable obj))))
1109 (define (record-type-descriptor obj)
1112 (error 'not-a-record obj)))
1121 (define (->bool x) (not (not x)))
1128 (define (symbol-append . args)
1129 (string->symbol (apply string-append (map symbol->string args))))
1131 (define (list->symbol . args)
1132 (string->symbol (apply list->string args)))
1134 (define (symbol . args)
1135 (string->symbol (apply string args)))
1142 (define (list-index l k)
1145 (and (not (null? l))
1148 (loop (+ n 1) (cdr l))))))
1152 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1153 ;; `stat' accessors.
1154 (primitive-load-path "ice-9/posix")
1156 (if (provided? 'socket)
1157 (primitive-load-path "ice-9/networking"))
1159 ;; For reference, Emacs file-exists-p uses stat in this same way.
1160 (define file-exists?
1161 (if (provided? 'posix)
1163 (->bool (stat str #f)))
1165 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
1167 (if port (begin (close-port port) #t)
1170 (define file-is-directory?
1171 (if (provided? 'posix)
1173 (eq? (stat:type (stat str)) 'directory))
1175 (let ((port (catch 'system-error
1176 (lambda () (open-file (string-append str "/.")
1179 (if port (begin (close-port port) #t)
1182 (define (system-error-errno args)
1183 (if (eq? (car args) 'system-error)
1184 (car (list-ref args 4))
1189 ;;; {Error Handling}
1195 (scm-error 'misc-error #f "?" #f #f))
1197 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1198 (scm-error 'misc-error #f msg (cons message args) #f)))))
1202 ;;; {Time Structures}
1205 (define (tm:sec obj) (vector-ref obj 0))
1206 (define (tm:min obj) (vector-ref obj 1))
1207 (define (tm:hour obj) (vector-ref obj 2))
1208 (define (tm:mday obj) (vector-ref obj 3))
1209 (define (tm:mon obj) (vector-ref obj 4))
1210 (define (tm:year obj) (vector-ref obj 5))
1211 (define (tm:wday obj) (vector-ref obj 6))
1212 (define (tm:yday obj) (vector-ref obj 7))
1213 (define (tm:isdst obj) (vector-ref obj 8))
1214 (define (tm:gmtoff obj) (vector-ref obj 9))
1215 (define (tm:zone obj) (vector-ref obj 10))
1217 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1218 (define (set-tm:min obj val) (vector-set! obj 1 val))
1219 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1220 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1221 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1222 (define (set-tm:year obj val) (vector-set! obj 5 val))
1223 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1224 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1225 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1226 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1227 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1229 (define (tms:clock obj) (vector-ref obj 0))
1230 (define (tms:utime obj) (vector-ref obj 1))
1231 (define (tms:stime obj) (vector-ref obj 2))
1232 (define (tms:cutime obj) (vector-ref obj 3))
1233 (define (tms:cstime obj) (vector-ref obj 4))
1237 ;;; {File Descriptors and Ports}
1240 (define file-position ftell)
1241 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1242 (seek port offset whence))
1244 (define (move->fdes fd/port fd)
1245 (cond ((integer? fd/port)
1246 (dup->fdes fd/port fd)
1250 (primitive-move->fdes fd/port fd)
1251 (set-port-revealed! fd/port 1)
1254 (define (release-port-handle port)
1255 (let ((revealed (port-revealed port)))
1257 (set-port-revealed! port (- revealed 1)))))
1262 (fdopen (dup->fdes port/fd) mode))
1263 ((port/fd mode new-fd)
1264 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1265 (set-port-revealed! port 1)
1271 (dup->port port/fd "r"))
1273 (dup->port port/fd "r" new-fd))))
1275 (define dup->outport
1278 (dup->port port/fd "w"))
1280 (dup->port port/fd "w" new-fd))))
1285 (if (integer? port/fd)
1287 (dup->port port/fd (port-mode port/fd))))
1289 (if (integer? port/fd)
1290 (dup->fdes port/fd new-fd)
1291 (dup->port port/fd (port-mode port/fd) new-fd)))))
1293 (define (duplicate-port port modes)
1294 (dup->port port modes))
1296 (define (fdes->inport fdes)
1297 (let loop ((rest-ports (fdes->ports fdes)))
1298 (cond ((null? rest-ports)
1299 (let ((result (fdopen fdes "r")))
1300 (set-port-revealed! result 1)
1302 ((input-port? (car rest-ports))
1303 (set-port-revealed! (car rest-ports)
1304 (+ (port-revealed (car rest-ports)) 1))
1307 (loop (cdr rest-ports))))))
1309 (define (fdes->outport fdes)
1310 (let loop ((rest-ports (fdes->ports fdes)))
1311 (cond ((null? rest-ports)
1312 (let ((result (fdopen fdes "w")))
1313 (set-port-revealed! result 1)
1315 ((output-port? (car rest-ports))
1316 (set-port-revealed! (car rest-ports)
1317 (+ (port-revealed (car rest-ports)) 1))
1320 (loop (cdr rest-ports))))))
1322 (define (port->fdes port)
1323 (set-port-revealed! port (+ (port-revealed port) 1))
1326 (define (setenv name value)
1328 (putenv (string-append name "=" value))
1331 (define (unsetenv name)
1332 "Remove the entry for NAME from the environment."
1340 (define (in-vicinity vicinity file)
1341 (let ((tail (let ((len (string-length vicinity)))
1344 (string-ref vicinity (- len 1))))))
1345 (string-append vicinity
1354 ;;; {Help for scm_shell}
1356 ;;; The argument-processing code used by Guile-based shells generates
1357 ;;; Scheme code based on the argument list. This page contains help
1358 ;;; functions for the code it generates.
1361 (define (command-line) (program-arguments))
1363 ;; This is mostly for the internal use of the code generated by
1364 ;; scm_compile_shell_switches.
1366 (define (load-user-init)
1367 (let* ((home (or (getenv "HOME")
1368 (false-if-exception (passwd:dir (getpwuid (getuid))))
1369 "/")) ;; fallback for cygwin etc.
1370 (init-file (in-vicinity home ".guile")))
1371 (if (file-exists? init-file)
1372 (primitive-load init-file))))
1376 ;;; {The interpreter stack}
1379 ;; %stacks defined in stacks.c
1380 (define (%start-stack tag thunk)
1381 (let ((prompt-tag (make-prompt-tag "start-stack")))
1385 (with-fluids ((%stacks (acons tag prompt-tag
1386 (or (fluid-ref %stacks) '()))))
1389 (%start-stack tag (lambda () (apply k args)))))))
1391 (define-syntax-rule (start-stack tag exp)
1392 (%start-stack tag (lambda () exp)))
1396 ;;; {Loading by paths}
1399 ;;; Load a Scheme source file named NAME, searching for it in the
1400 ;;; directories listed in %load-path, and applying each of the file
1401 ;;; name extensions listed in %load-extensions.
1402 (define (load-from-path name)
1403 (start-stack 'load-stack
1404 (primitive-load-path name)))
1406 (define-syntax-rule (add-to-load-path elt)
1407 "Add ELT to Guile's load path, at compile-time and at run-time."
1408 (eval-when (compile load eval)
1409 (set! %load-path (cons elt %load-path))))
1411 (define %load-verbosely #f)
1412 (define (assert-load-verbosity v) (set! %load-verbosely v))
1414 (define (%load-announce file)
1416 (with-output-to-port (current-warning-port)
1419 (display "loading ")
1424 (set! %load-hook %load-announce)
1428 ;;; {Reader Extensions}
1430 ;;; Reader code for various "#c" forms.
1433 (define read-eval? (make-fluid #f))
1434 (read-hash-extend #\.
1436 (if (fluid-ref read-eval?)
1437 (eval (read port) (interaction-environment))
1439 "#. read expansion found and read-eval? is #f."))))
1443 ;;; {Low Level Modules}
1445 ;;; These are the low level data structures for modules.
1447 ;;; Every module object is of the type 'module-type', which is a record
1448 ;;; consisting of the following members:
1450 ;;; - eval-closure: the function that defines for its module the strategy that
1451 ;;; shall be followed when looking up symbols in the module.
1453 ;;; An eval-closure is a function taking two arguments: the symbol to be
1454 ;;; looked up and a boolean value telling whether a binding for the symbol
1455 ;;; should be created if it does not exist yet. If the symbol lookup
1456 ;;; succeeded (either because an existing binding was found or because a new
1457 ;;; binding was created), a variable object representing the binding is
1458 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1459 ;;; closure does not take the module to be searched as an argument: During
1460 ;;; construction of the eval-closure, the eval-closure has to store the
1461 ;;; module it belongs to in its environment. This means, that any
1462 ;;; eval-closure can belong to only one module.
1464 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1465 ;;; special cases of eval-closures are to be distinguished: During startup
1466 ;;; the module system is not yet activated. In this phase, no modules are
1467 ;;; defined and all bindings are automatically stored by the system in the
1468 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1469 ;;; functions which require an eval-closure as their argument need to be
1470 ;;; passed the value #f.
1472 ;;; The other two special cases of eval-closures are the
1473 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1474 ;;; behave equally for the case that no new binding is to be created. The
1475 ;;; difference between the two comes in, when the boolean argument to the
1476 ;;; eval-closure indicates that a new binding shall be created if it is not
1479 ;;; Given that no new binding shall be created, both standard eval-closures
1480 ;;; define the following standard strategy of searching bindings in the
1481 ;;; module: First, the module's obarray is searched for the symbol. Second,
1482 ;;; if no binding for the symbol was found in the module's obarray, the
1483 ;;; module's binder procedure is exececuted. If this procedure did not
1484 ;;; return a binding for the symbol, the modules referenced in the module's
1485 ;;; uses list are recursively searched for a binding of the symbol. If the
1486 ;;; binding can not be found in these modules also, the symbol lookup has
1489 ;;; If a new binding shall be created, the standard-interface-eval-closure
1490 ;;; immediately returns indicating failure. That is, it does not even try
1491 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1492 ;;; first search the obarray, and if no binding was found there, would
1493 ;;; create a new binding in the obarray, therefore not calling the binder
1494 ;;; procedure or searching the modules in the uses list.
1496 ;;; The explanation of the following members obarray, binder and uses
1497 ;;; assumes that the symbol lookup follows the strategy that is defined in
1498 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1500 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1501 ;;; hash table, the definitions are found that are local to the module (that
1502 ;;; is, not imported from other modules). When looking up bindings in the
1503 ;;; module, this hash table is searched first.
1505 ;;; - binder: either #f or a function taking a module and a symbol argument.
1506 ;;; If it is a function it is called after the obarray has been
1507 ;;; unsuccessfully searched for a binding. It then can provide bindings
1508 ;;; that would otherwise not be found locally in the module.
1510 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1511 ;;; These modules are the third place queried for bindings after the obarray
1512 ;;; has been unsuccessfully searched and the binder function did not deliver
1513 ;;; a result either.
1515 ;;; - transformer: either #f or a function taking a scheme expression as
1516 ;;; delivered by read. If it is a function, it will be called to perform
1517 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1518 ;;; expression. The output of the transformer function will then be passed
1519 ;;; to Guile's internal memoizer. This means that the output must be valid
1520 ;;; scheme code. The only exception is, that the output may make use of the
1521 ;;; syntax extensions provided to identify the modules that a binding
1524 ;;; - name: the name of the module. This is used for all kinds of printing
1525 ;;; outputs. In certain places the module name also serves as a way of
1526 ;;; identification. When adding a module to the uses list of another
1527 ;;; module, it is made sure that the new uses list will not contain two
1528 ;;; modules of the same name.
1530 ;;; - kind: classification of the kind of module. The value is (currently?)
1531 ;;; only used for printing. It has no influence on how a module is treated.
1532 ;;; Currently the following values are used when setting the module kind:
1533 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1534 ;;; is set, it defaults to 'module.
1536 ;;; - duplicates-handlers: a list of procedures that get called to make a
1537 ;;; choice between two duplicate bindings when name clashes occur. See the
1538 ;;; `duplicate-handlers' global variable below.
1540 ;;; - observers: a list of procedures that get called when the module is
1543 ;;; - weak-observers: a weak-key hash table of procedures that get called
1544 ;;; when the module is modified. See `module-observe-weak' for details.
1546 ;;; In addition, the module may (must?) contain a binding for
1547 ;;; `%module-public-interface'. This variable should be bound to a module
1548 ;;; representing the exported interface of a module. See the
1549 ;;; `module-public-interface' and `module-export!' procedures.
1551 ;;; !!! warning: The interface to lazy binder procedures is going
1552 ;;; to be changed in an incompatible way to permit all the basic
1553 ;;; module ops to be virtualized.
1555 ;;; (make-module size use-list lazy-binding-proc) => module
1556 ;;; module-{obarray,uses,binder}[|-set!]
1557 ;;; (module? obj) => [#t|#f]
1558 ;;; (module-locally-bound? module symbol) => [#t|#f]
1559 ;;; (module-bound? module symbol) => [#t|#f]
1560 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1561 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1562 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1563 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1564 ;;; (module-symbol-binding module symbol opt-value)
1565 ;;; => [ <obj> | opt-value | an error occurs ]
1566 ;;; (module-make-local-var! module symbol) => #<variable...>
1567 ;;; (module-add! module symbol var) => unspecified
1568 ;;; (module-remove! module symbol) => unspecified
1569 ;;; (module-for-each proc module) => unspecified
1570 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1571 ;;; (set-current-module module) => unspecified
1572 ;;; (current-module) => #<module...>
1578 ;;; {Printing Modules}
1581 ;; This is how modules are printed. You can re-define it.
1582 (define (%print-module mod port)
1584 (display (or (module-kind mod) "module") port)
1586 (display (module-name mod) port)
1588 (display (number->string (object-address mod) 16) port)
1592 ;; Locally extend the syntax to allow record accessors to be defined at
1593 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1594 ;; the setters, in order to allow for redefinition of the record type; not
1595 ;; relevant in the case of modules, but perhaps if we make this public, it
1598 ((define-record-type
1600 (define (make-id scope . fragments)
1601 (datum->syntax #'scope
1602 (apply symbol-append
1604 (if (symbol? x) x (syntax->datum x)))
1607 (define (getter rtd type-name field slot)
1608 #`(define #,(make-id rtd type-name '- field)
1610 (lambda (#,type-name)
1611 (if (eq? (struct-vtable #,type-name) rtd)
1612 (struct-ref #,type-name #,slot)
1613 (%record-type-error rtd #,type-name))))))
1615 (define (setter rtd type-name field slot)
1616 #`(define #,(make-id rtd 'set- type-name '- field '!)
1618 (lambda (#,type-name val)
1619 (if (eq? (struct-vtable #,type-name) rtd)
1620 (struct-set! #,type-name #,slot val)
1621 (%record-type-error rtd #,type-name))))))
1623 (define (accessors rtd type-name fields n exp)
1624 (syntax-case fields ()
1626 (((field #:no-accessors) field* ...) (identifier? #'field)
1627 (accessors rtd type-name #'(field* ...) (1+ n)
1629 (((field #:no-setter) field* ...) (identifier? #'field)
1630 (accessors rtd type-name #'(field* ...) (1+ n)
1632 #,(getter rtd type-name #'field n))))
1633 (((field #:no-getter) field* ...) (identifier? #'field)
1634 (accessors rtd type-name #'(field* ...) (1+ n)
1636 #,(setter rtd type-name #'field n))))
1637 ((field field* ...) (identifier? #'field)
1638 (accessors rtd type-name #'(field* ...) (1+ n)
1640 #,(getter rtd type-name #'field n)
1641 #,(setter rtd type-name #'field n))))))
1643 (define (predicate rtd type-name fields exp)
1645 rtd type-name fields 0
1648 (define (#,(make-id rtd type-name '?) obj)
1649 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1651 (define (field-list fields)
1652 (syntax-case fields ()
1654 (((f . opts) . rest) (identifier? #'f)
1655 (cons #'f (field-list #'rest)))
1656 ((f . rest) (identifier? #'f)
1657 (cons #'f (field-list #'rest)))))
1659 (define (constructor rtd type-name fields exp)
1660 (let ((ctor (make-id rtd type-name '-constructor))
1661 (args (field-list fields)))
1662 (predicate rtd type-name fields
1667 (make-struct rtd 0 #,@args))))
1668 (struct-set! #,rtd (+ vtable-offset-user 2)
1671 (define (type type-name printer fields)
1672 (define (make-layout)
1673 (let lp ((fields fields) (slots '()))
1674 (syntax-case fields ()
1675 (() (datum->syntax #'here
1677 (apply string-append slots))))
1678 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1680 (let ((rtd (make-id type-name type-name '-type)))
1681 (constructor rtd type-name fields
1684 (make-struct record-type-vtable 0
1688 '#,(field-list fields)))
1689 (set-struct-vtable-name! #,rtd '#,type-name)))))
1692 ((_ type-name printer (field ...))
1693 (type #'type-name #'printer #'(field ...)))))))
1697 ;; A module is characterized by an obarray in which local symbols
1698 ;; are interned, a list of modules, "uses", from which non-local
1699 ;; bindings can be inherited, and an optional lazy-binder which
1700 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1701 ;; bindings that would otherwise not be found locally in the module.
1703 ;; NOTE: If you change the set of fields or their order, you also need to
1704 ;; change the constants in libguile/modules.h.
1706 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1707 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1708 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1709 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1711 (define-record-type module
1712 (lambda (obj port) (%print-module obj port))
1717 (transformer #:no-getter)
1721 (import-obarray #:no-setter)
1723 (weak-observers #:no-setter)
1731 ;; make-module &opt size uses binder
1733 ;; Create a new module, perhaps with a particular size of obarray,
1734 ;; initial uses list, or binding procedure.
1736 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
1737 (define %default-import-size
1738 ;; Typical number of imported bindings actually used by a module.
1741 (if (not (integer? size))
1742 (error "Illegal size to make-module." size))
1743 (if (not (and (list? uses)
1744 (and-map module? uses)))
1745 (error "Incorrect use list." uses))
1746 (if (and binder (not (procedure? binder)))
1748 "Lazy-binder expected to be a procedure or #f." binder))
1750 (let ((module (module-constructor (make-hash-table size)
1751 uses binder #f macroexpand
1753 (make-hash-table %default-import-size)
1755 (make-weak-key-hash-table 31) #f
1756 (make-hash-table 7) #f #f #f)))
1758 ;; We can't pass this as an argument to module-constructor,
1759 ;; because we need it to close over a pointer to the module
1761 (set-module-eval-closure! module (standard-eval-closure module))
1768 ;;; {Observer protocol}
1771 (define (module-observe module proc)
1772 (set-module-observers! module (cons proc (module-observers module)))
1775 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1776 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1777 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1778 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1779 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1782 ;; The two-argument version is kept for backward compatibility: when called
1783 ;; with two arguments, the observer gets unregistered when closure PROC
1784 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1785 (hashq-set! (module-weak-observers module) observer-id proc))
1787 (define (module-unobserve token)
1788 (let ((module (car token))
1791 (hash-remove! (module-weak-observers module) id)
1792 (set-module-observers! module (delq1! id (module-observers module)))))
1795 (define module-defer-observers #f)
1796 (define module-defer-observers-mutex (make-mutex 'recursive))
1797 (define module-defer-observers-table (make-hash-table))
1799 (define (module-modified m)
1800 (if module-defer-observers
1801 (hash-set! module-defer-observers-table m #t)
1802 (module-call-observers m)))
1804 ;;; This function can be used to delay calls to observers so that they
1805 ;;; can be called once only in the face of massive updating of modules.
1807 (define (call-with-deferred-observers thunk)
1810 (lock-mutex module-defer-observers-mutex)
1811 (set! module-defer-observers #t))
1814 (set! module-defer-observers #f)
1815 (hash-for-each (lambda (m dummy)
1816 (module-call-observers m))
1817 module-defer-observers-table)
1818 (hash-clear! module-defer-observers-table)
1819 (unlock-mutex module-defer-observers-mutex))))
1821 (define (module-call-observers m)
1822 (for-each (lambda (proc) (proc m)) (module-observers m))
1824 ;; We assume that weak observers don't (un)register themselves as they are
1825 ;; called since this would preclude proper iteration over the hash table
1827 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1831 ;;; {Module Searching in General}
1833 ;;; We sometimes want to look for properties of a symbol
1834 ;;; just within the obarray of one module. If the property
1835 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1836 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1839 ;;; Other times, we want to test for a symbol property in the obarray
1840 ;;; of M and, if it is not found there, try each of the modules in the
1841 ;;; uses list of M. This is the normal way of testing for some
1842 ;;; property, so we state these properties without qualification as
1843 ;;; in: ``The symbol 'fnord is interned in module M because it is
1844 ;;; interned locally in module M2 which is a member of the uses list
1848 ;; module-search fn m
1850 ;; return the first non-#f result of FN applied to M and then to
1851 ;; the modules in the uses of m, and so on recursively. If all applications
1852 ;; return #f, then so does this function.
1854 (define (module-search fn m v)
1857 (or (module-search fn (car pos) v)
1860 (loop (module-uses m))))
1863 ;;; {Is a symbol bound in a module?}
1865 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1866 ;;; of S in M has been set to some well-defined value.
1869 ;; module-locally-bound? module symbol
1871 ;; Is a symbol bound (interned and defined) locally in a given module?
1873 (define (module-locally-bound? m v)
1874 (let ((var (module-local-variable m v)))
1876 (variable-bound? var))))
1878 ;; module-bound? module symbol
1880 ;; Is a symbol bound (interned and defined) anywhere in a given module
1883 (define (module-bound? m v)
1884 (let ((var (module-variable m v)))
1886 (variable-bound? var))))
1888 ;;; {Is a symbol interned in a module?}
1890 ;;; Symbol S in Module M is interned if S occurs in
1891 ;;; of S in M has been set to some well-defined value.
1893 ;;; It is possible to intern a symbol in a module without providing
1894 ;;; an initial binding for the corresponding variable. This is done
1896 ;;; (module-add! module symbol (make-undefined-variable))
1898 ;;; In that case, the symbol is interned in the module, but not
1899 ;;; bound there. The unbound symbol shadows any binding for that
1900 ;;; symbol that might otherwise be inherited from a member of the uses list.
1903 (define (module-obarray-get-handle ob key)
1904 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1906 (define (module-obarray-ref ob key)
1907 ((if (symbol? key) hashq-ref hash-ref) ob key))
1909 (define (module-obarray-set! ob key val)
1910 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1912 (define (module-obarray-remove! ob key)
1913 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1915 ;; module-symbol-locally-interned? module symbol
1917 ;; is a symbol interned (not neccessarily defined) locally in a given module
1918 ;; or its uses? Interned symbols shadow inherited bindings even if
1919 ;; they are not themselves bound to a defined value.
1921 (define (module-symbol-locally-interned? m v)
1922 (not (not (module-obarray-get-handle (module-obarray m) v))))
1924 ;; module-symbol-interned? module symbol
1926 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1927 ;; or its uses? Interned symbols shadow inherited bindings even if
1928 ;; they are not themselves bound to a defined value.
1930 (define (module-symbol-interned? m v)
1931 (module-search module-symbol-locally-interned? m v))
1934 ;;; {Mapping modules x symbols --> variables}
1937 ;; module-local-variable module symbol
1938 ;; return the local variable associated with a MODULE and SYMBOL.
1940 ;;; This function is very important. It is the only function that can
1941 ;;; return a variable from a module other than the mutators that store
1942 ;;; new variables in modules. Therefore, this function is the location
1943 ;;; of the "lazy binder" hack.
1945 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1946 ;;; to a variable, return that variable object.
1948 ;;; If the symbols is not found at first, but the module has a lazy binder,
1949 ;;; then try the binder.
1951 ;;; If the symbol is not found at all, return #f.
1953 ;;; (This is now written in C, see `modules.c'.)
1956 ;;; {Mapping modules x symbols --> bindings}
1958 ;;; These are similar to the mapping to variables, except that the
1959 ;;; variable is dereferenced.
1962 ;; module-symbol-binding module symbol opt-value
1964 ;; return the binding of a variable specified by name within
1965 ;; a given module, signalling an error if the variable is unbound.
1966 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1967 ;; return OPT-VALUE.
1969 (define (module-symbol-local-binding m v . opt-val)
1970 (let ((var (module-local-variable m v)))
1971 (if (and var (variable-bound? var))
1973 (if (not (null? opt-val))
1975 (error "Locally unbound variable." v)))))
1977 ;; module-symbol-binding module symbol opt-value
1979 ;; return the binding of a variable specified by name within
1980 ;; a given module, signalling an error if the variable is unbound.
1981 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1982 ;; return OPT-VALUE.
1984 (define (module-symbol-binding m v . opt-val)
1985 (let ((var (module-variable m v)))
1986 (if (and var (variable-bound? var))
1988 (if (not (null? opt-val))
1990 (error "Unbound variable." v)))))
1995 ;;; {Adding Variables to Modules}
1998 ;; module-make-local-var! module symbol
2000 ;; ensure a variable for V in the local namespace of M.
2001 ;; If no variable was already there, then create a new and uninitialzied
2004 ;; This function is used in modules.c.
2006 (define (module-make-local-var! m v)
2007 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2010 ;; Mark as modified since this function is called when
2011 ;; the standard eval closure defines a binding
2015 ;; Create a new local variable.
2016 (let ((local-var (make-undefined-variable)))
2017 (module-add! m v local-var)
2020 ;; module-ensure-local-variable! module symbol
2022 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2023 ;; there is no binding for SYMBOL, create a new uninitialized
2024 ;; variable. Return the local variable.
2026 (define (module-ensure-local-variable! module symbol)
2027 (or (module-local-variable module symbol)
2028 (let ((var (make-undefined-variable)))
2029 (module-add! module symbol var)
2032 ;; module-add! module symbol var
2034 ;; ensure a particular variable for V in the local namespace of M.
2036 (define (module-add! m v var)
2037 (if (not (variable? var))
2038 (error "Bad variable to module-add!" var))
2039 (module-obarray-set! (module-obarray m) v var)
2040 (module-modified m))
2044 ;; make sure that a symbol is undefined in the local namespace of M.
2046 (define (module-remove! m v)
2047 (module-obarray-remove! (module-obarray m) v)
2048 (module-modified m))
2050 (define (module-clear! m)
2051 (hash-clear! (module-obarray m))
2052 (module-modified m))
2054 ;; MODULE-FOR-EACH -- exported
2056 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2058 (define (module-for-each proc module)
2059 (hash-for-each proc (module-obarray module)))
2061 (define (module-map proc module)
2062 (hash-map->list proc (module-obarray module)))
2066 ;; Modules exist in a separate namespace from values, because you generally do
2067 ;; not want the name of a submodule, which you might not even use, to collide
2068 ;; with local variables that happen to be named the same as the submodule.
2070 (define (module-ref-submodule module name)
2071 (or (hashq-ref (module-submodules module) name)
2072 (and (module-submodule-binder module)
2073 ((module-submodule-binder module) module name))))
2075 (define (module-define-submodule! module name submodule)
2076 (hashq-set! (module-submodules module) name submodule))
2078 ;; It used to be, however, that module names were also present in the
2079 ;; value namespace. When we enable deprecated code, we preserve this
2082 ;; These shims are defined here instead of in deprecated.scm because we
2083 ;; need their definitions before loading other modules.
2086 (define (module-ref-submodule module name)
2087 (or (hashq-ref (module-submodules module) name)
2088 (and (module-submodule-binder module)
2089 ((module-submodule-binder module) module name))
2090 (let ((var (module-local-variable module name)))
2091 (and var (variable-bound? var) (module? (variable-ref var))
2093 (warn "module" module "not in submodules table")
2094 (variable-ref var))))))
2096 (define (module-define-submodule! module name submodule)
2097 (let ((var (module-local-variable module name)))
2099 (or (not (variable-bound? var))
2100 (not (module? (variable-ref var)))))
2101 (warn "defining module" module ": not overriding local definition" var)
2102 (module-define! module name submodule)))
2103 (hashq-set! (module-submodules module) name submodule)))
2107 ;;; {Module-based Loading}
2110 (define (save-module-excursion thunk)
2111 (let ((inner-module (current-module))
2113 (dynamic-wind (lambda ()
2114 (set! outer-module (current-module))
2115 (set-current-module inner-module)
2116 (set! inner-module #f))
2119 (set! inner-module (current-module))
2120 (set-current-module outer-module)
2121 (set! outer-module #f)))))
2125 ;;; {MODULE-REF -- exported}
2128 ;; Returns the value of a variable called NAME in MODULE or any of its
2129 ;; used modules. If there is no such variable, then if the optional third
2130 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2132 (define (module-ref module name . rest)
2133 (let ((variable (module-variable module name)))
2134 (if (and variable (variable-bound? variable))
2135 (variable-ref variable)
2137 (error "No variable named" name 'in module)
2138 (car rest) ; default value
2141 ;; MODULE-SET! -- exported
2143 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2144 ;; to VALUE; if there is no such variable, an error is signaled.
2146 (define (module-set! module name value)
2147 (let ((variable (module-variable module name)))
2149 (variable-set! variable value)
2150 (error "No variable named" name 'in module))))
2152 ;; MODULE-DEFINE! -- exported
2154 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2155 ;; variable, it is added first.
2157 (define (module-define! module name value)
2158 (let ((variable (module-local-variable module name)))
2161 (variable-set! variable value)
2162 (module-modified module))
2163 (let ((variable (make-variable value)))
2164 (module-add! module name variable)))))
2166 ;; MODULE-DEFINED? -- exported
2168 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2171 (define (module-defined? module name)
2172 (let ((variable (module-variable module name)))
2173 (and variable (variable-bound? variable))))
2175 ;; MODULE-USE! module interface
2177 ;; Add INTERFACE to the list of interfaces used by MODULE.
2179 (define (module-use! module interface)
2180 (if (not (or (eq? module interface)
2181 (memq interface (module-uses module))))
2183 ;; Newly used modules must be appended rather than consed, so that
2184 ;; `module-variable' traverses the use list starting from the first
2186 (set-module-uses! module (append (module-uses module)
2188 (hash-clear! (module-import-obarray module))
2189 (module-modified module))))
2191 ;; MODULE-USE-INTERFACES! module interfaces
2193 ;; Same as MODULE-USE!, but only notifies module observers after all
2194 ;; interfaces are added to the inports list.
2196 (define (module-use-interfaces! module interfaces)
2197 (let* ((cur (module-uses module))
2198 (new (let lp ((in interfaces) (out '()))
2202 (let ((iface (car in)))
2203 (if (or (memq iface cur) (memq iface out))
2205 (cons iface out))))))))
2206 (set-module-uses! module (append cur new))
2207 (hash-clear! (module-import-obarray module))
2208 (module-modified module)))
2212 ;;; {Recursive Namespaces}
2214 ;;; A hierarchical namespace emerges if we consider some module to be
2215 ;;; root, and submodules of that module to be nested namespaces.
2217 ;;; The routines here manage variable names in hierarchical namespace.
2218 ;;; Each variable name is a list of elements, looked up in successively nested
2221 ;;; (nested-ref some-root-module '(foo bar baz))
2222 ;;; => <value of a variable named baz in the submodule bar of
2223 ;;; the submodule foo of some-root-module>
2228 ;;; ;; a-root is a module
2229 ;;; ;; name is a list of symbols
2231 ;;; nested-ref a-root name
2232 ;;; nested-set! a-root name val
2233 ;;; nested-define! a-root name val
2234 ;;; nested-remove! a-root name
2236 ;;; These functions manipulate values in namespaces. For referencing the
2237 ;;; namespaces themselves, use the following:
2239 ;;; nested-ref-module a-root name
2240 ;;; nested-define-module! a-root name mod
2242 ;;; (current-module) is a natural choice for a root so for convenience there are
2245 ;;; local-ref name == nested-ref (current-module) name
2246 ;;; local-set! name val == nested-set! (current-module) name val
2247 ;;; local-define name val == nested-define! (current-module) name val
2248 ;;; local-remove name == nested-remove! (current-module) name
2249 ;;; local-ref-module name == nested-ref-module (current-module) name
2250 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2254 (define (nested-ref root names)
2257 (let loop ((cur root)
2261 (module-ref cur head #f)
2262 (let ((cur (module-ref-submodule cur head)))
2264 (loop cur (car tail) (cdr tail))))))))
2266 (define (nested-set! root names val)
2267 (let loop ((cur root)
2271 (module-set! cur head val)
2272 (let ((cur (module-ref-submodule cur head)))
2274 (error "failed to resolve module" names)
2275 (loop cur (car tail) (cdr tail)))))))
2277 (define (nested-define! root names val)
2278 (let loop ((cur root)
2282 (module-define! cur head val)
2283 (let ((cur (module-ref-submodule cur head)))
2285 (error "failed to resolve module" names)
2286 (loop cur (car tail) (cdr tail)))))))
2288 (define (nested-remove! root names)
2289 (let loop ((cur root)
2293 (module-remove! cur head)
2294 (let ((cur (module-ref-submodule cur head)))
2296 (error "failed to resolve module" names)
2297 (loop cur (car tail) (cdr tail)))))))
2300 (define (nested-ref-module root names)
2301 (let loop ((cur root)
2305 (let ((cur (module-ref-submodule cur (car names))))
2307 (loop cur (cdr names)))))))
2309 (define (nested-define-module! root names module)
2311 (error "can't redefine root module" root module)
2312 (let loop ((cur root)
2316 (module-define-submodule! cur head module)
2317 (let ((cur (or (module-ref-submodule cur head)
2318 (let ((m (make-module 31)))
2319 (set-module-kind! m 'directory)
2320 (set-module-name! m (append (module-name cur)
2322 (module-define-submodule! cur head m)
2324 (loop cur (car tail) (cdr tail)))))))
2327 (define (local-ref names)
2328 (nested-ref (current-module) names))
2330 (define (local-set! names val)
2331 (nested-set! (current-module) names val))
2333 (define (local-define names val)
2334 (nested-define! (current-module) names val))
2336 (define (local-remove names)
2337 (nested-remove! (current-module) names))
2339 (define (local-ref-module names)
2340 (nested-ref-module (current-module) names))
2342 (define (local-define-module names mod)
2343 (nested-define-module! (current-module) names mod))
2349 ;;; {The (guile) module}
2351 ;;; The standard module, which has the core Guile bindings. Also called the
2352 ;;; "root module", as it is imported by many other modules, but it is not
2353 ;;; necessarily the root of anything; and indeed, the module named '() might be
2354 ;;; better thought of as a root.
2357 (define (set-system-module! m s)
2358 (set-procedure-property! (module-eval-closure m) 'system-module s))
2360 ;; The root module uses the pre-modules-obarray as its obarray. This
2361 ;; special obarray accumulates all bindings that have been established
2362 ;; before the module system is fully booted.
2364 ;; (The obarray continues to be used by code that has been closed over
2365 ;; before the module system has been booted.)
2367 (define the-root-module
2368 (let ((m (make-module 0)))
2369 (set-module-obarray! m (%get-pre-modules-obarray))
2370 (set-module-name! m '(guile))
2371 (set-system-module! m #t)
2374 ;; The root interface is a module that uses the same obarray as the
2375 ;; root module. It does not allow new definitions, tho.
2377 (define the-scm-module
2378 (let ((m (make-module 0)))
2379 (set-module-obarray! m (%get-pre-modules-obarray))
2380 (set-module-eval-closure! m (standard-interface-eval-closure m))
2381 (set-module-name! m '(guile))
2382 (set-module-kind! m 'interface)
2383 (set-system-module! m #t)
2385 ;; In Guile 1.8 and earlier M was its own public interface.
2386 (set-module-public-interface! m m)
2390 (set-module-public-interface! the-root-module the-scm-module)
2394 ;; Now that we have a root module, even though modules aren't fully booted,
2395 ;; expand the definition of resolve-module.
2397 (define (resolve-module name . args)
2398 (if (equal? name '(guile))
2400 (error "unexpected module to resolve during module boot" name)))
2402 ;; Cheat. These bindings are needed by modules.c, but we don't want
2403 ;; to move their real definition here because that would be unnatural.
2405 (define define-module* #f)
2406 (define process-use-modules #f)
2407 (define module-export! #f)
2408 (define default-duplicate-binding-procedures #f)
2410 ;; This boots the module system. All bindings needed by modules.c
2411 ;; must have been defined by now.
2413 (set-current-module the-root-module)
2418 ;; Now that modules are booted, give module-name its final definition.
2421 (let ((accessor (record-accessor module-type 'name)))
2424 (let ((name (list (gensym))))
2425 ;; Name MOD and bind it in the module root so that it's visible to
2426 ;; `resolve-module'. This is important as `psyntax' stores module
2427 ;; names and relies on being able to `resolve-module' them.
2428 (set-module-name! mod name)
2429 (nested-define-module! (resolve-module '() #f) name mod)
2432 (define (make-modules-in module name)
2433 (or (nested-ref-module module name)
2434 (let ((m (make-module 31)))
2435 (set-module-kind! m 'directory)
2436 (set-module-name! m (append (module-name module) name))
2437 (nested-define-module! module name m)
2440 (define (beautify-user-module! module)
2441 (let ((interface (module-public-interface module)))
2442 (if (or (not interface)
2443 (eq? interface module))
2444 (let ((interface (make-module 31)))
2445 (set-module-name! interface (module-name module))
2446 (set-module-version! interface (module-version module))
2447 (set-module-kind! interface 'interface)
2448 (set-module-public-interface! module interface))))
2449 (if (and (not (memq the-scm-module (module-uses module)))
2450 (not (eq? module the-root-module)))
2451 ;; Import the default set of bindings (from the SCM module) in MODULE.
2452 (module-use! module the-scm-module)))
2454 (define (version-matches? version-ref target)
2455 (define (sub-versions-match? v-refs t)
2456 (define (sub-version-matches? v-ref t)
2457 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2459 ((number? v-ref) (eqv? v-ref t))
2462 ((>=) (>= t (cadr v-ref)))
2463 ((<=) (<= t (cadr v-ref)))
2464 ((and) (and-map matches? (cdr v-ref)))
2465 ((or) (or-map matches? (cdr v-ref)))
2466 ((not) (not (matches? (cadr v-ref))))
2467 (else (error "Invalid sub-version reference" v-ref))))
2468 (else (error "Invalid sub-version reference" v-ref)))))
2470 (and (not (null? t))
2471 (sub-version-matches? (car v-refs) (car t))
2472 (sub-versions-match? (cdr v-refs) (cdr t)))))
2474 (let ((matches? (lambda (v) (version-matches? v target))))
2475 (or (null? version-ref)
2476 (case (car version-ref)
2477 ((and) (and-map matches? (cdr version-ref)))
2478 ((or) (or-map matches? (cdr version-ref)))
2479 ((not) (not (matches? (cadr version-ref))))
2480 (else (sub-versions-match? version-ref target))))))
2482 (define (make-fresh-user-module)
2483 (let ((m (make-module)))
2484 (beautify-user-module! m)
2487 ;; NOTE: This binding is used in libguile/modules.c.
2489 (define resolve-module
2490 (let ((root (make-module)))
2491 (set-module-name! root '())
2492 ;; Define the-root-module as '(guile).
2493 (module-define-submodule! root 'guile the-root-module)
2495 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2496 (let ((already (nested-ref-module root name)))
2499 (or (not autoload) (module-public-interface already)))
2500 ;; A hit, a palpable hit.
2502 (not (version-matches? version (module-version already))))
2503 (error "incompatible module version already loaded" name))
2506 ;; Try to autoload the module, and recurse.
2507 (try-load-module name version)
2508 (resolve-module name #f #:ensure ensure))
2510 ;; No module found (or if one was, it had no public interface), and
2511 ;; we're not autoloading. Make an empty module if #:ensure is true.
2514 (make-modules-in root name)))))))))
2517 (define (try-load-module name version)
2518 (try-module-autoload name version))
2520 (define (reload-module m)
2521 "Revisit the source file corresponding to the module @var{m}."
2522 (let ((f (module-filename m)))
2524 (save-module-excursion
2526 ;; Re-set the initial environment, as in try-module-autoload.
2527 (set-current-module (make-fresh-user-module))
2528 (primitive-load-path f)
2530 ;; Though we could guess, we *should* know it.
2531 (error "unknown file name for module" m))))
2533 (define (purify-module! module)
2534 "Removes bindings in MODULE which are inherited from the (guile) module."
2535 (let ((use-list (module-uses module)))
2536 (if (and (pair? use-list)
2537 (eq? (car (last-pair use-list)) the-scm-module))
2538 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2540 ;; Return a module that is an interface to the module designated by
2543 ;; `resolve-interface' takes four keyword arguments:
2545 ;; #:select SELECTION
2547 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2548 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2549 ;; is the name in the used module and SEEN is the name in the using
2550 ;; module. Note that SEEN is also passed through RENAMER, below. The
2551 ;; default is to select all bindings. If you specify no selection but
2552 ;; a renamer, only the bindings that already exist in the used module
2553 ;; are made available in the interface. Bindings that are added later
2554 ;; are not picked up.
2558 ;; BINDINGS is a list of bindings which should not be imported.
2562 ;; PREFIX is a symbol that will be appended to each exported name.
2563 ;; The default is to not perform any renaming.
2565 ;; #:renamer RENAMER
2567 ;; RENAMER is a procedure that takes a symbol and returns its new
2568 ;; name. The default is not perform any renaming.
2570 ;; Signal "no code for module" error if module name is not resolvable
2571 ;; or its public interface is not available. Signal "no binding"
2572 ;; error if selected binding does not exist in the used module.
2574 (define* (resolve-interface name #:key
2579 (symbol-prefix-proc prefix)
2582 (let* ((module (resolve-module name #t version #:ensure #f))
2583 (public-i (and module (module-public-interface module))))
2584 (and (or (not module) (not public-i))
2585 (error "no code for module" name))
2586 (if (and (not select) (null? hide) (eq? renamer identity))
2588 (let ((selection (or select (module-map (lambda (sym var) sym)
2590 (custom-i (make-module 31)))
2591 (set-module-kind! custom-i 'custom-interface)
2592 (set-module-name! custom-i name)
2593 ;; XXX - should use a lazy binder so that changes to the
2594 ;; used module are picked up automatically.
2595 (for-each (lambda (bspec)
2596 (let* ((direct? (symbol? bspec))
2597 (orig (if direct? bspec (car bspec)))
2598 (seen (if direct? bspec (cdr bspec)))
2599 (var (or (module-local-variable public-i orig)
2600 (module-local-variable module orig)
2602 ;; fixme: format manually for now
2604 #f "no binding `~A' in module ~A"
2606 (if (memq orig hide)
2607 (set! hide (delq! orig hide))
2608 (module-add! custom-i
2612 ;; Check that we are not hiding bindings which don't exist
2613 (for-each (lambda (binding)
2614 (if (not (module-local-variable public-i binding))
2617 #f "no binding `~A' to hide in module ~A"
2622 (define (symbol-prefix-proc prefix)
2624 (symbol-append prefix symbol)))
2626 ;; This function is called from "modules.c". If you change it, be
2627 ;; sure to update "modules.c" as well.
2629 (define* (define-module* name
2630 #:key filename pure version (duplicates '())
2631 (imports '()) (exports '()) (replacements '())
2632 (re-exports '()) (autoloads '()) transformer)
2633 (define (list-of pred l)
2635 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2636 (define (valid-export? x)
2637 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2638 (define (valid-autoload? x)
2639 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
2641 (define (resolve-imports imports)
2642 (define (resolve-import import-spec)
2643 (if (list? import-spec)
2644 (apply resolve-interface import-spec)
2645 (error "unexpected use-module specification" import-spec)))
2646 (let lp ((imports imports) (out '()))
2648 ((null? imports) (reverse! out))
2651 (cons (resolve-import (car imports)) out)))
2652 (else (error "unexpected tail of imports list" imports)))))
2654 ;; We could add a #:no-check arg, set by the define-module macro, if
2655 ;; these checks are taking too much time.
2657 (let ((module (resolve-module name #f)))
2658 (beautify-user-module! module)
2660 (set-module-filename! module filename))
2662 (purify-module! module))
2665 (if (not (list-of integer? version))
2666 (error "expected list of integers for version"))
2667 (set-module-version! module version)
2668 (set-module-version! (module-public-interface module) version)))
2669 (let ((imports (resolve-imports imports)))
2670 (call-with-deferred-observers
2673 (module-use-interfaces! module imports))
2674 (if (list-of valid-export? exports)
2676 (module-export! module exports))
2677 (error "expected exports to be a list of symbols or symbol pairs"))
2678 (if (list-of valid-export? replacements)
2679 (if (pair? replacements)
2680 (module-replace! module replacements))
2681 (error "expected replacements to be a list of symbols or symbol pairs"))
2682 (if (list-of valid-export? re-exports)
2683 (if (pair? re-exports)
2684 (module-re-export! module re-exports))
2685 (error "expected re-exports to be a list of symbols or symbol pairs"))
2687 (if (not (null? autoloads))
2688 (apply module-autoload! module autoloads))
2689 ;; Wait until modules have been loaded to resolve duplicates
2691 (if (pair? duplicates)
2692 (let ((handlers (lookup-duplicates-handlers duplicates)))
2693 (set-module-duplicates-handlers! module handlers))))))
2696 (if (and (pair? transformer) (list-of symbol? transformer))
2697 (let ((iface (resolve-interface transformer))
2698 (sym (car (last-pair transformer))))
2699 (set-module-transformer! module (module-ref iface sym)))
2700 (error "expected transformer to be a module name" transformer)))
2702 (run-hook module-defined-hook module)
2705 ;; `module-defined-hook' is a hook that is run whenever a new module
2706 ;; is defined. Its members are called with one argument, the new
2708 (define module-defined-hook (make-hook 1))
2715 (define (make-autoload-interface module name bindings)
2716 (let ((b (lambda (a sym definep)
2717 (and (memq sym bindings)
2718 (let ((i (module-public-interface (resolve-module name))))
2720 (error "missing interface for module" name))
2721 (let ((autoload (memq a (module-uses module))))
2722 ;; Replace autoload-interface with actual interface if
2723 ;; that has not happened yet.
2724 (if (pair? autoload)
2725 (set-car! autoload i)))
2726 (module-local-variable i sym))))))
2727 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2728 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2729 (make-hash-table 0) #f #f #f)))
2731 (define (module-autoload! module . args)
2732 "Have @var{module} automatically load the module named @var{name} when one
2733 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2734 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2735 module '(ice-9 q) '(make-q q-length))}."
2736 (let loop ((args args))
2740 (error "invalid name+binding autoload list" args))
2742 (let ((name (car args))
2743 (bindings (cadr args)))
2744 (module-use! module (make-autoload-interface module
2746 (loop (cddr args)))))))
2751 ;;; {Autoloading modules}
2754 (define autoloads-in-progress '())
2756 ;; This function is called from "modules.c". If you change it, be
2757 ;; sure to update "modules.c" as well.
2759 (define* (try-module-autoload module-name #:optional version)
2760 (let* ((reverse-name (reverse module-name))
2761 (name (symbol->string (car reverse-name)))
2762 (dir-hint-module-name (reverse (cdr reverse-name)))
2763 (dir-hint (apply string-append
2765 (string-append (symbol->string elt) "/"))
2766 dir-hint-module-name))))
2767 (resolve-module dir-hint-module-name #f)
2768 (and (not (autoload-done-or-in-progress? dir-hint name))
2771 (lambda () (autoload-in-progress! dir-hint name))
2773 (with-fluids ((current-reader #f))
2774 (save-module-excursion
2776 ;; The initial environment when loading a module is a fresh
2778 (set-current-module (make-fresh-user-module))
2779 ;; Here we could allow some other search strategy (other than
2780 ;; primitive-load-path), for example using versions encoded
2781 ;; into the file system -- but then we would have to figure
2782 ;; out how to locate the compiled file, do auto-compilation,
2783 ;; etc. Punt for now, and don't use versions when locating
2785 (primitive-load-path (in-vicinity dir-hint name) #f)
2787 (lambda () (set-autoloaded! dir-hint name didit)))
2792 ;;; {Dynamic linking of modules}
2795 (define autoloads-done '((guile . guile)))
2797 (define (autoload-done-or-in-progress? p m)
2798 (let ((n (cons p m)))
2799 (->bool (or (member n autoloads-done)
2800 (member n autoloads-in-progress)))))
2802 (define (autoload-done! p m)
2803 (let ((n (cons p m)))
2804 (set! autoloads-in-progress
2805 (delete! n autoloads-in-progress))
2806 (or (member n autoloads-done)
2807 (set! autoloads-done (cons n autoloads-done)))))
2809 (define (autoload-in-progress! p m)
2810 (let ((n (cons p m)))
2811 (set! autoloads-done
2812 (delete! n autoloads-done))
2813 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2815 (define (set-autoloaded! p m done?)
2817 (autoload-done! p m)
2818 (let ((n (cons p m)))
2819 (set! autoloads-done (delete! n autoloads-done))
2820 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2824 ;;; {Run-time options}
2827 (define-syntax define-option-interface
2829 ((_ (interface (options enable disable) (option-set!)))
2836 (begin (interface arg) (interface))
2839 (apply (lambda (name value documentation)
2841 (if (< (string-length (symbol->string name)) 8)
2846 (display documentation)
2850 (define (enable . flags)
2851 (interface (append flags (interface)))
2853 (define (disable . flags)
2854 (let ((options (interface)))
2855 (for-each (lambda (flag) (set! options (delq! flag options)))
2859 (define-syntax-rule (option-set! opt val)
2860 (eval-when (eval load compile expand)
2861 (options (append (options) (list 'opt val)))))))))
2863 (define-option-interface
2864 (debug-options-interface
2865 (debug-options debug-enable debug-disable)
2868 (define-option-interface
2869 (read-options-interface
2870 (read-options read-enable read-disable)
2873 (define-option-interface
2874 (print-options-interface
2875 (print-options print-enable print-disable)
2880 ;;; {The Unspecified Value}
2882 ;;; Currently Guile represents unspecified values via one particular value,
2883 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2884 ;;; future if we could replace this with a return of 0 values, though.
2887 (define-syntax *unspecified*
2888 (identifier-syntax (if #f #f)))
2890 (define (unspecified? v) (eq? v *unspecified*))
2899 ;; Three fields: the procedure itself, the fluid, and the converter.
2900 (make-struct <applicable-struct-vtable> 0 'pwprpr))
2901 (set-struct-vtable-name! <parameter> '<parameter>)
2903 (define* (make-parameter init #:optional (conv (lambda (x) x)))
2904 (let ((fluid (make-fluid (conv init))))
2905 (make-struct <parameter> 0
2907 (() (fluid-ref fluid))
2908 ((x) (let ((prev (fluid-ref fluid)))
2909 (fluid-set! fluid (conv x))
2913 (define (parameter? x)
2914 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
2916 (define (parameter-fluid p)
2919 (scm-error 'wrong-type-arg "parameter-fluid"
2920 "Not a parameter: ~S" (list p) #f)))
2922 (define (parameter-converter p)
2925 (scm-error 'wrong-type-arg "parameter-fluid"
2926 "Not a parameter: ~S" (list p) #f)))
2928 (define-syntax parameterize
2931 ((_ ((param value) ...) body body* ...)
2932 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
2933 #'(let ((p param) ...)
2934 (if (not (parameter? p))
2935 (scm-error 'wrong-type-arg "parameterize"
2936 "Not a parameter: ~S" (list p) #f))
2938 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
2940 body body* ...)))))))
2944 ;;; Current ports as parameters.
2947 (let ((fluid->parameter
2948 (lambda (fluid conv)
2949 (make-struct <parameter> 0
2951 (() (fluid-ref fluid))
2952 ((x) (let ((prev (fluid-ref fluid)))
2953 (fluid-set! fluid (conv x))
2956 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
2958 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
2962 (module-remove! (current-module) 'fluid)))
2964 (port-parameterize! current-input-port %current-input-port-fluid
2965 input-port? "expected an input port")
2966 (port-parameterize! current-output-port %current-output-port-fluid
2967 output-port? "expected an output port")
2968 (port-parameterize! current-error-port %current-error-port-fluid
2969 output-port? "expected an output port"))
2977 (define current-warning-port
2978 (make-parameter (current-error-port)
2980 (if (output-port? x)
2982 (error "expected an output port" x)))))
2990 (define *repl-stack* (make-fluid '()))
2992 ;; Programs can call `batch-mode?' to see if they are running as part of a
2993 ;; script or if they are running interactively. REPL implementations ensure that
2994 ;; `batch-mode?' returns #f during their extent.
2996 (define (batch-mode?)
2997 (null? (fluid-ref *repl-stack*)))
2999 ;; Programs can re-enter batch mode, for example after a fork, by calling
3000 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3001 ;; to abort to the outermost prompt, and call a thunk there.
3003 (define (ensure-batch-mode!)
3004 (set! batch-mode? (lambda () #t)))
3006 (define (quit . args)
3007 (apply throw 'quit args))
3011 (define (gc-run-time)
3012 (cdr (assq 'gc-time-taken (gc-stats))))
3014 (define abort-hook (make-hook))
3015 (define before-error-hook (make-hook))
3016 (define after-error-hook (make-hook))
3017 (define before-backtrace-hook (make-hook))
3018 (define after-backtrace-hook (make-hook))
3020 (define before-read-hook (make-hook))
3021 (define after-read-hook (make-hook))
3022 (define before-eval-hook (make-hook 1))
3023 (define after-eval-hook (make-hook 1))
3024 (define before-print-hook (make-hook 1))
3025 (define after-print-hook (make-hook 1))
3027 ;;; This hook is run at the very end of an interactive session.
3029 (define exit-hook (make-hook))
3031 ;;; The default repl-reader function. We may override this if we've
3032 ;;; the readline library.
3034 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3035 (if (not (char-ready?))
3037 (display (if (string? prompt) prompt (prompt)))
3038 ;; An interesting situation. The printer resets the column to
3039 ;; 0 by printing a newline, but we then advance it by printing
3040 ;; the prompt. However the port-column of the output port
3041 ;; does not typically correspond with the actual column on the
3042 ;; screen, because the input is echoed back! Since the
3043 ;; input is line-buffered and thus ends with a newline, the
3044 ;; output will really start on column zero. So, here we zero
3045 ;; it out. See bug 9664.
3047 ;; Note that for similar reasons, the output-line will not
3048 ;; reflect the actual line on the screen. But given the
3049 ;; possibility of multiline input, the fix is not as
3050 ;; straightforward, so we don't bother.
3052 ;; Also note that the readline implementation papers over
3053 ;; these concerns, because it's readline itself printing the
3054 ;; prompt, and not Guile.
3055 (set-port-column! (current-output-port) 0)))
3057 (run-hook before-read-hook)
3058 ((or reader read) (current-input-port))))
3063 ;;; {IOTA functions: generating lists of numbers}
3067 (let loop ((count (1- n)) (result '()))
3068 (if (< count 0) result
3069 (loop (1- count) (cons count result)))))
3075 ;;; with `continue' and `break'.
3078 ;; The inliner will remove the prompts at compile-time if it finds that
3079 ;; `continue' or `break' are not used.
3081 (define-syntax while
3084 ((while cond body ...)
3085 #`(let ((break-tag (make-prompt-tag "break"))
3086 (continue-tag (make-prompt-tag "continue")))
3090 (define-syntax #,(datum->syntax #'while 'break)
3094 #'(abort-to-prompt break-tag arg (... ...)))
3097 (apply abort-to-prompt break-tag args))))))
3102 (define-syntax #,(datum->syntax #'while 'continue)
3106 #'(abort-to-prompt continue-tag))
3108 (syntax-violation 'continue "too many arguments" x))
3111 (abort-to-prompt continue-tag))))))
3112 (do () ((not cond) #f) body ...))
3113 (lambda (k) (lp)))))
3117 (apply values args)))))))))
3122 ;;; {Module System Macros}
3125 ;; Return a list of expressions that evaluate to the appropriate
3126 ;; arguments for resolve-interface according to SPEC.
3128 (eval-when (compile)
3129 (if (memq 'prefix (read-options))
3130 (error "boot-9 must be compiled with #:kw, not :kw")))
3132 (define (keyword-like-symbol->keyword sym)
3133 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3135 (define-syntax define-module
3137 (define (keyword-like? stx)
3138 (let ((dat (syntax->datum stx)))
3140 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3141 (define (->keyword sym)
3142 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3144 (define (parse-iface args)
3145 (let loop ((in args) (out '()))
3148 ;; The user wanted #:foo, but wrote :foo. Fix it.
3149 ((sym . in) (keyword-like? #'sym)
3150 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3151 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3152 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3153 ((#:renamer renamer . in)
3154 (loop #'in (cons* #',renamer #:renamer out)))
3156 (loop #'in (cons* #'val #'kw out))))))
3158 (define (parse args imp exp rex rep aut)
3159 ;; Just quote everything except #:use-module and #:use-syntax. We
3160 ;; need to know about all arguments regardless since we want to turn
3161 ;; symbols that look like keywords into real keywords, and the
3162 ;; keyword args in a define-module form are not regular
3163 ;; (i.e. no-backtrace doesn't take a value).
3164 (syntax-case args ()
3166 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3167 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3168 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3169 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3170 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3171 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3172 ;; The user wanted #:foo, but wrote :foo. Fix it.
3173 ((sym . args) (keyword-like? #'sym)
3174 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3175 imp exp rex rep aut))
3176 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3177 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3178 ((#:no-backtrace . args)
3180 (parse #'args imp exp rex rep aut))
3182 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3184 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3185 ((#:version (v ...) . args)
3186 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3187 ((#:duplicates (d ...) . args)
3188 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3189 ((#:filename f . args)
3190 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3191 ((#:use-module (name name* ...) . args)
3192 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3193 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3194 ((#:use-syntax (name name* ...) . args)
3195 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3196 #`(#:transformer '(name name* ...)
3197 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3198 ((#:use-module ((name name* ...) arg ...) . args)
3199 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3201 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3203 ((#:export (ex ...) . args)
3204 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3205 ((#:export-syntax (ex ...) . args)
3206 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3207 ((#:re-export (re ...) . args)
3208 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3209 ((#:re-export-syntax (re ...) . args)
3210 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3211 ((#:replace (r ...) . args)
3212 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3213 ((#:replace-syntax (r ...) . args)
3214 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3215 ((#:autoload name bindings . args)
3216 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3218 (syntax-violation 'define-module "unknown keyword or bad argument"
3222 ((_ (name name* ...) arg ...)
3223 (and-map symbol? (syntax->datum #'(name name* ...)))
3224 (with-syntax (((quoted-arg ...)
3225 (parse #'(arg ...) '() '() '() '() '()))
3226 ;; Ideally the filename is either a string or #f;
3227 ;; this hack is to work around a case in which
3228 ;; port-filename returns a symbol (`socket') for
3230 (filename (let ((f (assq-ref (or (syntax-source x) '())
3232 (and (string? f) f))))
3233 #'(eval-when (eval load compile expand)
3234 (let ((m (define-module* '(name name* ...)
3235 #:filename filename quoted-arg ...)))
3236 (set-current-module m)
3239 ;; The guts of the use-modules macro. Add the interfaces of the named
3240 ;; modules to the use-list of the current module, in order.
3242 ;; This function is called by "modules.c". If you change it, be sure
3243 ;; to change scm_c_use_module as well.
3245 (define (process-use-modules module-interface-args)
3246 (let ((interfaces (map (lambda (mif-args)
3247 (or (apply resolve-interface mif-args)
3248 (error "no such module" mif-args)))
3249 module-interface-args)))
3250 (call-with-deferred-observers
3252 (module-use-interfaces! (current-module) interfaces)))))
3254 (define-syntax use-modules
3256 (define (keyword-like? stx)
3257 (let ((dat (syntax->datum stx)))
3259 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3260 (define (->keyword sym)
3261 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3263 (define (quotify-iface args)
3264 (let loop ((in args) (out '()))
3267 ;; The user wanted #:foo, but wrote :foo. Fix it.
3268 ((sym . in) (keyword-like? #'sym)
3269 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3270 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3271 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3272 ((#:renamer renamer . in)
3273 (loop #'in (cons* #'renamer #:renamer out)))
3275 (loop #'in (cons* #''val #'kw out))))))
3277 (define (quotify specs)
3278 (let lp ((in specs) (out '()))
3281 (((name name* ...) . in)
3282 (and-map symbol? (syntax->datum #'(name name* ...)))
3283 (lp #'in (cons #''((name name* ...)) out)))
3284 ((((name name* ...) arg ...) . in)
3285 (and-map symbol? (syntax->datum #'(name name* ...)))
3286 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3287 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3292 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3293 #'(eval-when (eval load compile expand)
3294 (process-use-modules (list quoted-args ...))
3297 (define-syntax-rule (use-syntax spec ...)
3299 (eval-when (eval load compile expand)
3300 (issue-deprecation-warning
3301 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3302 (use-modules spec ...)))
3304 (include-from-path "ice-9/r6rs-libraries")
3306 (define-syntax-rule (define-private foo bar)
3309 (define-syntax define-public
3311 ((_ (name . args) . body)
3312 (define-public name (lambda args . body)))
3318 (define-syntax-rule (defmacro-public name args body ...)
3320 (defmacro name args body ...)
3321 (export-syntax name)))
3323 ;; And now for the most important macro.
3324 (define-syntax-rule (λ formals body ...)
3325 (lambda formals body ...))
3328 ;; Export a local variable
3330 ;; This function is called from "modules.c". If you change it, be
3331 ;; sure to update "modules.c" as well.
3333 (define (module-export! m names)
3334 (let ((public-i (module-public-interface m)))
3335 (for-each (lambda (name)
3336 (let* ((internal-name (if (pair? name) (car name) name))
3337 (external-name (if (pair? name) (cdr name) name))
3338 (var (module-ensure-local-variable! m internal-name)))
3339 (module-add! public-i external-name var)))
3342 (define (module-replace! m names)
3343 (let ((public-i (module-public-interface m)))
3344 (for-each (lambda (name)
3345 (let* ((internal-name (if (pair? name) (car name) name))
3346 (external-name (if (pair? name) (cdr name) name))
3347 (var (module-ensure-local-variable! m internal-name)))
3348 ;; FIXME: use a bit on variables instead of object
3350 (set-object-property! var 'replace #t)
3351 (module-add! public-i external-name var)))
3354 ;; Export all local variables from a module
3356 (define (module-export-all! mod)
3357 (define (fresh-interface!)
3358 (let ((iface (make-module)))
3359 (set-module-name! iface (module-name mod))
3360 (set-module-version! iface (module-version mod))
3361 (set-module-kind! iface 'interface)
3362 (set-module-public-interface! mod iface)
3364 (let ((iface (or (module-public-interface mod)
3365 (fresh-interface!))))
3366 (set-module-obarray! iface (module-obarray mod))))
3368 ;; Re-export a imported variable
3370 (define (module-re-export! m names)
3371 (let ((public-i (module-public-interface m)))
3372 (for-each (lambda (name)
3373 (let* ((internal-name (if (pair? name) (car name) name))
3374 (external-name (if (pair? name) (cdr name) name))
3375 (var (module-variable m internal-name)))
3377 (error "Undefined variable:" internal-name))
3378 ((eq? var (module-local-variable m internal-name))
3379 (error "re-exporting local variable:" internal-name))
3381 (module-add! public-i external-name var)))))
3384 (define-syntax-rule (export name ...)
3385 (eval-when (eval load compile expand)
3386 (call-with-deferred-observers
3388 (module-export! (current-module) '(name ...))))))
3390 (define-syntax-rule (re-export name ...)
3391 (eval-when (eval load compile expand)
3392 (call-with-deferred-observers
3394 (module-re-export! (current-module) '(name ...))))))
3396 (define-syntax-rule (export! name ...)
3397 (eval-when (eval load compile expand)
3398 (call-with-deferred-observers
3400 (module-replace! (current-module) '(name ...))))))
3402 (define-syntax-rule (export-syntax name ...)
3405 (define-syntax-rule (re-export-syntax name ...)
3406 (re-export name ...))
3413 (define* (make-mutable-parameter init #:optional (converter identity))
3414 (let ((fluid (make-fluid (converter init))))
3416 (() (fluid-ref fluid))
3417 ((val) (fluid-set! fluid (converter val))))))
3422 ;;; {Handling of duplicate imported bindings}
3425 ;; Duplicate handlers take the following arguments:
3427 ;; module importing module
3428 ;; name conflicting name
3429 ;; int1 old interface where name occurs
3430 ;; val1 value of binding in old interface
3431 ;; int2 new interface where name occurs
3432 ;; val2 value of binding in new interface
3433 ;; var previous resolution or #f
3434 ;; val value of previous resolution
3436 ;; A duplicate handler can take three alternative actions:
3438 ;; 1. return #f => leave responsibility to next handler
3439 ;; 2. exit with an error
3440 ;; 3. return a variable resolving the conflict
3443 (define duplicate-handlers
3444 (let ((m (make-module 7)))
3446 (define (check module name int1 val1 int2 val2 var val)
3447 (scm-error 'misc-error
3449 "~A: `~A' imported from both ~A and ~A"
3450 (list (module-name module)
3456 (define (warn module name int1 val1 int2 val2 var val)
3457 (format (current-warning-port)
3458 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3459 (module-name module)
3465 (define (replace module name int1 val1 int2 val2 var val)
3466 (let ((old (or (and var (object-property var 'replace) var)
3467 (module-variable int1 name)))
3468 (new (module-variable int2 name)))
3469 (if (object-property old 'replace)
3470 (and (or (eq? old new)
3471 (not (object-property new 'replace)))
3473 (and (object-property new 'replace)
3476 (define (warn-override-core module name int1 val1 int2 val2 var val)
3477 (and (eq? int1 the-scm-module)
3479 (format (current-warning-port)
3480 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3481 (module-name module)
3484 (module-local-variable int2 name))))
3486 (define (first module name int1 val1 int2 val2 var val)
3487 (or var (module-local-variable int1 name)))
3489 (define (last module name int1 val1 int2 val2 var val)
3490 (module-local-variable int2 name))
3492 (define (noop module name int1 val1 int2 val2 var val)
3495 (set-module-name! m 'duplicate-handlers)
3496 (set-module-kind! m 'interface)
3497 (module-define! m 'check check)
3498 (module-define! m 'warn warn)
3499 (module-define! m 'replace replace)
3500 (module-define! m 'warn-override-core warn-override-core)
3501 (module-define! m 'first first)
3502 (module-define! m 'last last)
3503 (module-define! m 'merge-generics noop)
3504 (module-define! m 'merge-accessors noop)
3507 (define (lookup-duplicates-handlers handler-names)
3509 (map (lambda (handler-name)
3510 (or (module-symbol-local-binding
3511 duplicate-handlers handler-name #f)
3512 (error "invalid duplicate handler name:"
3514 (if (list? handler-names)
3516 (list handler-names)))))
3518 (define default-duplicate-binding-procedures
3519 (make-mutable-parameter #f))
3521 (define default-duplicate-binding-handler
3522 (make-mutable-parameter '(replace warn-override-core warn last)
3523 (lambda (handler-names)
3524 (default-duplicate-binding-procedures
3525 (lookup-duplicates-handlers handler-names))
3532 ;;; Load is tricky when combined with relative paths, compilation, and
3533 ;;; the file system. If a path is relative, what is it relative to? The
3534 ;;; path of the source file at the time it was compiled? The path of
3535 ;;; the compiled file? What if both or either were installed? And how
3536 ;;; do you get that information? Tricky, I say.
3538 ;;; To get around all of this, we're going to do something nasty, and
3539 ;;; turn `load' into a macro. That way it can know the path of the
3540 ;;; source file with respect to which it was invoked, so it can resolve
3541 ;;; relative paths with respect to the original source path.
3543 ;;; There is an exception, and that is that if the source file was in
3544 ;;; the load path when it was compiled, instead of looking up against
3545 ;;; the absolute source location, we load-from-path against the relative
3546 ;;; source location.
3549 (define %auto-compilation-options
3550 ;; Default `compile-file' option when auto-compiling.
3551 '(#:warnings (unbound-variable arity-mismatch format)))
3553 (define* (load-in-vicinity dir path #:optional reader)
3554 (define (canonical->suffix canon)
3556 ((string-prefix? "/" canon) canon)
3557 ((and (> (string-length canon) 2)
3558 (eqv? (string-ref canon 1) #\:))
3559 ;; Paths like C:... transform to /C...
3560 (string-append "/" (substring canon 0 1) (substring canon 2)))
3563 ;; Returns the .go file corresponding to `name'. Does not search load
3564 ;; paths, only the fallback path. If the .go file is missing or out of
3565 ;; date, and auto-compilation is enabled, will try auto-compilation, just
3566 ;; as primitive-load-path does internally. primitive-load is
3567 ;; unaffected. Returns #f if auto-compilation failed or was disabled.
3569 ;; NB: Unless we need to compile the file, this function should not cause
3570 ;; (system base compile) to be loaded up. For that reason compiled-file-name
3571 ;; partially duplicates functionality from (system base compile).
3573 (define (compiled-file-name canon-path)
3574 ;; FIXME: would probably be better just to append SHA1(canon-path)
3575 ;; to the %compile-fallback-path, to avoid deep directory stats.
3576 (and %compile-fallback-path
3578 %compile-fallback-path
3579 (canonical->suffix canon-path)
3580 (cond ((or (null? %load-compiled-extensions)
3581 (string-null? (car %load-compiled-extensions)))
3582 (warn "invalid %load-compiled-extensions"
3583 %load-compiled-extensions)
3585 (else (car %load-compiled-extensions))))))
3587 (define (fresh-compiled-file-name name go-path)
3590 (let* ((scmstat (stat name))
3591 (gostat (and (not %fresh-auto-compile)
3592 (stat go-path #f))))
3594 (or (> (stat:mtime gostat) (stat:mtime scmstat))
3595 (and (= (stat:mtime gostat) (stat:mtime scmstat))
3596 (>= (stat:mtimensec gostat)
3597 (stat:mtimensec scmstat)))))
3601 (format (current-warning-port)
3602 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
3605 (%load-should-auto-compile
3606 (%warn-auto-compilation-enabled)
3607 (format (current-warning-port) ";;; compiling ~a\n" name)
3610 (resolve-interface '(system base compile))
3613 #:opts %auto-compilation-options
3614 #:env (current-module))))
3615 (format (current-warning-port) ";;; compiled ~a\n" cfn)
3619 (format (current-warning-port)
3620 ";;; WARNING: compilation of ~a failed:\n" name)
3621 (for-each (lambda (s)
3622 (if (not (string-null? s))
3623 (format (current-warning-port) ";;; ~a\n" s)))
3625 (call-with-output-string
3626 (lambda (port) (print-exception port #f k args)))
3630 (define (absolute-path? path)
3631 (string-prefix? "/" path))
3633 (define (load-absolute abs-path)
3634 (let ((cfn (let ((canon (false-if-exception (canonicalize-path abs-path))))
3636 (let ((go-path (compiled-file-name canon)))
3638 (fresh-compiled-file-name abs-path go-path)))))))
3642 (%load-hook abs-path))
3643 (load-compiled cfn))
3644 (start-stack 'load-stack
3645 (primitive-load abs-path)))))
3647 (save-module-excursion
3649 (with-fluids ((current-reader reader)
3650 (%file-port-name-canonicalization 'relative))
3652 ((or (absolute-path? path))
3653 (load-absolute path))
3654 ((absolute-path? dir)
3655 (load-absolute (in-vicinity dir path)))
3657 (load-from-path (in-vicinity dir path))))))))
3660 (make-variable-transformer
3662 (let* ((src (syntax-source x))
3663 (file (and src (assq-ref src 'filename)))
3664 (dir (and (string? file) (dirname file))))
3667 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
3671 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
3675 ;;; {`cond-expand' for SRFI-0 support.}
3677 ;;; This syntactic form expands into different commands or
3678 ;;; definitions, depending on the features provided by the Scheme
3684 ;;; --> (cond-expand <cond-expand-clause>+)
3685 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3686 ;;; <cond-expand-clause>
3687 ;;; --> (<feature-requirement> <command-or-definition>*)
3688 ;;; <feature-requirement>
3689 ;;; --> <feature-identifier>
3690 ;;; | (and <feature-requirement>*)
3691 ;;; | (or <feature-requirement>*)
3692 ;;; | (not <feature-requirement>)
3693 ;;; <feature-identifier>
3694 ;;; --> <a symbol which is the name or alias of a SRFI>
3696 ;;; Additionally, this implementation provides the
3697 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3698 ;;; determine the implementation type and the supported standard.
3700 ;;; Currently, the following feature identifiers are supported:
3702 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3704 ;;; Remember to update the features list when adding more SRFIs.
3707 (define %cond-expand-features
3708 ;; Adjust the above comment when changing this.
3712 srfi-0 ;; cond-expand itself
3713 srfi-4 ;; homogenous numeric vectors
3714 srfi-6 ;; open-input-string etc, in the guile core
3715 srfi-13 ;; string library
3716 srfi-14 ;; character sets
3717 srfi-23 ;; `error` procedure
3718 srfi-39 ;; parameterize
3719 srfi-55 ;; require-extension
3720 srfi-61 ;; general cond clause
3723 ;; This table maps module public interfaces to the list of features.
3725 (define %cond-expand-table (make-hash-table 31))
3727 ;; Add one or more features to the `cond-expand' feature list of the
3730 (define (cond-expand-provide module features)
3731 (let ((mod (module-public-interface module)))
3733 (hashq-set! %cond-expand-table mod
3734 (append (hashq-ref %cond-expand-table mod '())
3737 (define-syntax cond-expand
3739 (define (module-has-feature? mod sym)
3740 (or-map (lambda (mod)
3741 (memq sym (hashq-ref %cond-expand-table mod '())))
3744 (define (condition-matches? condition)
3745 (syntax-case condition (and or not)
3747 (and-map condition-matches? #'(c ...)))
3749 (or-map condition-matches? #'(c ...)))
3751 (if (condition-matches? #'c) #f #t))
3754 (let ((sym (syntax->datum #'c)))
3755 (if (memq sym %cond-expand-features)
3757 (module-has-feature? (current-module) sym))))))
3759 (define (match clauses alternate)
3760 (syntax-case clauses ()
3761 (((condition form ...) . rest)
3762 (if (condition-matches? #'condition)
3764 (match #'rest alternate)))
3767 (syntax-case x (else)
3768 ((_ clause ... (else form ...))
3769 (match #'(clause ...)
3771 #'(begin form ...))))
3773 (match #'(clause ...)
3775 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
3777 ;; This procedure gets called from the startup code with a list of
3778 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3780 (define (use-srfis srfis)
3781 (process-use-modules
3783 (list (list 'srfi (string->symbol
3784 (string-append "srfi-" (number->string num))))))
3789 ;;; srfi-55: require-extension
3792 (define-syntax require-extension
3794 (syntax-case x (srfi)
3796 (and-map integer? (syntax->datum #'(n ...)))
3800 (datum->syntax x (symbol-append 'srfi- n)))
3802 (map number->string (syntax->datum #'(n ...)))))))
3803 #'(use-modules (srfi srfi-n) ...)))
3805 (identifier? #'type)
3806 (syntax-violation 'require-extension "Not a recognized extension type"
3810 ;;; Defining transparently inlinable procedures
3813 (define-syntax define-inlinable
3814 ;; Define a macro and a procedure such that direct calls are inlined, via
3815 ;; the macro expansion, whereas references in non-call contexts refer to
3816 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
3818 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
3820 (define prefix (string->symbol "% "))
3821 (define (make-procedure-name name)
3823 (symbol-append prefix (syntax->datum name)
3827 ((_ (name formals ...) body ...)
3828 (identifier? #'name)
3829 (with-syntax ((proc-name (make-procedure-name #'name))
3830 ((args ...) (generate-temporaries #'(formals ...))))
3832 (define (proc-name formals ...)
3833 (syntax-parameterize ((name (identifier-syntax proc-name)))
3835 (define-syntax-parameter name
3839 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
3840 (lambda (formals ...)
3845 #'proc-name))))))))))
3849 (define using-readline?
3850 (let ((using-readline? (make-fluid)))
3851 (make-procedure-with-setter
3852 (lambda () (fluid-ref using-readline?))
3853 (lambda (v) (fluid-set! using-readline? v)))))
3857 ;;; {Deprecated stuff}
3861 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3865 ;;; Place the user in the guile-user module.
3869 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3871 ;; Set filename to #f to prevent reload.
3872 (define-module (guile-user)
3873 #:autoload (system base compile) (compile compile-file)
3876 ;; Remain in the `(guile)' module at compilation-time so that the
3877 ;; `-Wunused-toplevel' warning works as expected.
3878 (eval-when (compile) (set-current-module the-root-module))
3880 ;;; boot-9.scm ends here