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)
394 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
395 ;; expanded macros, to dispatch an input against a set of patterns.
396 (define $sc-dispatch #f)
399 (primitive-load-path "ice-9/psyntax-pp")
400 ;; The binding for `macroexpand' has now been overridden, making psyntax the
407 ((_ x y ...) (if x (and y ...) #f))))
413 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
415 (define-syntax-rule (when test stmt stmt* ...)
416 (if test (begin stmt stmt* ...)))
418 (define-syntax-rule (unless test stmt stmt* ...)
419 (if (not test) (begin stmt stmt* ...)))
421 ;; The "maybe-more" bits are something of a hack, so that we can support
422 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
425 (syntax-rules (=> else)
426 ((_ "maybe-more" test consequent)
427 (if test consequent))
429 ((_ "maybe-more" test consequent clause ...)
430 (if test consequent (cond clause ...)))
432 ((_ (else else1 else2 ...))
433 (begin else1 else2 ...))
435 ((_ (test => receiver) more-clause ...)
437 (cond "maybe-more" t (receiver t) more-clause ...)))
439 ((_ (generator guard => receiver) more-clause ...)
440 (call-with-values (lambda () generator)
443 (apply guard t) (apply receiver t) more-clause ...))))
445 ((_ (test => receiver ...) more-clause ...)
446 (syntax-violation 'cond "wrong number of receiver expressions"
447 '(test => receiver ...)))
448 ((_ (generator guard => receiver ...) more-clause ...)
449 (syntax-violation 'cond "wrong number of receiver expressions"
450 '(generator guard => receiver ...)))
452 ((_ (test) more-clause ...)
454 (cond "maybe-more" t t more-clause ...)))
456 ((_ (test body1 body2 ...) more-clause ...)
458 test (begin body1 body2 ...) more-clause ...))))
464 (let ((atom-key (key ...)))
465 (case atom-key clauses ...)))
467 (else result1 result2 ...))
468 (begin result1 result2 ...))
470 ((atoms ...) result1 result2 ...))
471 (if (memv key '(atoms ...))
472 (begin result1 result2 ...)))
474 ((atoms ...) result1 result2 ...)
476 (if (memv key '(atoms ...))
477 (begin result1 result2 ...)
478 (case key clause clauses ...)))))
482 ((do ((var init step ...) ...)
495 (loop (do "step" var step ...)
503 (define-syntax-rule (delay exp)
504 (make-promise (lambda () exp)))
506 (include-from-path "ice-9/quasisyntax")
508 (define-syntax current-source-location
512 (with-syntax ((s (datum->syntax x (syntax-source x))))
515 ;; We provide this accessor out of convenience. current-line and
516 ;; current-column aren't so interesting, because they distort what they
517 ;; are measuring; better to use syntax-source from a macro.
519 (define-syntax current-filename
521 "A macro that expands to the current filename: the filename that
522 the (current-filename) form appears in. Expands to #f if this
523 information is unavailable."
525 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
527 (define-syntax-rule (define-once sym val)
529 (if (module-locally-bound? (current-module) 'sym) sym val)))
531 ;;; The real versions of `map' and `for-each', with cycle detection, and
532 ;;; that use reverse! instead of recursion in the case of `map'.
537 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
540 (if (eq? tortoise hare)
541 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
543 (map1 (cdr hare) (cdr tortoise) #f
544 (cons (f (car hare)) out)))
545 (map1 (cdr hare) tortoise #t
546 (cons (f (car hare)) out)))
549 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
553 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
558 (scm-error 'wrong-type-arg "map"
560 "List of wrong length: ~S"
564 (map2 (cdr h1) (cdr h2) t1 t2 #t
565 (cons (f (car h1) (car h2)) out)))
567 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
570 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
573 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
574 (cons (f (car h1) (car h2)) out)))))
576 ((and (null? h1) (null? h2))
580 (scm-error 'wrong-type-arg "map"
582 "List of wrong length: ~S"
586 (scm-error 'wrong-type-arg "map"
591 (let ((len (length l1)))
592 (let mapn ((rest rest))
594 (if (= (length (car rest)) len)
596 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
597 (list (car rest)) #f)))))
598 (let mapn ((l1 l1) (rest rest) (out '()))
601 (mapn (cdr l1) (map cdr rest)
602 (cons (apply f (car l1) (map car rest)) out)))))))
604 (define map-in-order map)
609 (let for-each1 ((hare l) (tortoise l) (move? #f))
612 (if (eq? tortoise hare)
613 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
617 (for-each1 (cdr hare) (cdr tortoise) #f)))
620 (for-each1 (cdr hare) tortoise #t)))
622 (if (not (null? hare))
623 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
627 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
629 ((and (pair? h1) (pair? h2))
632 (f (car h1) (car h2))
633 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
635 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
638 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
641 (f (car h1) (car h2))
642 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
645 (or (null? h2) (pair? h2))
646 (and (pair? h1) (null? h2)))
650 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
653 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
657 (let ((len (length l1)))
658 (let for-eachn ((rest rest))
660 (if (= (length (car rest)) len)
661 (for-eachn (cdr rest))
662 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
663 (list (car rest)) #f)))))
665 (let for-eachn ((l1 l1) (rest rest))
668 (apply f (car l1) (map car rest))
669 (for-eachn (cdr l1) (map cdr rest))))))))
675 ;;; Extensible exception printing.
678 (define set-exception-printer! #f)
679 ;; There is already a definition of print-exception from backtrace.c
680 ;; that we will override.
682 (let ((exception-printers '()))
683 (define (print-location frame port)
684 (let ((source (and=> frame frame-source)))
685 ;; source := (addr . (filename . (line . column)))
687 (let ((filename (or (cadr source) "<unnamed port>"))
688 (line (caddr source))
689 (col (cdddr source)))
690 (format port "~a:~a:~a: " filename (1+ line) col))
691 (format port "ERROR: "))))
693 (set! set-exception-printer!
695 (set! exception-printers (acons key proc exception-printers))))
697 (set! print-exception
698 (lambda (port frame key args)
699 (define (default-printer)
700 (format port "Throw to key `~a' with args `~s'." key args))
703 (let ((proc (frame-procedure frame)))
704 (print-location frame port)
705 (format port "In procedure ~a:\n"
706 (or (procedure-name proc) proc))))
708 (print-location frame port)
711 (let ((printer (assq-ref exception-printers key)))
713 (printer port key args default-printer)
716 (format port "Error while printing exception.")))
718 (force-output port))))
721 ;;; Printers for those keys thrown by Guile.
724 (define (scm-error-printer port key args default-printer)
725 ;; Abuse case-lambda as a pattern matcher, given that we don't have
726 ;; ice-9 match at this point.
728 ((subr msg args . rest)
730 (format port "In procedure ~a: " subr))
731 (apply format port msg (or args '())))
732 (_ (default-printer)))
735 (define (syntax-error-printer port key args default-printer)
737 ((who what where form subform . extra)
738 (format port "Syntax error:\n")
740 (let ((file (or (assq-ref where 'filename) "unknown file"))
741 (line (and=> (assq-ref where 'line) 1+))
742 (col (assq-ref where 'column)))
743 (format port "~a:~a:~a: " file line col))
744 (format port "unknown location: "))
746 (format port "~a: " who))
747 (format port "~a" what)
749 (format port " in subform ~s of ~s" subform form)
751 (format port " in form ~s" form))))
752 (_ (default-printer)))
755 (define (getaddrinfo-error-printer port key args default-printer)
756 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
758 (set-exception-printer! 'goops-error scm-error-printer)
759 (set-exception-printer! 'host-not-found scm-error-printer)
760 (set-exception-printer! 'keyword-argument-error scm-error-printer)
761 (set-exception-printer! 'misc-error scm-error-printer)
762 (set-exception-printer! 'no-data scm-error-printer)
763 (set-exception-printer! 'no-recovery scm-error-printer)
764 (set-exception-printer! 'null-pointer-error scm-error-printer)
765 (set-exception-printer! 'out-of-range scm-error-printer)
766 (set-exception-printer! 'program-error scm-error-printer)
767 (set-exception-printer! 'read-error scm-error-printer)
768 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
769 (set-exception-printer! 'signal scm-error-printer)
770 (set-exception-printer! 'stack-overflow scm-error-printer)
771 (set-exception-printer! 'system-error scm-error-printer)
772 (set-exception-printer! 'try-again scm-error-printer)
773 (set-exception-printer! 'unbound-variable scm-error-printer)
774 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
775 (set-exception-printer! 'wrong-type-arg scm-error-printer)
777 (set-exception-printer! 'syntax-error syntax-error-printer)
779 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
787 (define-syntax define-macro
791 ((_ (macro . args) doc body1 body ...)
792 (string? (syntax->datum #'doc))
793 #'(define-macro macro doc (lambda args body1 body ...)))
794 ((_ (macro . args) body ...)
795 #'(define-macro macro #f (lambda args body ...)))
796 ((_ macro doc transformer)
797 (or (string? (syntax->datum #'doc))
798 (not (syntax->datum #'doc)))
799 #'(define-syntax macro
802 #((macro-type . defmacro)
803 (defmacro-args args))
806 (let ((v (syntax->datum #'args)))
807 (datum->syntax y (apply transformer v)))))))))))
809 (define-syntax defmacro
811 "Define a defmacro, with the old lispy defun syntax."
813 ((_ macro args doc body1 body ...)
814 (string? (syntax->datum #'doc))
815 #'(define-macro macro doc (lambda args body1 body ...)))
816 ((_ macro args body ...)
817 #'(define-macro macro #f (lambda args body ...))))))
826 (define-syntax begin-deprecated
830 (if (include-deprecated-features)
831 #'(begin form form* ...)
836 ;;; {Trivial Functions}
839 (define (identity x) x)
841 (define (compose proc . rest)
842 "Compose PROC with the procedures in REST, such that the last one in
843 REST is applied first and PROC last, and return the resulting procedure.
844 The given procedures must have compatible arity."
847 (let ((g (apply compose rest)))
849 (call-with-values (lambda () (apply g args)) proc)))))
851 (define (negate proc)
852 "Return a procedure with the same arity as PROC that returns the `not'
855 (not (apply proc args))))
857 (define (const value)
858 "Return a procedure that accepts any number of arguments and returns
863 (define (and=> value procedure) (and value (procedure value)))
864 (define call/cc call-with-current-continuation)
866 (define-syntax-rule (false-if-exception expr)
869 (lambda (k . args) #f)))
873 ;;; {General Properties}
876 ;; Properties are a lispy way to associate random info with random objects.
877 ;; Traditionally properties are implemented as an alist or a plist actually
878 ;; pertaining to the object in question.
880 ;; These "object properties" have the advantage that they can be associated with
881 ;; any object, even if the object has no plist. Object properties are good when
882 ;; you are extending pre-existing objects in unexpected ways. They also present
883 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
884 ;; type that always has properties, it's often still best to store those
885 ;; properties within the object itself.
887 (define (make-object-property)
888 (define-syntax-rule (with-mutex lock exp)
889 (dynamic-wind (lambda () (lock-mutex lock))
891 (lambda () (unlock-mutex lock))))
892 (let ((prop (make-weak-key-hash-table))
894 (make-procedure-with-setter
895 (lambda (obj) (with-mutex lock (hashq-ref prop obj)))
896 (lambda (obj val) (with-mutex lock (hashq-set! prop obj val))))))
901 ;;; {Symbol Properties}
904 ;;; Symbol properties are something you see in old Lisp code. In most current
905 ;;; Guile code, symbols are not used as a data structure -- they are used as
906 ;;; keys into other data structures.
908 (define (symbol-property sym prop)
909 (let ((pair (assoc prop (symbol-pref sym))))
910 (and pair (cdr pair))))
912 (define (set-symbol-property! sym prop val)
913 (let ((pair (assoc prop (symbol-pref sym))))
916 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
918 (define (symbol-property-remove! sym prop)
919 (let ((pair (assoc prop (symbol-pref sym))))
921 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
928 (define (array-shape a)
929 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
930 (array-dimensions a)))
937 ;;; It's much better if you can use lambda* / define*, of course.
939 (define (kw-arg-ref args kw)
940 (let ((rem (member kw args)))
941 (and rem (pair? (cdr rem)) (cadr rem))))
948 (define (struct-layout s)
949 (struct-ref (struct-vtable s) vtable-index-layout))
956 ;; Printing records: by default, records are printed as
958 ;; #<type-name field1: val1 field2: val2 ...>
960 ;; You can change that by giving a custom printing function to
961 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
962 ;; will be called like
964 ;; (<printer> object port)
966 ;; It should print OBJECT to PORT.
968 (define (inherit-print-state old-port new-port)
969 (if (get-print-state old-port)
970 (port-with-print-state new-port (get-print-state old-port))
973 ;; 0: type-name, 1: fields, 2: constructor
974 (define record-type-vtable
975 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
976 ;; that we need to expose the bare vtable-vtable to Scheme.
977 (make-vtable-vtable "prprpw" 0
979 (cond ((eq? s record-type-vtable)
980 (display "#<record-type-vtable>" p))
982 (display "#<record-type " p)
983 (display (record-type-name s) p)
986 (define (record-type? obj)
987 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
989 (define* (make-record-type type-name fields #:optional printer)
990 ;; Pre-generate constructors for nfields < 20.
991 (define-syntax make-constructor
993 (define *max-static-argument-count* 20)
994 (define (make-formals n)
1000 (string (integer->char (+ (char->integer #\a) i)))))
1004 ((_ rtd exp) (not (identifier? #'exp))
1006 (make-constructor rtd n)))
1010 (if (< n *max-static-argument-count*)
1011 (cons (with-syntax (((formal ...) (make-formals n))
1014 (lambda (formal ...)
1015 (make-struct rtd 0 formal ...))))
1020 (if (= (length args) nfields)
1021 (apply make-struct rtd 0 args)
1022 (scm-error 'wrong-number-of-args
1023 (format #f "make-~a" type-name)
1024 "Wrong number of arguments" '() #f)))))))))
1026 (define (default-record-printer s p)
1028 (display (record-type-name (record-type-descriptor s)) p)
1029 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1032 ((not (null? fields))
1034 (display (car fields) p)
1036 (display (struct-ref s off) p)
1037 (loop (cdr fields) (+ 1 off)))))
1040 (let ((rtd (make-struct record-type-vtable 0
1042 (apply string-append
1043 (map (lambda (f) "pw") fields)))
1044 (or printer default-record-printer)
1046 (copy-tree fields))))
1047 (struct-set! rtd (+ vtable-offset-user 2)
1048 (make-constructor rtd (length fields)))
1049 ;; Temporary solution: Associate a name to the record type descriptor
1050 ;; so that the object system can create a wrapper class for it.
1051 (set-struct-vtable-name! rtd (if (symbol? type-name)
1053 (string->symbol type-name)))
1056 (define (record-type-name obj)
1057 (if (record-type? obj)
1058 (struct-ref obj vtable-offset-user)
1059 (error 'not-a-record-type obj)))
1061 (define (record-type-fields obj)
1062 (if (record-type? obj)
1063 (struct-ref obj (+ 1 vtable-offset-user))
1064 (error 'not-a-record-type obj)))
1066 (define* (record-constructor rtd #:optional field-names)
1067 (if (not field-names)
1068 (struct-ref rtd (+ 2 vtable-offset-user))
1070 `(lambda ,field-names
1071 (make-struct ',rtd 0 ,@(map (lambda (f)
1072 (if (memq f field-names)
1075 (record-type-fields rtd)))))))
1077 (define (record-predicate rtd)
1078 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1080 (define (%record-type-error rtd obj) ;; private helper
1081 (or (eq? rtd (record-type-descriptor obj))
1082 (scm-error 'wrong-type-arg "%record-type-check"
1083 "Wrong type record (want `~S'): ~S"
1084 (list (record-type-name rtd) obj)
1087 (define (record-accessor rtd field-name)
1088 (let ((pos (list-index (record-type-fields rtd) field-name)))
1090 (error 'no-such-field field-name))
1092 (if (eq? (struct-vtable obj) rtd)
1093 (struct-ref obj pos)
1094 (%record-type-error rtd obj)))))
1096 (define (record-modifier rtd field-name)
1097 (let ((pos (list-index (record-type-fields rtd) field-name)))
1099 (error 'no-such-field field-name))
1101 (if (eq? (struct-vtable obj) rtd)
1102 (struct-set! obj pos val)
1103 (%record-type-error rtd obj)))))
1105 (define (record? obj)
1106 (and (struct? obj) (record-type? (struct-vtable obj))))
1108 (define (record-type-descriptor obj)
1111 (error 'not-a-record obj)))
1120 (define (->bool x) (not (not x)))
1127 (define (symbol-append . args)
1128 (string->symbol (apply string-append (map symbol->string args))))
1130 (define (list->symbol . args)
1131 (string->symbol (apply list->string args)))
1133 (define (symbol . args)
1134 (string->symbol (apply string args)))
1141 (define (list-index l k)
1144 (and (not (null? l))
1147 (loop (+ n 1) (cdr l))))))
1151 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1152 ;; `stat' accessors.
1153 (primitive-load-path "ice-9/posix")
1155 (if (provided? 'socket)
1156 (primitive-load-path "ice-9/networking"))
1158 ;; For reference, Emacs file-exists-p uses stat in this same way.
1159 (define file-exists?
1160 (if (provided? 'posix)
1162 (->bool (stat str #f)))
1164 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
1166 (if port (begin (close-port port) #t)
1169 (define file-is-directory?
1170 (if (provided? 'posix)
1172 (eq? (stat:type (stat str)) 'directory))
1174 (let ((port (catch 'system-error
1175 (lambda () (open-file (string-append str "/.")
1178 (if port (begin (close-port port) #t)
1181 (define (system-error-errno args)
1182 (if (eq? (car args) 'system-error)
1183 (car (list-ref args 4))
1188 ;;; {Error Handling}
1194 (scm-error 'misc-error #f "?" #f #f))
1196 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1197 (scm-error 'misc-error #f msg (cons message args) #f)))))
1201 ;;; {Time Structures}
1204 (define (tm:sec obj) (vector-ref obj 0))
1205 (define (tm:min obj) (vector-ref obj 1))
1206 (define (tm:hour obj) (vector-ref obj 2))
1207 (define (tm:mday obj) (vector-ref obj 3))
1208 (define (tm:mon obj) (vector-ref obj 4))
1209 (define (tm:year obj) (vector-ref obj 5))
1210 (define (tm:wday obj) (vector-ref obj 6))
1211 (define (tm:yday obj) (vector-ref obj 7))
1212 (define (tm:isdst obj) (vector-ref obj 8))
1213 (define (tm:gmtoff obj) (vector-ref obj 9))
1214 (define (tm:zone obj) (vector-ref obj 10))
1216 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1217 (define (set-tm:min obj val) (vector-set! obj 1 val))
1218 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1219 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1220 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1221 (define (set-tm:year obj val) (vector-set! obj 5 val))
1222 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1223 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1224 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1225 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1226 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1228 (define (tms:clock obj) (vector-ref obj 0))
1229 (define (tms:utime obj) (vector-ref obj 1))
1230 (define (tms:stime obj) (vector-ref obj 2))
1231 (define (tms:cutime obj) (vector-ref obj 3))
1232 (define (tms:cstime obj) (vector-ref obj 4))
1236 ;;; {File Descriptors and Ports}
1239 (define file-position ftell)
1240 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1241 (seek port offset whence))
1243 (define (move->fdes fd/port fd)
1244 (cond ((integer? fd/port)
1245 (dup->fdes fd/port fd)
1249 (primitive-move->fdes fd/port fd)
1250 (set-port-revealed! fd/port 1)
1253 (define (release-port-handle port)
1254 (let ((revealed (port-revealed port)))
1256 (set-port-revealed! port (- revealed 1)))))
1261 (fdopen (dup->fdes port/fd) mode))
1262 ((port/fd mode new-fd)
1263 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1264 (set-port-revealed! port 1)
1270 (dup->port port/fd "r"))
1272 (dup->port port/fd "r" new-fd))))
1274 (define dup->outport
1277 (dup->port port/fd "w"))
1279 (dup->port port/fd "w" new-fd))))
1284 (if (integer? port/fd)
1286 (dup->port port/fd (port-mode port/fd))))
1288 (if (integer? port/fd)
1289 (dup->fdes port/fd new-fd)
1290 (dup->port port/fd (port-mode port/fd) new-fd)))))
1292 (define (duplicate-port port modes)
1293 (dup->port port modes))
1295 (define (fdes->inport fdes)
1296 (let loop ((rest-ports (fdes->ports fdes)))
1297 (cond ((null? rest-ports)
1298 (let ((result (fdopen fdes "r")))
1299 (set-port-revealed! result 1)
1301 ((input-port? (car rest-ports))
1302 (set-port-revealed! (car rest-ports)
1303 (+ (port-revealed (car rest-ports)) 1))
1306 (loop (cdr rest-ports))))))
1308 (define (fdes->outport fdes)
1309 (let loop ((rest-ports (fdes->ports fdes)))
1310 (cond ((null? rest-ports)
1311 (let ((result (fdopen fdes "w")))
1312 (set-port-revealed! result 1)
1314 ((output-port? (car rest-ports))
1315 (set-port-revealed! (car rest-ports)
1316 (+ (port-revealed (car rest-ports)) 1))
1319 (loop (cdr rest-ports))))))
1321 (define (port->fdes port)
1322 (set-port-revealed! port (+ (port-revealed port) 1))
1325 (define (setenv name value)
1327 (putenv (string-append name "=" value))
1330 (define (unsetenv name)
1331 "Remove the entry for NAME from the environment."
1339 (define (in-vicinity vicinity file)
1340 (let ((tail (let ((len (string-length vicinity)))
1343 (string-ref vicinity (- len 1))))))
1344 (string-append vicinity
1353 ;;; {Help for scm_shell}
1355 ;;; The argument-processing code used by Guile-based shells generates
1356 ;;; Scheme code based on the argument list. This page contains help
1357 ;;; functions for the code it generates.
1360 (define (command-line) (program-arguments))
1362 ;; This is mostly for the internal use of the code generated by
1363 ;; scm_compile_shell_switches.
1365 (define (load-user-init)
1366 (let* ((home (or (getenv "HOME")
1367 (false-if-exception (passwd:dir (getpwuid (getuid))))
1368 "/")) ;; fallback for cygwin etc.
1369 (init-file (in-vicinity home ".guile")))
1370 (if (file-exists? init-file)
1371 (primitive-load init-file))))
1375 ;;; {The interpreter stack}
1378 ;; %stacks defined in stacks.c
1379 (define (%start-stack tag thunk)
1380 (let ((prompt-tag (make-prompt-tag "start-stack")))
1384 (with-fluids ((%stacks (acons tag prompt-tag
1385 (or (fluid-ref %stacks) '()))))
1388 (%start-stack tag (lambda () (apply k args)))))))
1390 (define-syntax-rule (start-stack tag exp)
1391 (%start-stack tag (lambda () exp)))
1395 ;;; {Loading by paths}
1398 ;;; Load a Scheme source file named NAME, searching for it in the
1399 ;;; directories listed in %load-path, and applying each of the file
1400 ;;; name extensions listed in %load-extensions.
1401 (define (load-from-path name)
1402 (start-stack 'load-stack
1403 (primitive-load-path name)))
1405 (define-syntax-rule (add-to-load-path elt)
1406 "Add ELT to Guile's load path, at compile-time and at run-time."
1407 (eval-when (compile load eval)
1408 (set! %load-path (cons elt %load-path))))
1410 (define %load-verbosely #f)
1411 (define (assert-load-verbosity v) (set! %load-verbosely v))
1413 (define (%load-announce file)
1415 (with-output-to-port (current-warning-port)
1418 (display "loading ")
1423 (set! %load-hook %load-announce)
1427 ;;; {Reader Extensions}
1429 ;;; Reader code for various "#c" forms.
1432 (define read-eval? (make-fluid #f))
1433 (read-hash-extend #\.
1435 (if (fluid-ref read-eval?)
1436 (eval (read port) (interaction-environment))
1438 "#. read expansion found and read-eval? is #f."))))
1442 ;;; {Low Level Modules}
1444 ;;; These are the low level data structures for modules.
1446 ;;; Every module object is of the type 'module-type', which is a record
1447 ;;; consisting of the following members:
1449 ;;; - eval-closure: the function that defines for its module the strategy that
1450 ;;; shall be followed when looking up symbols in the module.
1452 ;;; An eval-closure is a function taking two arguments: the symbol to be
1453 ;;; looked up and a boolean value telling whether a binding for the symbol
1454 ;;; should be created if it does not exist yet. If the symbol lookup
1455 ;;; succeeded (either because an existing binding was found or because a new
1456 ;;; binding was created), a variable object representing the binding is
1457 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1458 ;;; closure does not take the module to be searched as an argument: During
1459 ;;; construction of the eval-closure, the eval-closure has to store the
1460 ;;; module it belongs to in its environment. This means, that any
1461 ;;; eval-closure can belong to only one module.
1463 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1464 ;;; special cases of eval-closures are to be distinguished: During startup
1465 ;;; the module system is not yet activated. In this phase, no modules are
1466 ;;; defined and all bindings are automatically stored by the system in the
1467 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1468 ;;; functions which require an eval-closure as their argument need to be
1469 ;;; passed the value #f.
1471 ;;; The other two special cases of eval-closures are the
1472 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1473 ;;; behave equally for the case that no new binding is to be created. The
1474 ;;; difference between the two comes in, when the boolean argument to the
1475 ;;; eval-closure indicates that a new binding shall be created if it is not
1478 ;;; Given that no new binding shall be created, both standard eval-closures
1479 ;;; define the following standard strategy of searching bindings in the
1480 ;;; module: First, the module's obarray is searched for the symbol. Second,
1481 ;;; if no binding for the symbol was found in the module's obarray, the
1482 ;;; module's binder procedure is exececuted. If this procedure did not
1483 ;;; return a binding for the symbol, the modules referenced in the module's
1484 ;;; uses list are recursively searched for a binding of the symbol. If the
1485 ;;; binding can not be found in these modules also, the symbol lookup has
1488 ;;; If a new binding shall be created, the standard-interface-eval-closure
1489 ;;; immediately returns indicating failure. That is, it does not even try
1490 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1491 ;;; first search the obarray, and if no binding was found there, would
1492 ;;; create a new binding in the obarray, therefore not calling the binder
1493 ;;; procedure or searching the modules in the uses list.
1495 ;;; The explanation of the following members obarray, binder and uses
1496 ;;; assumes that the symbol lookup follows the strategy that is defined in
1497 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1499 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1500 ;;; hash table, the definitions are found that are local to the module (that
1501 ;;; is, not imported from other modules). When looking up bindings in the
1502 ;;; module, this hash table is searched first.
1504 ;;; - binder: either #f or a function taking a module and a symbol argument.
1505 ;;; If it is a function it is called after the obarray has been
1506 ;;; unsuccessfully searched for a binding. It then can provide bindings
1507 ;;; that would otherwise not be found locally in the module.
1509 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1510 ;;; These modules are the third place queried for bindings after the obarray
1511 ;;; has been unsuccessfully searched and the binder function did not deliver
1512 ;;; a result either.
1514 ;;; - transformer: either #f or a function taking a scheme expression as
1515 ;;; delivered by read. If it is a function, it will be called to perform
1516 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1517 ;;; expression. The output of the transformer function will then be passed
1518 ;;; to Guile's internal memoizer. This means that the output must be valid
1519 ;;; scheme code. The only exception is, that the output may make use of the
1520 ;;; syntax extensions provided to identify the modules that a binding
1523 ;;; - name: the name of the module. This is used for all kinds of printing
1524 ;;; outputs. In certain places the module name also serves as a way of
1525 ;;; identification. When adding a module to the uses list of another
1526 ;;; module, it is made sure that the new uses list will not contain two
1527 ;;; modules of the same name.
1529 ;;; - kind: classification of the kind of module. The value is (currently?)
1530 ;;; only used for printing. It has no influence on how a module is treated.
1531 ;;; Currently the following values are used when setting the module kind:
1532 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1533 ;;; is set, it defaults to 'module.
1535 ;;; - duplicates-handlers: a list of procedures that get called to make a
1536 ;;; choice between two duplicate bindings when name clashes occur. See the
1537 ;;; `duplicate-handlers' global variable below.
1539 ;;; - observers: a list of procedures that get called when the module is
1542 ;;; - weak-observers: a weak-key hash table of procedures that get called
1543 ;;; when the module is modified. See `module-observe-weak' for details.
1545 ;;; In addition, the module may (must?) contain a binding for
1546 ;;; `%module-public-interface'. This variable should be bound to a module
1547 ;;; representing the exported interface of a module. See the
1548 ;;; `module-public-interface' and `module-export!' procedures.
1550 ;;; !!! warning: The interface to lazy binder procedures is going
1551 ;;; to be changed in an incompatible way to permit all the basic
1552 ;;; module ops to be virtualized.
1554 ;;; (make-module size use-list lazy-binding-proc) => module
1555 ;;; module-{obarray,uses,binder}[|-set!]
1556 ;;; (module? obj) => [#t|#f]
1557 ;;; (module-locally-bound? module symbol) => [#t|#f]
1558 ;;; (module-bound? module symbol) => [#t|#f]
1559 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1560 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1561 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1562 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1563 ;;; (module-symbol-binding module symbol opt-value)
1564 ;;; => [ <obj> | opt-value | an error occurs ]
1565 ;;; (module-make-local-var! module symbol) => #<variable...>
1566 ;;; (module-add! module symbol var) => unspecified
1567 ;;; (module-remove! module symbol) => unspecified
1568 ;;; (module-for-each proc module) => unspecified
1569 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1570 ;;; (set-current-module module) => unspecified
1571 ;;; (current-module) => #<module...>
1577 ;;; {Printing Modules}
1580 ;; This is how modules are printed. You can re-define it.
1581 (define (%print-module mod port)
1583 (display (or (module-kind mod) "module") port)
1585 (display (module-name mod) port)
1587 (display (number->string (object-address mod) 16) port)
1591 ;; Locally extend the syntax to allow record accessors to be defined at
1592 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1593 ;; the setters, in order to allow for redefinition of the record type; not
1594 ;; relevant in the case of modules, but perhaps if we make this public, it
1597 ((define-record-type
1599 (define (make-id scope . fragments)
1600 (datum->syntax #'scope
1601 (apply symbol-append
1603 (if (symbol? x) x (syntax->datum x)))
1606 (define (getter rtd type-name field slot)
1607 #`(define #,(make-id rtd type-name '- field)
1609 (lambda (#,type-name)
1610 (if (eq? (struct-vtable #,type-name) rtd)
1611 (struct-ref #,type-name #,slot)
1612 (%record-type-error rtd #,type-name))))))
1614 (define (setter rtd type-name field slot)
1615 #`(define #,(make-id rtd 'set- type-name '- field '!)
1617 (lambda (#,type-name val)
1618 (if (eq? (struct-vtable #,type-name) rtd)
1619 (struct-set! #,type-name #,slot val)
1620 (%record-type-error rtd #,type-name))))))
1622 (define (accessors rtd type-name fields n exp)
1623 (syntax-case fields ()
1625 (((field #:no-accessors) field* ...) (identifier? #'field)
1626 (accessors rtd type-name #'(field* ...) (1+ n)
1628 (((field #:no-setter) field* ...) (identifier? #'field)
1629 (accessors rtd type-name #'(field* ...) (1+ n)
1631 #,(getter rtd type-name #'field n))))
1632 (((field #:no-getter) field* ...) (identifier? #'field)
1633 (accessors rtd type-name #'(field* ...) (1+ n)
1635 #,(setter rtd type-name #'field n))))
1636 ((field field* ...) (identifier? #'field)
1637 (accessors rtd type-name #'(field* ...) (1+ n)
1639 #,(getter rtd type-name #'field n)
1640 #,(setter rtd type-name #'field n))))))
1642 (define (predicate rtd type-name fields exp)
1644 rtd type-name fields 0
1647 (define (#,(make-id rtd type-name '?) obj)
1648 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1650 (define (field-list fields)
1651 (syntax-case fields ()
1653 (((f . opts) . rest) (identifier? #'f)
1654 (cons #'f (field-list #'rest)))
1655 ((f . rest) (identifier? #'f)
1656 (cons #'f (field-list #'rest)))))
1658 (define (constructor rtd type-name fields exp)
1659 (let ((ctor (make-id rtd type-name '-constructor))
1660 (args (field-list fields)))
1661 (predicate rtd type-name fields
1666 (make-struct rtd 0 #,@args))))
1667 (struct-set! #,rtd (+ vtable-offset-user 2)
1670 (define (type type-name printer fields)
1671 (define (make-layout)
1672 (let lp ((fields fields) (slots '()))
1673 (syntax-case fields ()
1674 (() (datum->syntax #'here
1676 (apply string-append slots))))
1677 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1679 (let ((rtd (make-id type-name type-name '-type)))
1680 (constructor rtd type-name fields
1683 (make-struct record-type-vtable 0
1687 '#,(field-list fields)))
1688 (set-struct-vtable-name! #,rtd '#,type-name)))))
1691 ((_ type-name printer (field ...))
1692 (type #'type-name #'printer #'(field ...)))))))
1696 ;; A module is characterized by an obarray in which local symbols
1697 ;; are interned, a list of modules, "uses", from which non-local
1698 ;; bindings can be inherited, and an optional lazy-binder which
1699 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1700 ;; bindings that would otherwise not be found locally in the module.
1702 ;; NOTE: If you change the set of fields or their order, you also need to
1703 ;; change the constants in libguile/modules.h.
1705 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1706 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1707 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1708 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1710 (define-record-type module
1711 (lambda (obj port) (%print-module obj port))
1716 (transformer #:no-getter)
1720 (import-obarray #:no-setter)
1722 (weak-observers #:no-setter)
1730 ;; make-module &opt size uses binder
1732 ;; Create a new module, perhaps with a particular size of obarray,
1733 ;; initial uses list, or binding procedure.
1735 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
1736 (define %default-import-size
1737 ;; Typical number of imported bindings actually used by a module.
1740 (if (not (integer? size))
1741 (error "Illegal size to make-module." size))
1742 (if (not (and (list? uses)
1743 (and-map module? uses)))
1744 (error "Incorrect use list." uses))
1745 (if (and binder (not (procedure? binder)))
1747 "Lazy-binder expected to be a procedure or #f." binder))
1749 (let ((module (module-constructor (make-hash-table size)
1750 uses binder #f macroexpand
1752 (make-hash-table %default-import-size)
1754 (make-weak-key-hash-table 31) #f
1755 (make-hash-table 7) #f #f #f)))
1757 ;; We can't pass this as an argument to module-constructor,
1758 ;; because we need it to close over a pointer to the module
1760 (set-module-eval-closure! module (standard-eval-closure module))
1767 ;;; {Observer protocol}
1770 (define (module-observe module proc)
1771 (set-module-observers! module (cons proc (module-observers module)))
1774 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1775 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1776 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1777 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1778 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1781 ;; The two-argument version is kept for backward compatibility: when called
1782 ;; with two arguments, the observer gets unregistered when closure PROC
1783 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1784 (hashq-set! (module-weak-observers module) observer-id proc))
1786 (define (module-unobserve token)
1787 (let ((module (car token))
1790 (hash-remove! (module-weak-observers module) id)
1791 (set-module-observers! module (delq1! id (module-observers module)))))
1794 (define module-defer-observers #f)
1795 (define module-defer-observers-mutex (make-mutex 'recursive))
1796 (define module-defer-observers-table (make-hash-table))
1798 (define (module-modified m)
1799 (if module-defer-observers
1800 (hash-set! module-defer-observers-table m #t)
1801 (module-call-observers m)))
1803 ;;; This function can be used to delay calls to observers so that they
1804 ;;; can be called once only in the face of massive updating of modules.
1806 (define (call-with-deferred-observers thunk)
1809 (lock-mutex module-defer-observers-mutex)
1810 (set! module-defer-observers #t))
1813 (set! module-defer-observers #f)
1814 (hash-for-each (lambda (m dummy)
1815 (module-call-observers m))
1816 module-defer-observers-table)
1817 (hash-clear! module-defer-observers-table)
1818 (unlock-mutex module-defer-observers-mutex))))
1820 (define (module-call-observers m)
1821 (for-each (lambda (proc) (proc m)) (module-observers m))
1823 ;; We assume that weak observers don't (un)register themselves as they are
1824 ;; called since this would preclude proper iteration over the hash table
1826 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1830 ;;; {Module Searching in General}
1832 ;;; We sometimes want to look for properties of a symbol
1833 ;;; just within the obarray of one module. If the property
1834 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1835 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1838 ;;; Other times, we want to test for a symbol property in the obarray
1839 ;;; of M and, if it is not found there, try each of the modules in the
1840 ;;; uses list of M. This is the normal way of testing for some
1841 ;;; property, so we state these properties without qualification as
1842 ;;; in: ``The symbol 'fnord is interned in module M because it is
1843 ;;; interned locally in module M2 which is a member of the uses list
1847 ;; module-search fn m
1849 ;; return the first non-#f result of FN applied to M and then to
1850 ;; the modules in the uses of m, and so on recursively. If all applications
1851 ;; return #f, then so does this function.
1853 (define (module-search fn m v)
1856 (or (module-search fn (car pos) v)
1859 (loop (module-uses m))))
1862 ;;; {Is a symbol bound in a module?}
1864 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1865 ;;; of S in M has been set to some well-defined value.
1868 ;; module-locally-bound? module symbol
1870 ;; Is a symbol bound (interned and defined) locally in a given module?
1872 (define (module-locally-bound? m v)
1873 (let ((var (module-local-variable m v)))
1875 (variable-bound? var))))
1877 ;; module-bound? module symbol
1879 ;; Is a symbol bound (interned and defined) anywhere in a given module
1882 (define (module-bound? m v)
1883 (let ((var (module-variable m v)))
1885 (variable-bound? var))))
1887 ;;; {Is a symbol interned in a module?}
1889 ;;; Symbol S in Module M is interned if S occurs in
1890 ;;; of S in M has been set to some well-defined value.
1892 ;;; It is possible to intern a symbol in a module without providing
1893 ;;; an initial binding for the corresponding variable. This is done
1895 ;;; (module-add! module symbol (make-undefined-variable))
1897 ;;; In that case, the symbol is interned in the module, but not
1898 ;;; bound there. The unbound symbol shadows any binding for that
1899 ;;; symbol that might otherwise be inherited from a member of the uses list.
1902 (define (module-obarray-get-handle ob key)
1903 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1905 (define (module-obarray-ref ob key)
1906 ((if (symbol? key) hashq-ref hash-ref) ob key))
1908 (define (module-obarray-set! ob key val)
1909 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1911 (define (module-obarray-remove! ob key)
1912 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1914 ;; module-symbol-locally-interned? module symbol
1916 ;; is a symbol interned (not neccessarily defined) locally in a given module
1917 ;; or its uses? Interned symbols shadow inherited bindings even if
1918 ;; they are not themselves bound to a defined value.
1920 (define (module-symbol-locally-interned? m v)
1921 (not (not (module-obarray-get-handle (module-obarray m) v))))
1923 ;; module-symbol-interned? module symbol
1925 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1926 ;; or its uses? Interned symbols shadow inherited bindings even if
1927 ;; they are not themselves bound to a defined value.
1929 (define (module-symbol-interned? m v)
1930 (module-search module-symbol-locally-interned? m v))
1933 ;;; {Mapping modules x symbols --> variables}
1936 ;; module-local-variable module symbol
1937 ;; return the local variable associated with a MODULE and SYMBOL.
1939 ;;; This function is very important. It is the only function that can
1940 ;;; return a variable from a module other than the mutators that store
1941 ;;; new variables in modules. Therefore, this function is the location
1942 ;;; of the "lazy binder" hack.
1944 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1945 ;;; to a variable, return that variable object.
1947 ;;; If the symbols is not found at first, but the module has a lazy binder,
1948 ;;; then try the binder.
1950 ;;; If the symbol is not found at all, return #f.
1952 ;;; (This is now written in C, see `modules.c'.)
1955 ;;; {Mapping modules x symbols --> bindings}
1957 ;;; These are similar to the mapping to variables, except that the
1958 ;;; variable is dereferenced.
1961 ;; module-symbol-binding module symbol opt-value
1963 ;; return the binding of a variable specified by name within
1964 ;; a given module, signalling an error if the variable is unbound.
1965 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1966 ;; return OPT-VALUE.
1968 (define (module-symbol-local-binding m v . opt-val)
1969 (let ((var (module-local-variable m v)))
1970 (if (and var (variable-bound? var))
1972 (if (not (null? opt-val))
1974 (error "Locally unbound variable." v)))))
1976 ;; module-symbol-binding module symbol opt-value
1978 ;; return the binding of a variable specified by name within
1979 ;; a given module, signalling an error if the variable is unbound.
1980 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1981 ;; return OPT-VALUE.
1983 (define (module-symbol-binding m v . opt-val)
1984 (let ((var (module-variable m v)))
1985 (if (and var (variable-bound? var))
1987 (if (not (null? opt-val))
1989 (error "Unbound variable." v)))))
1994 ;;; {Adding Variables to Modules}
1997 ;; module-make-local-var! module symbol
1999 ;; ensure a variable for V in the local namespace of M.
2000 ;; If no variable was already there, then create a new and uninitialzied
2003 ;; This function is used in modules.c.
2005 (define (module-make-local-var! m v)
2006 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2009 ;; Mark as modified since this function is called when
2010 ;; the standard eval closure defines a binding
2014 ;; Create a new local variable.
2015 (let ((local-var (make-undefined-variable)))
2016 (module-add! m v local-var)
2019 ;; module-ensure-local-variable! module symbol
2021 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2022 ;; there is no binding for SYMBOL, create a new uninitialized
2023 ;; variable. Return the local variable.
2025 (define (module-ensure-local-variable! module symbol)
2026 (or (module-local-variable module symbol)
2027 (let ((var (make-undefined-variable)))
2028 (module-add! module symbol var)
2031 ;; module-add! module symbol var
2033 ;; ensure a particular variable for V in the local namespace of M.
2035 (define (module-add! m v var)
2036 (if (not (variable? var))
2037 (error "Bad variable to module-add!" var))
2038 (module-obarray-set! (module-obarray m) v var)
2039 (module-modified m))
2043 ;; make sure that a symbol is undefined in the local namespace of M.
2045 (define (module-remove! m v)
2046 (module-obarray-remove! (module-obarray m) v)
2047 (module-modified m))
2049 (define (module-clear! m)
2050 (hash-clear! (module-obarray m))
2051 (module-modified m))
2053 ;; MODULE-FOR-EACH -- exported
2055 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2057 (define (module-for-each proc module)
2058 (hash-for-each proc (module-obarray module)))
2060 (define (module-map proc module)
2061 (hash-map->list proc (module-obarray module)))
2065 ;; Modules exist in a separate namespace from values, because you generally do
2066 ;; not want the name of a submodule, which you might not even use, to collide
2067 ;; with local variables that happen to be named the same as the submodule.
2069 (define (module-ref-submodule module name)
2070 (or (hashq-ref (module-submodules module) name)
2071 (and (module-submodule-binder module)
2072 ((module-submodule-binder module) module name))))
2074 (define (module-define-submodule! module name submodule)
2075 (hashq-set! (module-submodules module) name submodule))
2077 ;; It used to be, however, that module names were also present in the
2078 ;; value namespace. When we enable deprecated code, we preserve this
2081 ;; These shims are defined here instead of in deprecated.scm because we
2082 ;; need their definitions before loading other modules.
2085 (define (module-ref-submodule module name)
2086 (or (hashq-ref (module-submodules module) name)
2087 (and (module-submodule-binder module)
2088 ((module-submodule-binder module) module name))
2089 (let ((var (module-local-variable module name)))
2090 (and var (variable-bound? var) (module? (variable-ref var))
2092 (warn "module" module "not in submodules table")
2093 (variable-ref var))))))
2095 (define (module-define-submodule! module name submodule)
2096 (let ((var (module-local-variable module name)))
2098 (or (not (variable-bound? var))
2099 (not (module? (variable-ref var)))))
2100 (warn "defining module" module ": not overriding local definition" var)
2101 (module-define! module name submodule)))
2102 (hashq-set! (module-submodules module) name submodule)))
2106 ;;; {Module-based Loading}
2109 (define (save-module-excursion thunk)
2110 (let ((inner-module (current-module))
2112 (dynamic-wind (lambda ()
2113 (set! outer-module (current-module))
2114 (set-current-module inner-module)
2115 (set! inner-module #f))
2118 (set! inner-module (current-module))
2119 (set-current-module outer-module)
2120 (set! outer-module #f)))))
2124 ;;; {MODULE-REF -- exported}
2127 ;; Returns the value of a variable called NAME in MODULE or any of its
2128 ;; used modules. If there is no such variable, then if the optional third
2129 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2131 (define (module-ref module name . rest)
2132 (let ((variable (module-variable module name)))
2133 (if (and variable (variable-bound? variable))
2134 (variable-ref variable)
2136 (error "No variable named" name 'in module)
2137 (car rest) ; default value
2140 ;; MODULE-SET! -- exported
2142 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2143 ;; to VALUE; if there is no such variable, an error is signaled.
2145 (define (module-set! module name value)
2146 (let ((variable (module-variable module name)))
2148 (variable-set! variable value)
2149 (error "No variable named" name 'in module))))
2151 ;; MODULE-DEFINE! -- exported
2153 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2154 ;; variable, it is added first.
2156 (define (module-define! module name value)
2157 (let ((variable (module-local-variable module name)))
2160 (variable-set! variable value)
2161 (module-modified module))
2162 (let ((variable (make-variable value)))
2163 (module-add! module name variable)))))
2165 ;; MODULE-DEFINED? -- exported
2167 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2170 (define (module-defined? module name)
2171 (let ((variable (module-variable module name)))
2172 (and variable (variable-bound? variable))))
2174 ;; MODULE-USE! module interface
2176 ;; Add INTERFACE to the list of interfaces used by MODULE.
2178 (define (module-use! module interface)
2179 (if (not (or (eq? module interface)
2180 (memq interface (module-uses module))))
2182 ;; Newly used modules must be appended rather than consed, so that
2183 ;; `module-variable' traverses the use list starting from the first
2185 (set-module-uses! module (append (module-uses module)
2187 (hash-clear! (module-import-obarray module))
2188 (module-modified module))))
2190 ;; MODULE-USE-INTERFACES! module interfaces
2192 ;; Same as MODULE-USE!, but only notifies module observers after all
2193 ;; interfaces are added to the inports list.
2195 (define (module-use-interfaces! module interfaces)
2196 (let* ((cur (module-uses module))
2197 (new (let lp ((in interfaces) (out '()))
2201 (let ((iface (car in)))
2202 (if (or (memq iface cur) (memq iface out))
2204 (cons iface out))))))))
2205 (set-module-uses! module (append cur new))
2206 (hash-clear! (module-import-obarray module))
2207 (module-modified module)))
2211 ;;; {Recursive Namespaces}
2213 ;;; A hierarchical namespace emerges if we consider some module to be
2214 ;;; root, and submodules of that module to be nested namespaces.
2216 ;;; The routines here manage variable names in hierarchical namespace.
2217 ;;; Each variable name is a list of elements, looked up in successively nested
2220 ;;; (nested-ref some-root-module '(foo bar baz))
2221 ;;; => <value of a variable named baz in the submodule bar of
2222 ;;; the submodule foo of some-root-module>
2227 ;;; ;; a-root is a module
2228 ;;; ;; name is a list of symbols
2230 ;;; nested-ref a-root name
2231 ;;; nested-set! a-root name val
2232 ;;; nested-define! a-root name val
2233 ;;; nested-remove! a-root name
2235 ;;; These functions manipulate values in namespaces. For referencing the
2236 ;;; namespaces themselves, use the following:
2238 ;;; nested-ref-module a-root name
2239 ;;; nested-define-module! a-root name mod
2241 ;;; (current-module) is a natural choice for a root so for convenience there are
2244 ;;; local-ref name == nested-ref (current-module) name
2245 ;;; local-set! name val == nested-set! (current-module) name val
2246 ;;; local-define name val == nested-define! (current-module) name val
2247 ;;; local-remove name == nested-remove! (current-module) name
2248 ;;; local-ref-module name == nested-ref-module (current-module) name
2249 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2253 (define (nested-ref root names)
2256 (let loop ((cur root)
2260 (module-ref cur head #f)
2261 (let ((cur (module-ref-submodule cur head)))
2263 (loop cur (car tail) (cdr tail))))))))
2265 (define (nested-set! root names val)
2266 (let loop ((cur root)
2270 (module-set! cur head val)
2271 (let ((cur (module-ref-submodule cur head)))
2273 (error "failed to resolve module" names)
2274 (loop cur (car tail) (cdr tail)))))))
2276 (define (nested-define! root names val)
2277 (let loop ((cur root)
2281 (module-define! cur head val)
2282 (let ((cur (module-ref-submodule cur head)))
2284 (error "failed to resolve module" names)
2285 (loop cur (car tail) (cdr tail)))))))
2287 (define (nested-remove! root names)
2288 (let loop ((cur root)
2292 (module-remove! cur head)
2293 (let ((cur (module-ref-submodule cur head)))
2295 (error "failed to resolve module" names)
2296 (loop cur (car tail) (cdr tail)))))))
2299 (define (nested-ref-module root names)
2300 (let loop ((cur root)
2304 (let ((cur (module-ref-submodule cur (car names))))
2306 (loop cur (cdr names)))))))
2308 (define (nested-define-module! root names module)
2310 (error "can't redefine root module" root module)
2311 (let loop ((cur root)
2315 (module-define-submodule! cur head module)
2316 (let ((cur (or (module-ref-submodule cur head)
2317 (let ((m (make-module 31)))
2318 (set-module-kind! m 'directory)
2319 (set-module-name! m (append (module-name cur)
2321 (module-define-submodule! cur head m)
2323 (loop cur (car tail) (cdr tail)))))))
2326 (define (local-ref names)
2327 (nested-ref (current-module) names))
2329 (define (local-set! names val)
2330 (nested-set! (current-module) names val))
2332 (define (local-define names val)
2333 (nested-define! (current-module) names val))
2335 (define (local-remove names)
2336 (nested-remove! (current-module) names))
2338 (define (local-ref-module names)
2339 (nested-ref-module (current-module) names))
2341 (define (local-define-module names mod)
2342 (nested-define-module! (current-module) names mod))
2348 ;;; {The (guile) module}
2350 ;;; The standard module, which has the core Guile bindings. Also called the
2351 ;;; "root module", as it is imported by many other modules, but it is not
2352 ;;; necessarily the root of anything; and indeed, the module named '() might be
2353 ;;; better thought of as a root.
2356 (define (set-system-module! m s)
2357 (set-procedure-property! (module-eval-closure m) 'system-module s))
2359 ;; The root module uses the pre-modules-obarray as its obarray. This
2360 ;; special obarray accumulates all bindings that have been established
2361 ;; before the module system is fully booted.
2363 ;; (The obarray continues to be used by code that has been closed over
2364 ;; before the module system has been booted.)
2366 (define the-root-module
2367 (let ((m (make-module 0)))
2368 (set-module-obarray! m (%get-pre-modules-obarray))
2369 (set-module-name! m '(guile))
2370 (set-system-module! m #t)
2373 ;; The root interface is a module that uses the same obarray as the
2374 ;; root module. It does not allow new definitions, tho.
2376 (define the-scm-module
2377 (let ((m (make-module 0)))
2378 (set-module-obarray! m (%get-pre-modules-obarray))
2379 (set-module-eval-closure! m (standard-interface-eval-closure m))
2380 (set-module-name! m '(guile))
2381 (set-module-kind! m 'interface)
2382 (set-system-module! m #t)
2384 ;; In Guile 1.8 and earlier M was its own public interface.
2385 (set-module-public-interface! m m)
2389 (set-module-public-interface! the-root-module the-scm-module)
2393 ;; Now that we have a root module, even though modules aren't fully booted,
2394 ;; expand the definition of resolve-module.
2396 (define (resolve-module name . args)
2397 (if (equal? name '(guile))
2399 (error "unexpected module to resolve during module boot" name)))
2401 ;; Cheat. These bindings are needed by modules.c, but we don't want
2402 ;; to move their real definition here because that would be unnatural.
2404 (define define-module* #f)
2405 (define process-use-modules #f)
2406 (define module-export! #f)
2407 (define default-duplicate-binding-procedures #f)
2409 ;; This boots the module system. All bindings needed by modules.c
2410 ;; must have been defined by now.
2412 (set-current-module the-root-module)
2417 ;; Now that modules are booted, give module-name its final definition.
2420 (let ((accessor (record-accessor module-type 'name)))
2423 (let ((name (list (gensym))))
2424 ;; Name MOD and bind it in the module root so that it's visible to
2425 ;; `resolve-module'. This is important as `psyntax' stores module
2426 ;; names and relies on being able to `resolve-module' them.
2427 (set-module-name! mod name)
2428 (nested-define-module! (resolve-module '() #f) name mod)
2431 (define (make-modules-in module name)
2432 (or (nested-ref-module module name)
2433 (let ((m (make-module 31)))
2434 (set-module-kind! m 'directory)
2435 (set-module-name! m (append (module-name module) name))
2436 (nested-define-module! module name m)
2439 (define (beautify-user-module! module)
2440 (let ((interface (module-public-interface module)))
2441 (if (or (not interface)
2442 (eq? interface module))
2443 (let ((interface (make-module 31)))
2444 (set-module-name! interface (module-name module))
2445 (set-module-version! interface (module-version module))
2446 (set-module-kind! interface 'interface)
2447 (set-module-public-interface! module interface))))
2448 (if (and (not (memq the-scm-module (module-uses module)))
2449 (not (eq? module the-root-module)))
2450 ;; Import the default set of bindings (from the SCM module) in MODULE.
2451 (module-use! module the-scm-module)))
2453 (define (version-matches? version-ref target)
2454 (define (sub-versions-match? v-refs t)
2455 (define (sub-version-matches? v-ref t)
2456 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2458 ((number? v-ref) (eqv? v-ref t))
2461 ((>=) (>= t (cadr v-ref)))
2462 ((<=) (<= t (cadr v-ref)))
2463 ((and) (and-map matches? (cdr v-ref)))
2464 ((or) (or-map matches? (cdr v-ref)))
2465 ((not) (not (matches? (cadr v-ref))))
2466 (else (error "Invalid sub-version reference" v-ref))))
2467 (else (error "Invalid sub-version reference" v-ref)))))
2469 (and (not (null? t))
2470 (sub-version-matches? (car v-refs) (car t))
2471 (sub-versions-match? (cdr v-refs) (cdr t)))))
2473 (let ((matches? (lambda (v) (version-matches? v target))))
2474 (or (null? version-ref)
2475 (case (car version-ref)
2476 ((and) (and-map matches? (cdr version-ref)))
2477 ((or) (or-map matches? (cdr version-ref)))
2478 ((not) (not (matches? (cadr version-ref))))
2479 (else (sub-versions-match? version-ref target))))))
2481 (define (make-fresh-user-module)
2482 (let ((m (make-module)))
2483 (beautify-user-module! m)
2486 ;; NOTE: This binding is used in libguile/modules.c.
2488 (define resolve-module
2489 (let ((root (make-module)))
2490 (set-module-name! root '())
2491 ;; Define the-root-module as '(guile).
2492 (module-define-submodule! root 'guile the-root-module)
2494 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2495 (let ((already (nested-ref-module root name)))
2498 (or (not autoload) (module-public-interface already)))
2499 ;; A hit, a palpable hit.
2501 (not (version-matches? version (module-version already))))
2502 (error "incompatible module version already loaded" name))
2505 ;; Try to autoload the module, and recurse.
2506 (try-load-module name version)
2507 (resolve-module name #f #:ensure ensure))
2509 ;; No module found (or if one was, it had no public interface), and
2510 ;; we're not autoloading. Make an empty module if #:ensure is true.
2513 (make-modules-in root name)))))))))
2516 (define (try-load-module name version)
2517 (try-module-autoload name version))
2519 (define (reload-module m)
2520 "Revisit the source file corresponding to the module @var{m}."
2521 (let ((f (module-filename m)))
2523 (save-module-excursion
2525 ;; Re-set the initial environment, as in try-module-autoload.
2526 (set-current-module (make-fresh-user-module))
2527 (primitive-load-path f)
2529 ;; Though we could guess, we *should* know it.
2530 (error "unknown file name for module" m))))
2532 (define (purify-module! module)
2533 "Removes bindings in MODULE which are inherited from the (guile) module."
2534 (let ((use-list (module-uses module)))
2535 (if (and (pair? use-list)
2536 (eq? (car (last-pair use-list)) the-scm-module))
2537 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2539 ;; Return a module that is an interface to the module designated by
2542 ;; `resolve-interface' takes four keyword arguments:
2544 ;; #:select SELECTION
2546 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2547 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2548 ;; is the name in the used module and SEEN is the name in the using
2549 ;; module. Note that SEEN is also passed through RENAMER, below. The
2550 ;; default is to select all bindings. If you specify no selection but
2551 ;; a renamer, only the bindings that already exist in the used module
2552 ;; are made available in the interface. Bindings that are added later
2553 ;; are not picked up.
2557 ;; BINDINGS is a list of bindings which should not be imported.
2561 ;; PREFIX is a symbol that will be appended to each exported name.
2562 ;; The default is to not perform any renaming.
2564 ;; #:renamer RENAMER
2566 ;; RENAMER is a procedure that takes a symbol and returns its new
2567 ;; name. The default is not perform any renaming.
2569 ;; Signal "no code for module" error if module name is not resolvable
2570 ;; or its public interface is not available. Signal "no binding"
2571 ;; error if selected binding does not exist in the used module.
2573 (define* (resolve-interface name #:key
2578 (symbol-prefix-proc prefix)
2581 (let* ((module (resolve-module name #t version #:ensure #f))
2582 (public-i (and module (module-public-interface module))))
2583 (and (or (not module) (not public-i))
2584 (error "no code for module" name))
2585 (if (and (not select) (null? hide) (eq? renamer identity))
2587 (let ((selection (or select (module-map (lambda (sym var) sym)
2589 (custom-i (make-module 31)))
2590 (set-module-kind! custom-i 'custom-interface)
2591 (set-module-name! custom-i name)
2592 ;; XXX - should use a lazy binder so that changes to the
2593 ;; used module are picked up automatically.
2594 (for-each (lambda (bspec)
2595 (let* ((direct? (symbol? bspec))
2596 (orig (if direct? bspec (car bspec)))
2597 (seen (if direct? bspec (cdr bspec)))
2598 (var (or (module-local-variable public-i orig)
2599 (module-local-variable module orig)
2601 ;; fixme: format manually for now
2603 #f "no binding `~A' in module ~A"
2605 (if (memq orig hide)
2606 (set! hide (delq! orig hide))
2607 (module-add! custom-i
2611 ;; Check that we are not hiding bindings which don't exist
2612 (for-each (lambda (binding)
2613 (if (not (module-local-variable public-i binding))
2616 #f "no binding `~A' to hide in module ~A"
2621 (define (symbol-prefix-proc prefix)
2623 (symbol-append prefix symbol)))
2625 ;; This function is called from "modules.c". If you change it, be
2626 ;; sure to update "modules.c" as well.
2628 (define* (define-module* name
2629 #:key filename pure version (duplicates '())
2630 (imports '()) (exports '()) (replacements '())
2631 (re-exports '()) (autoloads '()) transformer)
2632 (define (list-of pred l)
2634 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2635 (define (valid-export? x)
2636 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2637 (define (valid-autoload? x)
2638 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
2640 (define (resolve-imports imports)
2641 (define (resolve-import import-spec)
2642 (if (list? import-spec)
2643 (apply resolve-interface import-spec)
2644 (error "unexpected use-module specification" import-spec)))
2645 (let lp ((imports imports) (out '()))
2647 ((null? imports) (reverse! out))
2650 (cons (resolve-import (car imports)) out)))
2651 (else (error "unexpected tail of imports list" imports)))))
2653 ;; We could add a #:no-check arg, set by the define-module macro, if
2654 ;; these checks are taking too much time.
2656 (let ((module (resolve-module name #f)))
2657 (beautify-user-module! module)
2659 (set-module-filename! module filename))
2661 (purify-module! module))
2664 (if (not (list-of integer? version))
2665 (error "expected list of integers for version"))
2666 (set-module-version! module version)
2667 (set-module-version! (module-public-interface module) version)))
2668 (let ((imports (resolve-imports imports)))
2669 (call-with-deferred-observers
2672 (module-use-interfaces! module imports))
2673 (if (list-of valid-export? exports)
2675 (module-export! module exports))
2676 (error "expected exports to be a list of symbols or symbol pairs"))
2677 (if (list-of valid-export? replacements)
2678 (if (pair? replacements)
2679 (module-replace! module replacements))
2680 (error "expected replacements to be a list of symbols or symbol pairs"))
2681 (if (list-of valid-export? re-exports)
2682 (if (pair? re-exports)
2683 (module-re-export! module re-exports))
2684 (error "expected re-exports to be a list of symbols or symbol pairs"))
2686 (if (not (null? autoloads))
2687 (apply module-autoload! module autoloads))
2688 ;; Wait until modules have been loaded to resolve duplicates
2690 (if (pair? duplicates)
2691 (let ((handlers (lookup-duplicates-handlers duplicates)))
2692 (set-module-duplicates-handlers! module handlers))))))
2695 (if (and (pair? transformer) (list-of symbol? transformer))
2696 (let ((iface (resolve-interface transformer))
2697 (sym (car (last-pair transformer))))
2698 (set-module-transformer! module (module-ref iface sym)))
2699 (error "expected transformer to be a module name" transformer)))
2701 (run-hook module-defined-hook module)
2704 ;; `module-defined-hook' is a hook that is run whenever a new module
2705 ;; is defined. Its members are called with one argument, the new
2707 (define module-defined-hook (make-hook 1))
2714 (define (make-autoload-interface module name bindings)
2715 (let ((b (lambda (a sym definep)
2716 (and (memq sym bindings)
2717 (let ((i (module-public-interface (resolve-module name))))
2719 (error "missing interface for module" name))
2720 (let ((autoload (memq a (module-uses module))))
2721 ;; Replace autoload-interface with actual interface if
2722 ;; that has not happened yet.
2723 (if (pair? autoload)
2724 (set-car! autoload i)))
2725 (module-local-variable i sym))))))
2726 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2727 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2728 (make-hash-table 0) #f #f #f)))
2730 (define (module-autoload! module . args)
2731 "Have @var{module} automatically load the module named @var{name} when one
2732 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2733 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2734 module '(ice-9 q) '(make-q q-length))}."
2735 (let loop ((args args))
2739 (error "invalid name+binding autoload list" args))
2741 (let ((name (car args))
2742 (bindings (cadr args)))
2743 (module-use! module (make-autoload-interface module
2745 (loop (cddr args)))))))
2750 ;;; {Autoloading modules}
2753 (define autoloads-in-progress '())
2755 ;; This function is called from "modules.c". If you change it, be
2756 ;; sure to update "modules.c" as well.
2758 (define* (try-module-autoload module-name #:optional version)
2759 (let* ((reverse-name (reverse module-name))
2760 (name (symbol->string (car reverse-name)))
2761 (dir-hint-module-name (reverse (cdr reverse-name)))
2762 (dir-hint (apply string-append
2764 (string-append (symbol->string elt) "/"))
2765 dir-hint-module-name))))
2766 (resolve-module dir-hint-module-name #f)
2767 (and (not (autoload-done-or-in-progress? dir-hint name))
2770 (lambda () (autoload-in-progress! dir-hint name))
2772 (with-fluids ((current-reader #f))
2773 (save-module-excursion
2775 ;; The initial environment when loading a module is a fresh
2777 (set-current-module (make-fresh-user-module))
2778 ;; Here we could allow some other search strategy (other than
2779 ;; primitive-load-path), for example using versions encoded
2780 ;; into the file system -- but then we would have to figure
2781 ;; out how to locate the compiled file, do auto-compilation,
2782 ;; etc. Punt for now, and don't use versions when locating
2784 (primitive-load-path (in-vicinity dir-hint name) #f)
2786 (lambda () (set-autoloaded! dir-hint name didit)))
2791 ;;; {Dynamic linking of modules}
2794 (define autoloads-done '((guile . guile)))
2796 (define (autoload-done-or-in-progress? p m)
2797 (let ((n (cons p m)))
2798 (->bool (or (member n autoloads-done)
2799 (member n autoloads-in-progress)))))
2801 (define (autoload-done! p m)
2802 (let ((n (cons p m)))
2803 (set! autoloads-in-progress
2804 (delete! n autoloads-in-progress))
2805 (or (member n autoloads-done)
2806 (set! autoloads-done (cons n autoloads-done)))))
2808 (define (autoload-in-progress! p m)
2809 (let ((n (cons p m)))
2810 (set! autoloads-done
2811 (delete! n autoloads-done))
2812 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2814 (define (set-autoloaded! p m done?)
2816 (autoload-done! p m)
2817 (let ((n (cons p m)))
2818 (set! autoloads-done (delete! n autoloads-done))
2819 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2823 ;;; {Run-time options}
2826 (define-syntax define-option-interface
2828 ((_ (interface (options enable disable) (option-set!)))
2835 (begin (interface arg) (interface))
2838 (apply (lambda (name value documentation)
2840 (if (< (string-length (symbol->string name)) 8)
2845 (display documentation)
2849 (define (enable . flags)
2850 (interface (append flags (interface)))
2852 (define (disable . flags)
2853 (let ((options (interface)))
2854 (for-each (lambda (flag) (set! options (delq! flag options)))
2858 (define-syntax-rule (option-set! opt val)
2859 (eval-when (eval load compile expand)
2860 (options (append (options) (list 'opt val)))))))))
2862 (define-option-interface
2863 (debug-options-interface
2864 (debug-options debug-enable debug-disable)
2867 (define-option-interface
2868 (read-options-interface
2869 (read-options read-enable read-disable)
2872 (define-option-interface
2873 (print-options-interface
2874 (print-options print-enable print-disable)
2879 ;;; {The Unspecified Value}
2881 ;;; Currently Guile represents unspecified values via one particular value,
2882 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2883 ;;; future if we could replace this with a return of 0 values, though.
2886 (define-syntax *unspecified*
2887 (identifier-syntax (if #f #f)))
2889 (define (unspecified? v) (eq? v *unspecified*))
2898 ;; Three fields: the procedure itself, the fluid, and the converter.
2899 (make-struct <applicable-struct-vtable> 0 'pwprpr))
2900 (set-struct-vtable-name! <parameter> '<parameter>)
2902 (define* (make-parameter init #:optional (conv (lambda (x) x)))
2903 (let ((fluid (make-fluid (conv init))))
2904 (make-struct <parameter> 0
2906 (() (fluid-ref fluid))
2907 ((x) (let ((prev (fluid-ref fluid)))
2908 (fluid-set! fluid (conv x))
2912 (define (parameter? x)
2913 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
2915 (define (parameter-fluid p)
2918 (scm-error 'wrong-type-arg "parameter-fluid"
2919 "Not a parameter: ~S" (list p) #f)))
2921 (define (parameter-converter p)
2924 (scm-error 'wrong-type-arg "parameter-fluid"
2925 "Not a parameter: ~S" (list p) #f)))
2927 (define-syntax parameterize
2930 ((_ ((param value) ...) body body* ...)
2931 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
2932 #'(let ((p param) ...)
2933 (if (not (parameter? p))
2934 (scm-error 'wrong-type-arg "parameterize"
2935 "Not a parameter: ~S" (list p) #f))
2937 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
2939 body body* ...)))))))
2943 ;;; Current ports as parameters.
2946 (let ((fluid->parameter
2947 (lambda (fluid conv)
2948 (make-struct <parameter> 0
2950 (() (fluid-ref fluid))
2951 ((x) (let ((prev (fluid-ref fluid)))
2952 (fluid-set! fluid (conv x))
2955 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
2957 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
2961 (module-remove! (current-module) 'fluid)))
2963 (port-parameterize! current-input-port %current-input-port-fluid
2964 input-port? "expected an input port")
2965 (port-parameterize! current-output-port %current-output-port-fluid
2966 output-port? "expected an output port")
2967 (port-parameterize! current-error-port %current-error-port-fluid
2968 output-port? "expected an output port"))
2976 (define current-warning-port
2977 (make-parameter (current-error-port)
2979 (if (output-port? x)
2981 (error "expected an output port" x)))))
2989 (define *repl-stack* (make-fluid '()))
2991 ;; Programs can call `batch-mode?' to see if they are running as part of a
2992 ;; script or if they are running interactively. REPL implementations ensure that
2993 ;; `batch-mode?' returns #f during their extent.
2995 (define (batch-mode?)
2996 (null? (fluid-ref *repl-stack*)))
2998 ;; Programs can re-enter batch mode, for example after a fork, by calling
2999 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3000 ;; to abort to the outermost prompt, and call a thunk there.
3002 (define (ensure-batch-mode!)
3003 (set! batch-mode? (lambda () #t)))
3005 (define (quit . args)
3006 (apply throw 'quit args))
3010 (define (gc-run-time)
3011 (cdr (assq 'gc-time-taken (gc-stats))))
3013 (define abort-hook (make-hook))
3014 (define before-error-hook (make-hook))
3015 (define after-error-hook (make-hook))
3016 (define before-backtrace-hook (make-hook))
3017 (define after-backtrace-hook (make-hook))
3019 (define before-read-hook (make-hook))
3020 (define after-read-hook (make-hook))
3021 (define before-eval-hook (make-hook 1))
3022 (define after-eval-hook (make-hook 1))
3023 (define before-print-hook (make-hook 1))
3024 (define after-print-hook (make-hook 1))
3026 ;;; This hook is run at the very end of an interactive session.
3028 (define exit-hook (make-hook))
3030 ;;; The default repl-reader function. We may override this if we've
3031 ;;; the readline library.
3033 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3034 (if (not (char-ready?))
3036 (display (if (string? prompt) prompt (prompt)))
3037 ;; An interesting situation. The printer resets the column to
3038 ;; 0 by printing a newline, but we then advance it by printing
3039 ;; the prompt. However the port-column of the output port
3040 ;; does not typically correspond with the actual column on the
3041 ;; screen, because the input is echoed back! Since the
3042 ;; input is line-buffered and thus ends with a newline, the
3043 ;; output will really start on column zero. So, here we zero
3044 ;; it out. See bug 9664.
3046 ;; Note that for similar reasons, the output-line will not
3047 ;; reflect the actual line on the screen. But given the
3048 ;; possibility of multiline input, the fix is not as
3049 ;; straightforward, so we don't bother.
3051 ;; Also note that the readline implementation papers over
3052 ;; these concerns, because it's readline itself printing the
3053 ;; prompt, and not Guile.
3054 (set-port-column! (current-output-port) 0)))
3056 (run-hook before-read-hook)
3057 ((or reader read) (current-input-port))))
3062 ;;; {IOTA functions: generating lists of numbers}
3066 (let loop ((count (1- n)) (result '()))
3067 (if (< count 0) result
3068 (loop (1- count) (cons count result)))))
3074 ;;; with `continue' and `break'.
3077 ;; The inliner will remove the prompts at compile-time if it finds that
3078 ;; `continue' or `break' are not used.
3080 (define-syntax while
3083 ((while cond body ...)
3084 #`(let ((break-tag (make-prompt-tag "break"))
3085 (continue-tag (make-prompt-tag "continue")))
3089 (define-syntax #,(datum->syntax #'while 'break)
3093 #'(abort-to-prompt break-tag arg (... ...)))
3096 (apply abort-to-prompt break-tag args))))))
3101 (define-syntax #,(datum->syntax #'while 'continue)
3105 #'(abort-to-prompt continue-tag))
3107 (syntax-violation 'continue "too many arguments" x))
3110 (abort-to-prompt continue-tag))))))
3111 (do () ((not cond) #f) body ...))
3112 (lambda (k) (lp)))))
3116 (apply values args)))))))))
3121 ;;; {Module System Macros}
3124 ;; Return a list of expressions that evaluate to the appropriate
3125 ;; arguments for resolve-interface according to SPEC.
3127 (eval-when (compile)
3128 (if (memq 'prefix (read-options))
3129 (error "boot-9 must be compiled with #:kw, not :kw")))
3131 (define (keyword-like-symbol->keyword sym)
3132 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3134 (define-syntax define-module
3136 (define (keyword-like? stx)
3137 (let ((dat (syntax->datum stx)))
3139 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3140 (define (->keyword sym)
3141 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3143 (define (parse-iface args)
3144 (let loop ((in args) (out '()))
3147 ;; The user wanted #:foo, but wrote :foo. Fix it.
3148 ((sym . in) (keyword-like? #'sym)
3149 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3150 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3151 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3152 ((#:renamer renamer . in)
3153 (loop #'in (cons* #',renamer #:renamer out)))
3155 (loop #'in (cons* #'val #'kw out))))))
3157 (define (parse args imp exp rex rep aut)
3158 ;; Just quote everything except #:use-module and #:use-syntax. We
3159 ;; need to know about all arguments regardless since we want to turn
3160 ;; symbols that look like keywords into real keywords, and the
3161 ;; keyword args in a define-module form are not regular
3162 ;; (i.e. no-backtrace doesn't take a value).
3163 (syntax-case args ()
3165 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3166 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3167 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3168 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3169 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3170 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3171 ;; The user wanted #:foo, but wrote :foo. Fix it.
3172 ((sym . args) (keyword-like? #'sym)
3173 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3174 imp exp rex rep aut))
3175 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3176 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3177 ((#:no-backtrace . args)
3179 (parse #'args imp exp rex rep aut))
3181 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3183 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3184 ((#:version (v ...) . args)
3185 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3186 ((#:duplicates (d ...) . args)
3187 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3188 ((#:filename f . args)
3189 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3190 ((#:use-module (name name* ...) . args)
3191 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3192 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3193 ((#:use-syntax (name name* ...) . args)
3194 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3195 #`(#:transformer '(name name* ...)
3196 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3197 ((#:use-module ((name name* ...) arg ...) . args)
3198 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3200 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3202 ((#:export (ex ...) . args)
3203 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3204 ((#:export-syntax (ex ...) . args)
3205 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3206 ((#:re-export (re ...) . args)
3207 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3208 ((#:re-export-syntax (re ...) . args)
3209 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3210 ((#:replace (r ...) . args)
3211 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3212 ((#:replace-syntax (r ...) . args)
3213 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3214 ((#:autoload name bindings . args)
3215 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3217 (syntax-violation 'define-module "unknown keyword or bad argument"
3221 ((_ (name name* ...) arg ...)
3222 (and-map symbol? (syntax->datum #'(name name* ...)))
3223 (with-syntax (((quoted-arg ...)
3224 (parse #'(arg ...) '() '() '() '() '()))
3225 ;; Ideally the filename is either a string or #f;
3226 ;; this hack is to work around a case in which
3227 ;; port-filename returns a symbol (`socket') for
3229 (filename (let ((f (assq-ref (or (syntax-source x) '())
3231 (and (string? f) f))))
3232 #'(eval-when (eval load compile expand)
3233 (let ((m (define-module* '(name name* ...)
3234 #:filename filename quoted-arg ...)))
3235 (set-current-module m)
3238 ;; The guts of the use-modules macro. Add the interfaces of the named
3239 ;; modules to the use-list of the current module, in order.
3241 ;; This function is called by "modules.c". If you change it, be sure
3242 ;; to change scm_c_use_module as well.
3244 (define (process-use-modules module-interface-args)
3245 (let ((interfaces (map (lambda (mif-args)
3246 (or (apply resolve-interface mif-args)
3247 (error "no such module" mif-args)))
3248 module-interface-args)))
3249 (call-with-deferred-observers
3251 (module-use-interfaces! (current-module) interfaces)))))
3253 (define-syntax use-modules
3255 (define (keyword-like? stx)
3256 (let ((dat (syntax->datum stx)))
3258 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3259 (define (->keyword sym)
3260 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3262 (define (quotify-iface args)
3263 (let loop ((in args) (out '()))
3266 ;; The user wanted #:foo, but wrote :foo. Fix it.
3267 ((sym . in) (keyword-like? #'sym)
3268 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3269 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3270 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3271 ((#:renamer renamer . in)
3272 (loop #'in (cons* #'renamer #:renamer out)))
3274 (loop #'in (cons* #''val #'kw out))))))
3276 (define (quotify specs)
3277 (let lp ((in specs) (out '()))
3280 (((name name* ...) . in)
3281 (and-map symbol? (syntax->datum #'(name name* ...)))
3282 (lp #'in (cons #''((name name* ...)) out)))
3283 ((((name name* ...) arg ...) . in)
3284 (and-map symbol? (syntax->datum #'(name name* ...)))
3285 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3286 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3291 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3292 #'(eval-when (eval load compile expand)
3293 (process-use-modules (list quoted-args ...))
3296 (define-syntax-rule (use-syntax spec ...)
3298 (eval-when (eval load compile expand)
3299 (issue-deprecation-warning
3300 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3301 (use-modules spec ...)))
3303 (include-from-path "ice-9/r6rs-libraries")
3305 (define-syntax-rule (define-private foo bar)
3308 (define-syntax define-public
3310 ((_ (name . args) . body)
3311 (define-public name (lambda args . body)))
3317 (define-syntax-rule (defmacro-public name args body ...)
3319 (defmacro name args body ...)
3320 (export-syntax name)))
3322 ;; And now for the most important macro.
3323 (define-syntax-rule (λ formals body ...)
3324 (lambda formals body ...))
3327 ;; Export a local variable
3329 ;; This function is called from "modules.c". If you change it, be
3330 ;; sure to update "modules.c" as well.
3332 (define (module-export! m names)
3333 (let ((public-i (module-public-interface m)))
3334 (for-each (lambda (name)
3335 (let* ((internal-name (if (pair? name) (car name) name))
3336 (external-name (if (pair? name) (cdr name) name))
3337 (var (module-ensure-local-variable! m internal-name)))
3338 (module-add! public-i external-name var)))
3341 (define (module-replace! m names)
3342 (let ((public-i (module-public-interface m)))
3343 (for-each (lambda (name)
3344 (let* ((internal-name (if (pair? name) (car name) name))
3345 (external-name (if (pair? name) (cdr name) name))
3346 (var (module-ensure-local-variable! m internal-name)))
3347 ;; FIXME: use a bit on variables instead of object
3349 (set-object-property! var 'replace #t)
3350 (module-add! public-i external-name var)))
3353 ;; Export all local variables from a module
3355 (define (module-export-all! mod)
3356 (define (fresh-interface!)
3357 (let ((iface (make-module)))
3358 (set-module-name! iface (module-name mod))
3359 (set-module-version! iface (module-version mod))
3360 (set-module-kind! iface 'interface)
3361 (set-module-public-interface! mod iface)
3363 (let ((iface (or (module-public-interface mod)
3364 (fresh-interface!))))
3365 (set-module-obarray! iface (module-obarray mod))))
3367 ;; Re-export a imported variable
3369 (define (module-re-export! m names)
3370 (let ((public-i (module-public-interface m)))
3371 (for-each (lambda (name)
3372 (let* ((internal-name (if (pair? name) (car name) name))
3373 (external-name (if (pair? name) (cdr name) name))
3374 (var (module-variable m internal-name)))
3376 (error "Undefined variable:" internal-name))
3377 ((eq? var (module-local-variable m internal-name))
3378 (error "re-exporting local variable:" internal-name))
3380 (module-add! public-i external-name var)))))
3383 (define-syntax-rule (export name ...)
3384 (eval-when (eval load compile expand)
3385 (call-with-deferred-observers
3387 (module-export! (current-module) '(name ...))))))
3389 (define-syntax-rule (re-export name ...)
3390 (eval-when (eval load compile expand)
3391 (call-with-deferred-observers
3393 (module-re-export! (current-module) '(name ...))))))
3395 (define-syntax-rule (export! name ...)
3396 (eval-when (eval load compile expand)
3397 (call-with-deferred-observers
3399 (module-replace! (current-module) '(name ...))))))
3401 (define-syntax-rule (export-syntax name ...)
3404 (define-syntax-rule (re-export-syntax name ...)
3405 (re-export name ...))
3412 (define* (make-mutable-parameter init #:optional (converter identity))
3413 (let ((fluid (make-fluid (converter init))))
3415 (() (fluid-ref fluid))
3416 ((val) (fluid-set! fluid (converter val))))))
3421 ;;; {Handling of duplicate imported bindings}
3424 ;; Duplicate handlers take the following arguments:
3426 ;; module importing module
3427 ;; name conflicting name
3428 ;; int1 old interface where name occurs
3429 ;; val1 value of binding in old interface
3430 ;; int2 new interface where name occurs
3431 ;; val2 value of binding in new interface
3432 ;; var previous resolution or #f
3433 ;; val value of previous resolution
3435 ;; A duplicate handler can take three alternative actions:
3437 ;; 1. return #f => leave responsibility to next handler
3438 ;; 2. exit with an error
3439 ;; 3. return a variable resolving the conflict
3442 (define duplicate-handlers
3443 (let ((m (make-module 7)))
3445 (define (check module name int1 val1 int2 val2 var val)
3446 (scm-error 'misc-error
3448 "~A: `~A' imported from both ~A and ~A"
3449 (list (module-name module)
3455 (define (warn module name int1 val1 int2 val2 var val)
3456 (format (current-warning-port)
3457 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3458 (module-name module)
3464 (define (replace module name int1 val1 int2 val2 var val)
3465 (let ((old (or (and var (object-property var 'replace) var)
3466 (module-variable int1 name)))
3467 (new (module-variable int2 name)))
3468 (if (object-property old 'replace)
3469 (and (or (eq? old new)
3470 (not (object-property new 'replace)))
3472 (and (object-property new 'replace)
3475 (define (warn-override-core module name int1 val1 int2 val2 var val)
3476 (and (eq? int1 the-scm-module)
3478 (format (current-warning-port)
3479 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3480 (module-name module)
3483 (module-local-variable int2 name))))
3485 (define (first module name int1 val1 int2 val2 var val)
3486 (or var (module-local-variable int1 name)))
3488 (define (last module name int1 val1 int2 val2 var val)
3489 (module-local-variable int2 name))
3491 (define (noop module name int1 val1 int2 val2 var val)
3494 (set-module-name! m 'duplicate-handlers)
3495 (set-module-kind! m 'interface)
3496 (module-define! m 'check check)
3497 (module-define! m 'warn warn)
3498 (module-define! m 'replace replace)
3499 (module-define! m 'warn-override-core warn-override-core)
3500 (module-define! m 'first first)
3501 (module-define! m 'last last)
3502 (module-define! m 'merge-generics noop)
3503 (module-define! m 'merge-accessors noop)
3506 (define (lookup-duplicates-handlers handler-names)
3508 (map (lambda (handler-name)
3509 (or (module-symbol-local-binding
3510 duplicate-handlers handler-name #f)
3511 (error "invalid duplicate handler name:"
3513 (if (list? handler-names)
3515 (list handler-names)))))
3517 (define default-duplicate-binding-procedures
3518 (make-mutable-parameter #f))
3520 (define default-duplicate-binding-handler
3521 (make-mutable-parameter '(replace warn-override-core warn last)
3522 (lambda (handler-names)
3523 (default-duplicate-binding-procedures
3524 (lookup-duplicates-handlers handler-names))
3531 ;;; Load is tricky when combined with relative paths, compilation, and
3532 ;;; the file system. If a path is relative, what is it relative to? The
3533 ;;; path of the source file at the time it was compiled? The path of
3534 ;;; the compiled file? What if both or either were installed? And how
3535 ;;; do you get that information? Tricky, I say.
3537 ;;; To get around all of this, we're going to do something nasty, and
3538 ;;; turn `load' into a macro. That way it can know the path of the
3539 ;;; source file with respect to which it was invoked, so it can resolve
3540 ;;; relative paths with respect to the original source path.
3542 ;;; There is an exception, and that is that if the source file was in
3543 ;;; the load path when it was compiled, instead of looking up against
3544 ;;; the absolute source location, we load-from-path against the relative
3545 ;;; source location.
3548 (define %auto-compilation-options
3549 ;; Default `compile-file' option when auto-compiling.
3550 '(#:warnings (unbound-variable arity-mismatch format)))
3552 (define* (load-in-vicinity dir path #:optional reader)
3553 (define (canonical->suffix canon)
3555 ((string-prefix? "/" canon) canon)
3556 ((and (> (string-length canon) 2)
3557 (eqv? (string-ref canon 1) #\:))
3558 ;; Paths like C:... transform to /C...
3559 (string-append "/" (substring canon 0 1) (substring canon 2)))
3562 ;; Returns the .go file corresponding to `name'. Does not search load
3563 ;; paths, only the fallback path. If the .go file is missing or out of
3564 ;; date, and auto-compilation is enabled, will try auto-compilation, just
3565 ;; as primitive-load-path does internally. primitive-load is
3566 ;; unaffected. Returns #f if auto-compilation failed or was disabled.
3568 ;; NB: Unless we need to compile the file, this function should not cause
3569 ;; (system base compile) to be loaded up. For that reason compiled-file-name
3570 ;; partially duplicates functionality from (system base compile).
3572 (define (compiled-file-name canon-path)
3573 ;; FIXME: would probably be better just to append SHA1(canon-path)
3574 ;; to the %compile-fallback-path, to avoid deep directory stats.
3575 (and %compile-fallback-path
3577 %compile-fallback-path
3578 (canonical->suffix canon-path)
3579 (cond ((or (null? %load-compiled-extensions)
3580 (string-null? (car %load-compiled-extensions)))
3581 (warn "invalid %load-compiled-extensions"
3582 %load-compiled-extensions)
3584 (else (car %load-compiled-extensions))))))
3586 (define (fresh-compiled-file-name name go-path)
3589 (let* ((scmstat (stat name))
3590 (gostat (and (not %fresh-auto-compile)
3591 (stat go-path #f))))
3593 (or (> (stat:mtime gostat) (stat:mtime scmstat))
3594 (and (= (stat:mtime gostat) (stat:mtime scmstat))
3595 (>= (stat:mtimensec gostat)
3596 (stat:mtimensec scmstat)))))
3600 (format (current-warning-port)
3601 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
3604 (%load-should-auto-compile
3605 (%warn-auto-compilation-enabled)
3606 (format (current-warning-port) ";;; compiling ~a\n" name)
3609 (resolve-interface '(system base compile))
3612 #:opts %auto-compilation-options
3613 #:env (current-module))))
3614 (format (current-warning-port) ";;; compiled ~a\n" cfn)
3618 (format (current-warning-port)
3619 ";;; WARNING: compilation of ~a failed:\n" name)
3620 (for-each (lambda (s)
3621 (if (not (string-null? s))
3622 (format (current-warning-port) ";;; ~a\n" s)))
3624 (call-with-output-string
3625 (lambda (port) (print-exception port #f k args)))
3629 (define (absolute-path? path)
3630 (string-prefix? "/" path))
3632 (define (load-absolute abs-path)
3633 (let ((cfn (let ((canon (false-if-exception (canonicalize-path abs-path))))
3635 (let ((go-path (compiled-file-name canon)))
3637 (fresh-compiled-file-name abs-path go-path)))))))
3641 (%load-hook abs-path))
3642 (load-compiled cfn))
3643 (start-stack 'load-stack
3644 (primitive-load abs-path)))))
3646 (save-module-excursion
3648 (with-fluids ((current-reader reader)
3649 (%file-port-name-canonicalization 'relative))
3651 ((or (absolute-path? path))
3652 (load-absolute path))
3653 ((absolute-path? dir)
3654 (load-absolute (in-vicinity dir path)))
3656 (load-from-path (in-vicinity dir path))))))))
3659 (make-variable-transformer
3661 (let* ((src (syntax-source x))
3662 (file (and src (assq-ref src 'filename)))
3663 (dir (and (string? file) (dirname file))))
3666 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
3670 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
3674 ;;; {`cond-expand' for SRFI-0 support.}
3676 ;;; This syntactic form expands into different commands or
3677 ;;; definitions, depending on the features provided by the Scheme
3683 ;;; --> (cond-expand <cond-expand-clause>+)
3684 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3685 ;;; <cond-expand-clause>
3686 ;;; --> (<feature-requirement> <command-or-definition>*)
3687 ;;; <feature-requirement>
3688 ;;; --> <feature-identifier>
3689 ;;; | (and <feature-requirement>*)
3690 ;;; | (or <feature-requirement>*)
3691 ;;; | (not <feature-requirement>)
3692 ;;; <feature-identifier>
3693 ;;; --> <a symbol which is the name or alias of a SRFI>
3695 ;;; Additionally, this implementation provides the
3696 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3697 ;;; determine the implementation type and the supported standard.
3699 ;;; Currently, the following feature identifiers are supported:
3701 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3703 ;;; Remember to update the features list when adding more SRFIs.
3706 (define %cond-expand-features
3707 ;; Adjust the above comment when changing this.
3711 srfi-0 ;; cond-expand itself
3712 srfi-4 ;; homogenous numeric vectors
3713 srfi-6 ;; open-input-string etc, in the guile core
3714 srfi-13 ;; string library
3715 srfi-14 ;; character sets
3716 srfi-23 ;; `error` procedure
3717 srfi-39 ;; parameterize
3718 srfi-55 ;; require-extension
3719 srfi-61 ;; general cond clause
3722 ;; This table maps module public interfaces to the list of features.
3724 (define %cond-expand-table (make-hash-table 31))
3726 ;; Add one or more features to the `cond-expand' feature list of the
3729 (define (cond-expand-provide module features)
3730 (let ((mod (module-public-interface module)))
3732 (hashq-set! %cond-expand-table mod
3733 (append (hashq-ref %cond-expand-table mod '())
3736 (define-syntax cond-expand
3738 (define (module-has-feature? mod sym)
3739 (or-map (lambda (mod)
3740 (memq sym (hashq-ref %cond-expand-table mod '())))
3743 (define (condition-matches? condition)
3744 (syntax-case condition (and or not)
3746 (and-map condition-matches? #'(c ...)))
3748 (or-map condition-matches? #'(c ...)))
3750 (if (condition-matches? #'c) #f #t))
3753 (let ((sym (syntax->datum #'c)))
3754 (if (memq sym %cond-expand-features)
3756 (module-has-feature? (current-module) sym))))))
3758 (define (match clauses alternate)
3759 (syntax-case clauses ()
3760 (((condition form ...) . rest)
3761 (if (condition-matches? #'condition)
3763 (match #'rest alternate)))
3766 (syntax-case x (else)
3767 ((_ clause ... (else form ...))
3768 (match #'(clause ...)
3770 #'(begin form ...))))
3772 (match #'(clause ...)
3774 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
3776 ;; This procedure gets called from the startup code with a list of
3777 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3779 (define (use-srfis srfis)
3780 (process-use-modules
3782 (list (list 'srfi (string->symbol
3783 (string-append "srfi-" (number->string num))))))
3788 ;;; srfi-55: require-extension
3791 (define-syntax require-extension
3793 (syntax-case x (srfi)
3795 (and-map integer? (syntax->datum #'(n ...)))
3799 (datum->syntax x (symbol-append 'srfi- n)))
3801 (map number->string (syntax->datum #'(n ...)))))))
3802 #'(use-modules (srfi srfi-n) ...)))
3804 (identifier? #'type)
3805 (syntax-violation 'require-extension "Not a recognized extension type"
3809 ;;; Defining transparently inlinable procedures
3812 (define-syntax define-inlinable
3813 ;; Define a macro and a procedure such that direct calls are inlined, via
3814 ;; the macro expansion, whereas references in non-call contexts refer to
3815 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
3817 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
3819 (define prefix (string->symbol "% "))
3820 (define (make-procedure-name name)
3822 (symbol-append prefix (syntax->datum name)
3826 ((_ (name formals ...) body ...)
3827 (identifier? #'name)
3828 (with-syntax ((proc-name (make-procedure-name #'name))
3829 ((args ...) (generate-temporaries #'(formals ...))))
3831 (define (proc-name formals ...)
3832 (syntax-parameterize ((name (identifier-syntax proc-name)))
3834 (define-syntax-parameter name
3838 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
3839 (lambda (formals ...)
3844 #'proc-name))))))))))
3848 (define using-readline?
3849 (let ((using-readline? (make-fluid)))
3850 (make-procedure-with-setter
3851 (lambda () (fluid-ref using-readline?))
3852 (lambda (v) (fluid-set! using-readline? v)))))
3856 ;;; {Deprecated stuff}
3860 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3864 ;;; Place the user in the guile-user module.
3868 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3870 ;; Set filename to #f to prevent reload.
3871 (define-module (guile-user)
3872 #:autoload (system base compile) (compile compile-file)
3875 ;; Remain in the `(guile)' module at compilation-time so that the
3876 ;; `-Wunused-toplevel' warning works as expected.
3877 (eval-when (compile) (set-current-module the-root-module))
3879 ;;; boot-9.scm ends here