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)
393 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
394 ;; expanded macros, to dispatch an input against a set of patterns.
395 (define $sc-dispatch #f)
398 (primitive-load-path "ice-9/psyntax-pp")
399 ;; The binding for `macroexpand' has now been overridden, making psyntax the
406 ((_ x y ...) (if x (and y ...) #f))))
412 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
414 (define-syntax-rule (when test stmt stmt* ...)
415 (if test (begin stmt stmt* ...)))
417 (define-syntax-rule (unless test stmt stmt* ...)
418 (if (not test) (begin stmt stmt* ...)))
420 ;; The "maybe-more" bits are something of a hack, so that we can support
421 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
424 (syntax-rules (=> else)
425 ((_ "maybe-more" test consequent)
426 (if test consequent))
428 ((_ "maybe-more" test consequent clause ...)
429 (if test consequent (cond clause ...)))
431 ((_ (else else1 else2 ...))
432 (begin else1 else2 ...))
434 ((_ (test => receiver) more-clause ...)
436 (cond "maybe-more" t (receiver t) more-clause ...)))
438 ((_ (generator guard => receiver) more-clause ...)
439 (call-with-values (lambda () generator)
442 (apply guard t) (apply receiver t) more-clause ...))))
444 ((_ (test => receiver ...) more-clause ...)
445 (syntax-violation 'cond "wrong number of receiver expressions"
446 '(test => receiver ...)))
447 ((_ (generator guard => receiver ...) more-clause ...)
448 (syntax-violation 'cond "wrong number of receiver expressions"
449 '(generator guard => receiver ...)))
451 ((_ (test) more-clause ...)
453 (cond "maybe-more" t t more-clause ...)))
455 ((_ (test body1 body2 ...) more-clause ...)
457 test (begin body1 body2 ...) more-clause ...))))
463 (let ((atom-key (key ...)))
464 (case atom-key clauses ...)))
466 (else result1 result2 ...))
467 (begin result1 result2 ...))
469 ((atoms ...) result1 result2 ...))
470 (if (memv key '(atoms ...))
471 (begin result1 result2 ...)))
473 ((atoms ...) result1 result2 ...)
475 (if (memv key '(atoms ...))
476 (begin result1 result2 ...)
477 (case key clause clauses ...)))))
481 ((do ((var init step ...) ...)
494 (loop (do "step" var step ...)
502 (define-syntax-rule (delay exp)
503 (make-promise (lambda () exp)))
505 (include-from-path "ice-9/quasisyntax")
507 (define-syntax current-source-location
511 (with-syntax ((s (datum->syntax x (syntax-source x))))
514 ;; We provide this accessor out of convenience. current-line and
515 ;; current-column aren't so interesting, because they distort what they
516 ;; are measuring; better to use syntax-source from a macro.
518 (define-syntax current-filename
520 "A macro that expands to the current filename: the filename that
521 the (current-filename) form appears in. Expands to #f if this
522 information is unavailable."
524 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
526 (define-syntax-rule (define-once sym val)
528 (if (module-locally-bound? (current-module) 'sym) sym val)))
530 ;;; The real versions of `map' and `for-each', with cycle detection, and
531 ;;; that use reverse! instead of recursion in the case of `map'.
536 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
539 (if (eq? tortoise hare)
540 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
542 (map1 (cdr hare) (cdr tortoise) #f
543 (cons (f (car hare)) out)))
544 (map1 (cdr hare) tortoise #t
545 (cons (f (car hare)) out)))
548 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
552 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
557 (scm-error 'wrong-type-arg "map"
559 "List of wrong length: ~S"
563 (map2 (cdr h1) (cdr h2) t1 t2 #t
564 (cons (f (car h1) (car h2)) out)))
566 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
569 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
572 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
573 (cons (f (car h1) (car h2)) out)))))
575 ((and (null? h1) (null? h2))
579 (scm-error 'wrong-type-arg "map"
581 "List of wrong length: ~S"
585 (scm-error 'wrong-type-arg "map"
590 (let ((len (length l1)))
591 (let mapn ((rest rest))
593 (if (= (length (car rest)) len)
595 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
596 (list (car rest)) #f)))))
597 (let mapn ((l1 l1) (rest rest) (out '()))
600 (mapn (cdr l1) (map cdr rest)
601 (cons (apply f (car l1) (map car rest)) out)))))))
603 (define map-in-order map)
608 (let for-each1 ((hare l) (tortoise l) (move? #f))
611 (if (eq? tortoise hare)
612 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
616 (for-each1 (cdr hare) (cdr tortoise) #f)))
619 (for-each1 (cdr hare) tortoise #t)))
621 (if (not (null? hare))
622 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
626 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
628 ((and (pair? h1) (pair? h2))
631 (f (car h1) (car h2))
632 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
634 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
637 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
640 (f (car h1) (car h2))
641 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
644 (or (null? h2) (pair? h2))
645 (and (pair? h1) (null? h2)))
649 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
652 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
656 (let ((len (length l1)))
657 (let for-eachn ((rest rest))
659 (if (= (length (car rest)) len)
660 (for-eachn (cdr rest))
661 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
662 (list (car rest)) #f)))))
664 (let for-eachn ((l1 l1) (rest rest))
667 (apply f (car l1) (map car rest))
668 (for-eachn (cdr l1) (map cdr rest))))))))
674 ;;; Extensible exception printing.
677 (define set-exception-printer! #f)
678 ;; There is already a definition of print-exception from backtrace.c
679 ;; that we will override.
681 (let ((exception-printers '()))
682 (define (print-location frame port)
683 (let ((source (and=> frame frame-source)))
684 ;; source := (addr . (filename . (line . column)))
686 (let ((filename (or (cadr source) "<unnamed port>"))
687 (line (caddr source))
688 (col (cdddr source)))
689 (format port "~a:~a:~a: " filename (1+ line) col))
690 (format port "ERROR: "))))
692 (set! set-exception-printer!
694 (set! exception-printers (acons key proc exception-printers))))
696 (set! print-exception
697 (lambda (port frame key args)
698 (define (default-printer)
699 (format port "Throw to key `~a' with args `~s'." key args))
702 (let ((proc (frame-procedure frame)))
703 (print-location frame port)
704 (format port "In procedure ~a:\n"
705 (or (procedure-name proc) proc))))
707 (print-location frame port)
710 (let ((printer (assq-ref exception-printers key)))
712 (printer port key args default-printer)
715 (format port "Error while printing exception.")))
717 (force-output port))))
720 ;;; Printers for those keys thrown by Guile.
723 (define (scm-error-printer port key args default-printer)
724 ;; Abuse case-lambda as a pattern matcher, given that we don't have
725 ;; ice-9 match at this point.
727 ((subr msg args . rest)
729 (format port "In procedure ~a: " subr))
730 (apply format port msg (or args '())))
731 (_ (default-printer)))
734 (define (syntax-error-printer port key args default-printer)
736 ((who what where form subform . extra)
737 (format port "Syntax error:\n")
739 (let ((file (or (assq-ref where 'filename) "unknown file"))
740 (line (and=> (assq-ref where 'line) 1+))
741 (col (assq-ref where 'column)))
742 (format port "~a:~a:~a: " file line col))
743 (format port "unknown location: "))
745 (format port "~a: " who))
746 (format port "~a" what)
748 (format port " in subform ~s of ~s" subform form)
750 (format port " in form ~s" form))))
751 (_ (default-printer)))
754 (define (getaddrinfo-error-printer port key args default-printer)
755 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
757 (set-exception-printer! 'goops-error scm-error-printer)
758 (set-exception-printer! 'host-not-found scm-error-printer)
759 (set-exception-printer! 'keyword-argument-error scm-error-printer)
760 (set-exception-printer! 'misc-error scm-error-printer)
761 (set-exception-printer! 'no-data scm-error-printer)
762 (set-exception-printer! 'no-recovery scm-error-printer)
763 (set-exception-printer! 'null-pointer-error scm-error-printer)
764 (set-exception-printer! 'out-of-range scm-error-printer)
765 (set-exception-printer! 'program-error scm-error-printer)
766 (set-exception-printer! 'read-error scm-error-printer)
767 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
768 (set-exception-printer! 'signal scm-error-printer)
769 (set-exception-printer! 'stack-overflow scm-error-printer)
770 (set-exception-printer! 'system-error scm-error-printer)
771 (set-exception-printer! 'try-again scm-error-printer)
772 (set-exception-printer! 'unbound-variable scm-error-printer)
773 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
774 (set-exception-printer! 'wrong-type-arg scm-error-printer)
776 (set-exception-printer! 'syntax-error syntax-error-printer)
778 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
786 (define-syntax define-macro
790 ((_ (macro . args) doc body1 body ...)
791 (string? (syntax->datum #'doc))
792 #'(define-macro macro doc (lambda args body1 body ...)))
793 ((_ (macro . args) body ...)
794 #'(define-macro macro #f (lambda args body ...)))
795 ((_ macro doc transformer)
796 (or (string? (syntax->datum #'doc))
797 (not (syntax->datum #'doc)))
798 #'(define-syntax macro
801 #((macro-type . defmacro)
802 (defmacro-args args))
805 (let ((v (syntax->datum #'args)))
806 (datum->syntax y (apply transformer v)))))))))))
808 (define-syntax defmacro
810 "Define a defmacro, with the old lispy defun syntax."
812 ((_ macro args doc body1 body ...)
813 (string? (syntax->datum #'doc))
814 #'(define-macro macro doc (lambda args body1 body ...)))
815 ((_ macro args body ...)
816 #'(define-macro macro #f (lambda args body ...))))))
825 (define-syntax begin-deprecated
829 (if (include-deprecated-features)
830 #'(begin form form* ...)
835 ;;; {Trivial Functions}
838 (define (identity x) x)
840 (define (compose proc . rest)
841 "Compose PROC with the procedures in REST, such that the last one in
842 REST is applied first and PROC last, and return the resulting procedure.
843 The given procedures must have compatible arity."
846 (let ((g (apply compose rest)))
848 (call-with-values (lambda () (apply g args)) proc)))))
850 (define (negate proc)
851 "Return a procedure with the same arity as PROC that returns the `not'
854 (not (apply proc args))))
856 (define (const value)
857 "Return a procedure that accepts any number of arguments and returns
862 (define (and=> value procedure) (and value (procedure value)))
863 (define call/cc call-with-current-continuation)
865 (define-syntax-rule (false-if-exception expr)
868 (lambda (k . args) #f)))
872 ;;; {General Properties}
875 ;; Properties are a lispy way to associate random info with random objects.
876 ;; Traditionally properties are implemented as an alist or a plist actually
877 ;; pertaining to the object in question.
879 ;; These "object properties" have the advantage that they can be associated with
880 ;; any object, even if the object has no plist. Object properties are good when
881 ;; you are extending pre-existing objects in unexpected ways. They also present
882 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
883 ;; type that always has properties, it's often still best to store those
884 ;; properties within the object itself.
886 (define (make-object-property)
887 (define-syntax-rule (with-mutex lock exp)
888 (dynamic-wind (lambda () (lock-mutex lock))
890 (lambda () (unlock-mutex lock))))
891 (let ((prop (make-weak-key-hash-table))
893 (make-procedure-with-setter
894 (lambda (obj) (with-mutex lock (hashq-ref prop obj)))
895 (lambda (obj val) (with-mutex lock (hashq-set! prop obj val))))))
900 ;;; {Symbol Properties}
903 ;;; Symbol properties are something you see in old Lisp code. In most current
904 ;;; Guile code, symbols are not used as a data structure -- they are used as
905 ;;; keys into other data structures.
907 (define (symbol-property sym prop)
908 (let ((pair (assoc prop (symbol-pref sym))))
909 (and pair (cdr pair))))
911 (define (set-symbol-property! sym prop val)
912 (let ((pair (assoc prop (symbol-pref sym))))
915 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
917 (define (symbol-property-remove! sym prop)
918 (let ((pair (assoc prop (symbol-pref sym))))
920 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
927 (define (array-shape a)
928 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
929 (array-dimensions a)))
936 ;;; It's much better if you can use lambda* / define*, of course.
938 (define (kw-arg-ref args kw)
939 (let ((rem (member kw args)))
940 (and rem (pair? (cdr rem)) (cadr rem))))
947 (define (struct-layout s)
948 (struct-ref (struct-vtable s) vtable-index-layout))
955 ;; Printing records: by default, records are printed as
957 ;; #<type-name field1: val1 field2: val2 ...>
959 ;; You can change that by giving a custom printing function to
960 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
961 ;; will be called like
963 ;; (<printer> object port)
965 ;; It should print OBJECT to PORT.
967 (define (inherit-print-state old-port new-port)
968 (if (get-print-state old-port)
969 (port-with-print-state new-port (get-print-state old-port))
972 ;; 0: type-name, 1: fields, 2: constructor
973 (define record-type-vtable
974 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
975 ;; that we need to expose the bare vtable-vtable to Scheme.
976 (make-vtable-vtable "prprpw" 0
978 (cond ((eq? s record-type-vtable)
979 (display "#<record-type-vtable>" p))
981 (display "#<record-type " p)
982 (display (record-type-name s) p)
985 (define (record-type? obj)
986 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
988 (define* (make-record-type type-name fields #:optional printer)
989 ;; Pre-generate constructors for nfields < 20.
990 (define-syntax make-constructor
992 (define *max-static-argument-count* 20)
993 (define (make-formals n)
999 (string (integer->char (+ (char->integer #\a) i)))))
1003 ((_ rtd exp) (not (identifier? #'exp))
1005 (make-constructor rtd n)))
1009 (if (< n *max-static-argument-count*)
1010 (cons (with-syntax (((formal ...) (make-formals n))
1013 (lambda (formal ...)
1014 (make-struct rtd 0 formal ...))))
1019 (if (= (length args) nfields)
1020 (apply make-struct rtd 0 args)
1021 (scm-error 'wrong-number-of-args
1022 (format #f "make-~a" type-name)
1023 "Wrong number of arguments" '() #f)))))))))
1025 (define (default-record-printer s p)
1027 (display (record-type-name (record-type-descriptor s)) p)
1028 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1031 ((not (null? fields))
1033 (display (car fields) p)
1035 (display (struct-ref s off) p)
1036 (loop (cdr fields) (+ 1 off)))))
1039 (let ((rtd (make-struct record-type-vtable 0
1041 (apply string-append
1042 (map (lambda (f) "pw") fields)))
1043 (or printer default-record-printer)
1045 (copy-tree fields))))
1046 (struct-set! rtd (+ vtable-offset-user 2)
1047 (make-constructor rtd (length fields)))
1048 ;; Temporary solution: Associate a name to the record type descriptor
1049 ;; so that the object system can create a wrapper class for it.
1050 (set-struct-vtable-name! rtd (if (symbol? type-name)
1052 (string->symbol type-name)))
1055 (define (record-type-name obj)
1056 (if (record-type? obj)
1057 (struct-ref obj vtable-offset-user)
1058 (error 'not-a-record-type obj)))
1060 (define (record-type-fields obj)
1061 (if (record-type? obj)
1062 (struct-ref obj (+ 1 vtable-offset-user))
1063 (error 'not-a-record-type obj)))
1065 (define* (record-constructor rtd #:optional field-names)
1066 (if (not field-names)
1067 (struct-ref rtd (+ 2 vtable-offset-user))
1069 `(lambda ,field-names
1070 (make-struct ',rtd 0 ,@(map (lambda (f)
1071 (if (memq f field-names)
1074 (record-type-fields rtd)))))))
1076 (define (record-predicate rtd)
1077 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1079 (define (%record-type-error rtd obj) ;; private helper
1080 (or (eq? rtd (record-type-descriptor obj))
1081 (scm-error 'wrong-type-arg "%record-type-check"
1082 "Wrong type record (want `~S'): ~S"
1083 (list (record-type-name rtd) obj)
1086 (define (record-accessor rtd field-name)
1087 (let ((pos (list-index (record-type-fields rtd) field-name)))
1089 (error 'no-such-field field-name))
1091 (if (eq? (struct-vtable obj) rtd)
1092 (struct-ref obj pos)
1093 (%record-type-error rtd obj)))))
1095 (define (record-modifier rtd field-name)
1096 (let ((pos (list-index (record-type-fields rtd) field-name)))
1098 (error 'no-such-field field-name))
1100 (if (eq? (struct-vtable obj) rtd)
1101 (struct-set! obj pos val)
1102 (%record-type-error rtd obj)))))
1104 (define (record? obj)
1105 (and (struct? obj) (record-type? (struct-vtable obj))))
1107 (define (record-type-descriptor obj)
1110 (error 'not-a-record obj)))
1119 (define (->bool x) (not (not x)))
1126 (define (symbol-append . args)
1127 (string->symbol (apply string-append (map symbol->string args))))
1129 (define (list->symbol . args)
1130 (string->symbol (apply list->string args)))
1132 (define (symbol . args)
1133 (string->symbol (apply string args)))
1140 (define (list-index l k)
1143 (and (not (null? l))
1146 (loop (+ n 1) (cdr l))))))
1150 ;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1151 ;; `stat' accessors.
1152 (primitive-load-path "ice-9/posix")
1154 (if (provided? 'socket)
1155 (primitive-load-path "ice-9/networking"))
1157 ;; For reference, Emacs file-exists-p uses stat in this same way.
1158 (define file-exists?
1159 (if (provided? 'posix)
1161 (->bool (stat str #f)))
1163 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
1165 (if port (begin (close-port port) #t)
1168 (define file-is-directory?
1169 (if (provided? 'posix)
1171 (eq? (stat:type (stat str)) 'directory))
1173 (let ((port (catch 'system-error
1174 (lambda () (open-file (string-append str "/.")
1177 (if port (begin (close-port port) #t)
1180 (define (system-error-errno args)
1181 (if (eq? (car args) 'system-error)
1182 (car (list-ref args 4))
1187 ;;; {Error Handling}
1193 (scm-error 'misc-error #f "?" #f #f))
1195 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1196 (scm-error 'misc-error #f msg (cons message args) #f)))))
1200 ;;; {Time Structures}
1203 (define (tm:sec obj) (vector-ref obj 0))
1204 (define (tm:min obj) (vector-ref obj 1))
1205 (define (tm:hour obj) (vector-ref obj 2))
1206 (define (tm:mday obj) (vector-ref obj 3))
1207 (define (tm:mon obj) (vector-ref obj 4))
1208 (define (tm:year obj) (vector-ref obj 5))
1209 (define (tm:wday obj) (vector-ref obj 6))
1210 (define (tm:yday obj) (vector-ref obj 7))
1211 (define (tm:isdst obj) (vector-ref obj 8))
1212 (define (tm:gmtoff obj) (vector-ref obj 9))
1213 (define (tm:zone obj) (vector-ref obj 10))
1215 (define (set-tm:sec obj val) (vector-set! obj 0 val))
1216 (define (set-tm:min obj val) (vector-set! obj 1 val))
1217 (define (set-tm:hour obj val) (vector-set! obj 2 val))
1218 (define (set-tm:mday obj val) (vector-set! obj 3 val))
1219 (define (set-tm:mon obj val) (vector-set! obj 4 val))
1220 (define (set-tm:year obj val) (vector-set! obj 5 val))
1221 (define (set-tm:wday obj val) (vector-set! obj 6 val))
1222 (define (set-tm:yday obj val) (vector-set! obj 7 val))
1223 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
1224 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1225 (define (set-tm:zone obj val) (vector-set! obj 10 val))
1227 (define (tms:clock obj) (vector-ref obj 0))
1228 (define (tms:utime obj) (vector-ref obj 1))
1229 (define (tms:stime obj) (vector-ref obj 2))
1230 (define (tms:cutime obj) (vector-ref obj 3))
1231 (define (tms:cstime obj) (vector-ref obj 4))
1235 ;;; {File Descriptors and Ports}
1238 (define file-position ftell)
1239 (define* (file-set-position port offset #:optional (whence SEEK_SET))
1240 (seek port offset whence))
1242 (define (move->fdes fd/port fd)
1243 (cond ((integer? fd/port)
1244 (dup->fdes fd/port fd)
1248 (primitive-move->fdes fd/port fd)
1249 (set-port-revealed! fd/port 1)
1252 (define (release-port-handle port)
1253 (let ((revealed (port-revealed port)))
1255 (set-port-revealed! port (- revealed 1)))))
1260 (fdopen (dup->fdes port/fd) mode))
1261 ((port/fd mode new-fd)
1262 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1263 (set-port-revealed! port 1)
1269 (dup->port port/fd "r"))
1271 (dup->port port/fd "r" new-fd))))
1273 (define dup->outport
1276 (dup->port port/fd "w"))
1278 (dup->port port/fd "w" new-fd))))
1283 (if (integer? port/fd)
1285 (dup->port port/fd (port-mode port/fd))))
1287 (if (integer? port/fd)
1288 (dup->fdes port/fd new-fd)
1289 (dup->port port/fd (port-mode port/fd) new-fd)))))
1291 (define (duplicate-port port modes)
1292 (dup->port port modes))
1294 (define (fdes->inport fdes)
1295 (let loop ((rest-ports (fdes->ports fdes)))
1296 (cond ((null? rest-ports)
1297 (let ((result (fdopen fdes "r")))
1298 (set-port-revealed! result 1)
1300 ((input-port? (car rest-ports))
1301 (set-port-revealed! (car rest-ports)
1302 (+ (port-revealed (car rest-ports)) 1))
1305 (loop (cdr rest-ports))))))
1307 (define (fdes->outport fdes)
1308 (let loop ((rest-ports (fdes->ports fdes)))
1309 (cond ((null? rest-ports)
1310 (let ((result (fdopen fdes "w")))
1311 (set-port-revealed! result 1)
1313 ((output-port? (car rest-ports))
1314 (set-port-revealed! (car rest-ports)
1315 (+ (port-revealed (car rest-ports)) 1))
1318 (loop (cdr rest-ports))))))
1320 (define (port->fdes port)
1321 (set-port-revealed! port (+ (port-revealed port) 1))
1324 (define (setenv name value)
1326 (putenv (string-append name "=" value))
1329 (define (unsetenv name)
1330 "Remove the entry for NAME from the environment."
1338 (define (in-vicinity vicinity file)
1339 (let ((tail (let ((len (string-length vicinity)))
1342 (string-ref vicinity (- len 1))))))
1343 (string-append vicinity
1352 ;;; {Help for scm_shell}
1354 ;;; The argument-processing code used by Guile-based shells generates
1355 ;;; Scheme code based on the argument list. This page contains help
1356 ;;; functions for the code it generates.
1359 (define (command-line) (program-arguments))
1361 ;; This is mostly for the internal use of the code generated by
1362 ;; scm_compile_shell_switches.
1364 (define (load-user-init)
1365 (let* ((home (or (getenv "HOME")
1366 (false-if-exception (passwd:dir (getpwuid (getuid))))
1367 "/")) ;; fallback for cygwin etc.
1368 (init-file (in-vicinity home ".guile")))
1369 (if (file-exists? init-file)
1370 (primitive-load init-file))))
1374 ;;; {The interpreter stack}
1377 ;; %stacks defined in stacks.c
1378 (define (%start-stack tag thunk)
1379 (let ((prompt-tag (make-prompt-tag "start-stack")))
1383 (with-fluids ((%stacks (acons tag prompt-tag
1384 (or (fluid-ref %stacks) '()))))
1387 (%start-stack tag (lambda () (apply k args)))))))
1389 (define-syntax-rule (start-stack tag exp)
1390 (%start-stack tag (lambda () exp)))
1394 ;;; {Loading by paths}
1397 ;;; Load a Scheme source file named NAME, searching for it in the
1398 ;;; directories listed in %load-path, and applying each of the file
1399 ;;; name extensions listed in %load-extensions.
1400 (define (load-from-path name)
1401 (start-stack 'load-stack
1402 (primitive-load-path name)))
1404 (define-syntax-rule (add-to-load-path elt)
1405 "Add ELT to Guile's load path, at compile-time and at run-time."
1406 (eval-when (compile load eval)
1407 (set! %load-path (cons elt %load-path))))
1409 (define %load-verbosely #f)
1410 (define (assert-load-verbosity v) (set! %load-verbosely v))
1412 (define (%load-announce file)
1414 (with-output-to-port (current-warning-port)
1417 (display "loading ")
1422 (set! %load-hook %load-announce)
1426 ;;; {Reader Extensions}
1428 ;;; Reader code for various "#c" forms.
1431 (define read-eval? (make-fluid #f))
1432 (read-hash-extend #\.
1434 (if (fluid-ref read-eval?)
1435 (eval (read port) (interaction-environment))
1437 "#. read expansion found and read-eval? is #f."))))
1441 ;;; {Low Level Modules}
1443 ;;; These are the low level data structures for modules.
1445 ;;; Every module object is of the type 'module-type', which is a record
1446 ;;; consisting of the following members:
1448 ;;; - eval-closure: the function that defines for its module the strategy that
1449 ;;; shall be followed when looking up symbols in the module.
1451 ;;; An eval-closure is a function taking two arguments: the symbol to be
1452 ;;; looked up and a boolean value telling whether a binding for the symbol
1453 ;;; should be created if it does not exist yet. If the symbol lookup
1454 ;;; succeeded (either because an existing binding was found or because a new
1455 ;;; binding was created), a variable object representing the binding is
1456 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1457 ;;; closure does not take the module to be searched as an argument: During
1458 ;;; construction of the eval-closure, the eval-closure has to store the
1459 ;;; module it belongs to in its environment. This means, that any
1460 ;;; eval-closure can belong to only one module.
1462 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1463 ;;; special cases of eval-closures are to be distinguished: During startup
1464 ;;; the module system is not yet activated. In this phase, no modules are
1465 ;;; defined and all bindings are automatically stored by the system in the
1466 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1467 ;;; functions which require an eval-closure as their argument need to be
1468 ;;; passed the value #f.
1470 ;;; The other two special cases of eval-closures are the
1471 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1472 ;;; behave equally for the case that no new binding is to be created. The
1473 ;;; difference between the two comes in, when the boolean argument to the
1474 ;;; eval-closure indicates that a new binding shall be created if it is not
1477 ;;; Given that no new binding shall be created, both standard eval-closures
1478 ;;; define the following standard strategy of searching bindings in the
1479 ;;; module: First, the module's obarray is searched for the symbol. Second,
1480 ;;; if no binding for the symbol was found in the module's obarray, the
1481 ;;; module's binder procedure is exececuted. If this procedure did not
1482 ;;; return a binding for the symbol, the modules referenced in the module's
1483 ;;; uses list are recursively searched for a binding of the symbol. If the
1484 ;;; binding can not be found in these modules also, the symbol lookup has
1487 ;;; If a new binding shall be created, the standard-interface-eval-closure
1488 ;;; immediately returns indicating failure. That is, it does not even try
1489 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1490 ;;; first search the obarray, and if no binding was found there, would
1491 ;;; create a new binding in the obarray, therefore not calling the binder
1492 ;;; procedure or searching the modules in the uses list.
1494 ;;; The explanation of the following members obarray, binder and uses
1495 ;;; assumes that the symbol lookup follows the strategy that is defined in
1496 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1498 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1499 ;;; hash table, the definitions are found that are local to the module (that
1500 ;;; is, not imported from other modules). When looking up bindings in the
1501 ;;; module, this hash table is searched first.
1503 ;;; - binder: either #f or a function taking a module and a symbol argument.
1504 ;;; If it is a function it is called after the obarray has been
1505 ;;; unsuccessfully searched for a binding. It then can provide bindings
1506 ;;; that would otherwise not be found locally in the module.
1508 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1509 ;;; These modules are the third place queried for bindings after the obarray
1510 ;;; has been unsuccessfully searched and the binder function did not deliver
1511 ;;; a result either.
1513 ;;; - transformer: either #f or a function taking a scheme expression as
1514 ;;; delivered by read. If it is a function, it will be called to perform
1515 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1516 ;;; expression. The output of the transformer function will then be passed
1517 ;;; to Guile's internal memoizer. This means that the output must be valid
1518 ;;; scheme code. The only exception is, that the output may make use of the
1519 ;;; syntax extensions provided to identify the modules that a binding
1522 ;;; - name: the name of the module. This is used for all kinds of printing
1523 ;;; outputs. In certain places the module name also serves as a way of
1524 ;;; identification. When adding a module to the uses list of another
1525 ;;; module, it is made sure that the new uses list will not contain two
1526 ;;; modules of the same name.
1528 ;;; - kind: classification of the kind of module. The value is (currently?)
1529 ;;; only used for printing. It has no influence on how a module is treated.
1530 ;;; Currently the following values are used when setting the module kind:
1531 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1532 ;;; is set, it defaults to 'module.
1534 ;;; - duplicates-handlers: a list of procedures that get called to make a
1535 ;;; choice between two duplicate bindings when name clashes occur. See the
1536 ;;; `duplicate-handlers' global variable below.
1538 ;;; - observers: a list of procedures that get called when the module is
1541 ;;; - weak-observers: a weak-key hash table of procedures that get called
1542 ;;; when the module is modified. See `module-observe-weak' for details.
1544 ;;; In addition, the module may (must?) contain a binding for
1545 ;;; `%module-public-interface'. This variable should be bound to a module
1546 ;;; representing the exported interface of a module. See the
1547 ;;; `module-public-interface' and `module-export!' procedures.
1549 ;;; !!! warning: The interface to lazy binder procedures is going
1550 ;;; to be changed in an incompatible way to permit all the basic
1551 ;;; module ops to be virtualized.
1553 ;;; (make-module size use-list lazy-binding-proc) => module
1554 ;;; module-{obarray,uses,binder}[|-set!]
1555 ;;; (module? obj) => [#t|#f]
1556 ;;; (module-locally-bound? module symbol) => [#t|#f]
1557 ;;; (module-bound? module symbol) => [#t|#f]
1558 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1559 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1560 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1561 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1562 ;;; (module-symbol-binding module symbol opt-value)
1563 ;;; => [ <obj> | opt-value | an error occurs ]
1564 ;;; (module-make-local-var! module symbol) => #<variable...>
1565 ;;; (module-add! module symbol var) => unspecified
1566 ;;; (module-remove! module symbol) => unspecified
1567 ;;; (module-for-each proc module) => unspecified
1568 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1569 ;;; (set-current-module module) => unspecified
1570 ;;; (current-module) => #<module...>
1576 ;;; {Printing Modules}
1579 ;; This is how modules are printed. You can re-define it.
1580 (define (%print-module mod port)
1582 (display (or (module-kind mod) "module") port)
1584 (display (module-name mod) port)
1586 (display (number->string (object-address mod) 16) port)
1590 ;; Locally extend the syntax to allow record accessors to be defined at
1591 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1592 ;; the setters, in order to allow for redefinition of the record type; not
1593 ;; relevant in the case of modules, but perhaps if we make this public, it
1596 ((define-record-type
1598 (define (make-id scope . fragments)
1599 (datum->syntax #'scope
1600 (apply symbol-append
1602 (if (symbol? x) x (syntax->datum x)))
1605 (define (getter rtd type-name field slot)
1606 #`(define #,(make-id rtd type-name '- field)
1608 (lambda (#,type-name)
1609 (if (eq? (struct-vtable #,type-name) rtd)
1610 (struct-ref #,type-name #,slot)
1611 (%record-type-error rtd #,type-name))))))
1613 (define (setter rtd type-name field slot)
1614 #`(define #,(make-id rtd 'set- type-name '- field '!)
1616 (lambda (#,type-name val)
1617 (if (eq? (struct-vtable #,type-name) rtd)
1618 (struct-set! #,type-name #,slot val)
1619 (%record-type-error rtd #,type-name))))))
1621 (define (accessors rtd type-name fields n exp)
1622 (syntax-case fields ()
1624 (((field #:no-accessors) field* ...) (identifier? #'field)
1625 (accessors rtd type-name #'(field* ...) (1+ n)
1627 (((field #:no-setter) field* ...) (identifier? #'field)
1628 (accessors rtd type-name #'(field* ...) (1+ n)
1630 #,(getter rtd type-name #'field n))))
1631 (((field #:no-getter) field* ...) (identifier? #'field)
1632 (accessors rtd type-name #'(field* ...) (1+ n)
1634 #,(setter rtd type-name #'field n))))
1635 ((field field* ...) (identifier? #'field)
1636 (accessors rtd type-name #'(field* ...) (1+ n)
1638 #,(getter rtd type-name #'field n)
1639 #,(setter rtd type-name #'field n))))))
1641 (define (predicate rtd type-name fields exp)
1643 rtd type-name fields 0
1646 (define (#,(make-id rtd type-name '?) obj)
1647 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1649 (define (field-list fields)
1650 (syntax-case fields ()
1652 (((f . opts) . rest) (identifier? #'f)
1653 (cons #'f (field-list #'rest)))
1654 ((f . rest) (identifier? #'f)
1655 (cons #'f (field-list #'rest)))))
1657 (define (constructor rtd type-name fields exp)
1658 (let ((ctor (make-id rtd type-name '-constructor))
1659 (args (field-list fields)))
1660 (predicate rtd type-name fields
1665 (make-struct rtd 0 #,@args))))
1666 (struct-set! #,rtd (+ vtable-offset-user 2)
1669 (define (type type-name printer fields)
1670 (define (make-layout)
1671 (let lp ((fields fields) (slots '()))
1672 (syntax-case fields ()
1673 (() (datum->syntax #'here
1675 (apply string-append slots))))
1676 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1678 (let ((rtd (make-id type-name type-name '-type)))
1679 (constructor rtd type-name fields
1682 (make-struct record-type-vtable 0
1686 '#,(field-list fields)))
1687 (set-struct-vtable-name! #,rtd '#,type-name)))))
1690 ((_ type-name printer (field ...))
1691 (type #'type-name #'printer #'(field ...)))))))
1695 ;; A module is characterized by an obarray in which local symbols
1696 ;; are interned, a list of modules, "uses", from which non-local
1697 ;; bindings can be inherited, and an optional lazy-binder which
1698 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1699 ;; bindings that would otherwise not be found locally in the module.
1701 ;; NOTE: If you change the set of fields or their order, you also need to
1702 ;; change the constants in libguile/modules.h.
1704 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1705 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1706 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1707 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1709 (define-record-type module
1710 (lambda (obj port) (%print-module obj port))
1715 (transformer #:no-getter)
1719 (import-obarray #:no-setter)
1721 (weak-observers #:no-setter)
1729 ;; make-module &opt size uses binder
1731 ;; Create a new module, perhaps with a particular size of obarray,
1732 ;; initial uses list, or binding procedure.
1734 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
1735 (define %default-import-size
1736 ;; Typical number of imported bindings actually used by a module.
1739 (if (not (integer? size))
1740 (error "Illegal size to make-module." size))
1741 (if (not (and (list? uses)
1742 (and-map module? uses)))
1743 (error "Incorrect use list." uses))
1744 (if (and binder (not (procedure? binder)))
1746 "Lazy-binder expected to be a procedure or #f." binder))
1748 (let ((module (module-constructor (make-hash-table size)
1749 uses binder #f macroexpand
1751 (make-hash-table %default-import-size)
1753 (make-weak-key-hash-table 31) #f
1754 (make-hash-table 7) #f #f #f)))
1756 ;; We can't pass this as an argument to module-constructor,
1757 ;; because we need it to close over a pointer to the module
1759 (set-module-eval-closure! module (standard-eval-closure module))
1766 ;;; {Observer protocol}
1769 (define (module-observe module proc)
1770 (set-module-observers! module (cons proc (module-observers module)))
1773 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1774 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1775 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1776 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1777 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1780 ;; The two-argument version is kept for backward compatibility: when called
1781 ;; with two arguments, the observer gets unregistered when closure PROC
1782 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1783 (hashq-set! (module-weak-observers module) observer-id proc))
1785 (define (module-unobserve token)
1786 (let ((module (car token))
1789 (hash-remove! (module-weak-observers module) id)
1790 (set-module-observers! module (delq1! id (module-observers module)))))
1793 (define module-defer-observers #f)
1794 (define module-defer-observers-mutex (make-mutex 'recursive))
1795 (define module-defer-observers-table (make-hash-table))
1797 (define (module-modified m)
1798 (if module-defer-observers
1799 (hash-set! module-defer-observers-table m #t)
1800 (module-call-observers m)))
1802 ;;; This function can be used to delay calls to observers so that they
1803 ;;; can be called once only in the face of massive updating of modules.
1805 (define (call-with-deferred-observers thunk)
1808 (lock-mutex module-defer-observers-mutex)
1809 (set! module-defer-observers #t))
1812 (set! module-defer-observers #f)
1813 (hash-for-each (lambda (m dummy)
1814 (module-call-observers m))
1815 module-defer-observers-table)
1816 (hash-clear! module-defer-observers-table)
1817 (unlock-mutex module-defer-observers-mutex))))
1819 (define (module-call-observers m)
1820 (for-each (lambda (proc) (proc m)) (module-observers m))
1822 ;; We assume that weak observers don't (un)register themselves as they are
1823 ;; called since this would preclude proper iteration over the hash table
1825 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1829 ;;; {Module Searching in General}
1831 ;;; We sometimes want to look for properties of a symbol
1832 ;;; just within the obarray of one module. If the property
1833 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1834 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1837 ;;; Other times, we want to test for a symbol property in the obarray
1838 ;;; of M and, if it is not found there, try each of the modules in the
1839 ;;; uses list of M. This is the normal way of testing for some
1840 ;;; property, so we state these properties without qualification as
1841 ;;; in: ``The symbol 'fnord is interned in module M because it is
1842 ;;; interned locally in module M2 which is a member of the uses list
1846 ;; module-search fn m
1848 ;; return the first non-#f result of FN applied to M and then to
1849 ;; the modules in the uses of m, and so on recursively. If all applications
1850 ;; return #f, then so does this function.
1852 (define (module-search fn m v)
1855 (or (module-search fn (car pos) v)
1858 (loop (module-uses m))))
1861 ;;; {Is a symbol bound in a module?}
1863 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1864 ;;; of S in M has been set to some well-defined value.
1867 ;; module-locally-bound? module symbol
1869 ;; Is a symbol bound (interned and defined) locally in a given module?
1871 (define (module-locally-bound? m v)
1872 (let ((var (module-local-variable m v)))
1874 (variable-bound? var))))
1876 ;; module-bound? module symbol
1878 ;; Is a symbol bound (interned and defined) anywhere in a given module
1881 (define (module-bound? m v)
1882 (let ((var (module-variable m v)))
1884 (variable-bound? var))))
1886 ;;; {Is a symbol interned in a module?}
1888 ;;; Symbol S in Module M is interned if S occurs in
1889 ;;; of S in M has been set to some well-defined value.
1891 ;;; It is possible to intern a symbol in a module without providing
1892 ;;; an initial binding for the corresponding variable. This is done
1894 ;;; (module-add! module symbol (make-undefined-variable))
1896 ;;; In that case, the symbol is interned in the module, but not
1897 ;;; bound there. The unbound symbol shadows any binding for that
1898 ;;; symbol that might otherwise be inherited from a member of the uses list.
1901 (define (module-obarray-get-handle ob key)
1902 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1904 (define (module-obarray-ref ob key)
1905 ((if (symbol? key) hashq-ref hash-ref) ob key))
1907 (define (module-obarray-set! ob key val)
1908 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1910 (define (module-obarray-remove! ob key)
1911 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1913 ;; module-symbol-locally-interned? module symbol
1915 ;; is a symbol interned (not neccessarily defined) locally in a given module
1916 ;; or its uses? Interned symbols shadow inherited bindings even if
1917 ;; they are not themselves bound to a defined value.
1919 (define (module-symbol-locally-interned? m v)
1920 (not (not (module-obarray-get-handle (module-obarray m) v))))
1922 ;; module-symbol-interned? module symbol
1924 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1925 ;; or its uses? Interned symbols shadow inherited bindings even if
1926 ;; they are not themselves bound to a defined value.
1928 (define (module-symbol-interned? m v)
1929 (module-search module-symbol-locally-interned? m v))
1932 ;;; {Mapping modules x symbols --> variables}
1935 ;; module-local-variable module symbol
1936 ;; return the local variable associated with a MODULE and SYMBOL.
1938 ;;; This function is very important. It is the only function that can
1939 ;;; return a variable from a module other than the mutators that store
1940 ;;; new variables in modules. Therefore, this function is the location
1941 ;;; of the "lazy binder" hack.
1943 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1944 ;;; to a variable, return that variable object.
1946 ;;; If the symbols is not found at first, but the module has a lazy binder,
1947 ;;; then try the binder.
1949 ;;; If the symbol is not found at all, return #f.
1951 ;;; (This is now written in C, see `modules.c'.)
1954 ;;; {Mapping modules x symbols --> bindings}
1956 ;;; These are similar to the mapping to variables, except that the
1957 ;;; variable is dereferenced.
1960 ;; module-symbol-binding module symbol opt-value
1962 ;; return the binding of a variable specified by name within
1963 ;; a given module, signalling an error if the variable is unbound.
1964 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1965 ;; return OPT-VALUE.
1967 (define (module-symbol-local-binding m v . opt-val)
1968 (let ((var (module-local-variable m v)))
1969 (if (and var (variable-bound? var))
1971 (if (not (null? opt-val))
1973 (error "Locally unbound variable." v)))))
1975 ;; module-symbol-binding module symbol opt-value
1977 ;; return the binding of a variable specified by name within
1978 ;; a given module, signalling an error if the variable is unbound.
1979 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1980 ;; return OPT-VALUE.
1982 (define (module-symbol-binding m v . opt-val)
1983 (let ((var (module-variable m v)))
1984 (if (and var (variable-bound? var))
1986 (if (not (null? opt-val))
1988 (error "Unbound variable." v)))))
1993 ;;; {Adding Variables to Modules}
1996 ;; module-make-local-var! module symbol
1998 ;; ensure a variable for V in the local namespace of M.
1999 ;; If no variable was already there, then create a new and uninitialzied
2002 ;; This function is used in modules.c.
2004 (define (module-make-local-var! m v)
2005 (or (let ((b (module-obarray-ref (module-obarray m) v)))
2008 ;; Mark as modified since this function is called when
2009 ;; the standard eval closure defines a binding
2013 ;; Create a new local variable.
2014 (let ((local-var (make-undefined-variable)))
2015 (module-add! m v local-var)
2018 ;; module-ensure-local-variable! module symbol
2020 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
2021 ;; there is no binding for SYMBOL, create a new uninitialized
2022 ;; variable. Return the local variable.
2024 (define (module-ensure-local-variable! module symbol)
2025 (or (module-local-variable module symbol)
2026 (let ((var (make-undefined-variable)))
2027 (module-add! module symbol var)
2030 ;; module-add! module symbol var
2032 ;; ensure a particular variable for V in the local namespace of M.
2034 (define (module-add! m v var)
2035 (if (not (variable? var))
2036 (error "Bad variable to module-add!" var))
2037 (module-obarray-set! (module-obarray m) v var)
2038 (module-modified m))
2042 ;; make sure that a symbol is undefined in the local namespace of M.
2044 (define (module-remove! m v)
2045 (module-obarray-remove! (module-obarray m) v)
2046 (module-modified m))
2048 (define (module-clear! m)
2049 (hash-clear! (module-obarray m))
2050 (module-modified m))
2052 ;; MODULE-FOR-EACH -- exported
2054 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2056 (define (module-for-each proc module)
2057 (hash-for-each proc (module-obarray module)))
2059 (define (module-map proc module)
2060 (hash-map->list proc (module-obarray module)))
2064 ;; Modules exist in a separate namespace from values, because you generally do
2065 ;; not want the name of a submodule, which you might not even use, to collide
2066 ;; with local variables that happen to be named the same as the submodule.
2068 (define (module-ref-submodule module name)
2069 (or (hashq-ref (module-submodules module) name)
2070 (and (module-submodule-binder module)
2071 ((module-submodule-binder module) module name))))
2073 (define (module-define-submodule! module name submodule)
2074 (hashq-set! (module-submodules module) name submodule))
2076 ;; It used to be, however, that module names were also present in the
2077 ;; value namespace. When we enable deprecated code, we preserve this
2080 ;; These shims are defined here instead of in deprecated.scm because we
2081 ;; need their definitions before loading other modules.
2084 (define (module-ref-submodule module name)
2085 (or (hashq-ref (module-submodules module) name)
2086 (and (module-submodule-binder module)
2087 ((module-submodule-binder module) module name))
2088 (let ((var (module-local-variable module name)))
2089 (and var (variable-bound? var) (module? (variable-ref var))
2091 (warn "module" module "not in submodules table")
2092 (variable-ref var))))))
2094 (define (module-define-submodule! module name submodule)
2095 (let ((var (module-local-variable module name)))
2097 (or (not (variable-bound? var))
2098 (not (module? (variable-ref var)))))
2099 (warn "defining module" module ": not overriding local definition" var)
2100 (module-define! module name submodule)))
2101 (hashq-set! (module-submodules module) name submodule)))
2105 ;;; {Module-based Loading}
2108 (define (save-module-excursion thunk)
2109 (let ((inner-module (current-module))
2111 (dynamic-wind (lambda ()
2112 (set! outer-module (current-module))
2113 (set-current-module inner-module)
2114 (set! inner-module #f))
2117 (set! inner-module (current-module))
2118 (set-current-module outer-module)
2119 (set! outer-module #f)))))
2123 ;;; {MODULE-REF -- exported}
2126 ;; Returns the value of a variable called NAME in MODULE or any of its
2127 ;; used modules. If there is no such variable, then if the optional third
2128 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2130 (define (module-ref module name . rest)
2131 (let ((variable (module-variable module name)))
2132 (if (and variable (variable-bound? variable))
2133 (variable-ref variable)
2135 (error "No variable named" name 'in module)
2136 (car rest) ; default value
2139 ;; MODULE-SET! -- exported
2141 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2142 ;; to VALUE; if there is no such variable, an error is signaled.
2144 (define (module-set! module name value)
2145 (let ((variable (module-variable module name)))
2147 (variable-set! variable value)
2148 (error "No variable named" name 'in module))))
2150 ;; MODULE-DEFINE! -- exported
2152 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2153 ;; variable, it is added first.
2155 (define (module-define! module name value)
2156 (let ((variable (module-local-variable module name)))
2159 (variable-set! variable value)
2160 (module-modified module))
2161 (let ((variable (make-variable value)))
2162 (module-add! module name variable)))))
2164 ;; MODULE-DEFINED? -- exported
2166 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2169 (define (module-defined? module name)
2170 (let ((variable (module-variable module name)))
2171 (and variable (variable-bound? variable))))
2173 ;; MODULE-USE! module interface
2175 ;; Add INTERFACE to the list of interfaces used by MODULE.
2177 (define (module-use! module interface)
2178 (if (not (or (eq? module interface)
2179 (memq interface (module-uses module))))
2181 ;; Newly used modules must be appended rather than consed, so that
2182 ;; `module-variable' traverses the use list starting from the first
2184 (set-module-uses! module (append (module-uses module)
2186 (hash-clear! (module-import-obarray module))
2187 (module-modified module))))
2189 ;; MODULE-USE-INTERFACES! module interfaces
2191 ;; Same as MODULE-USE!, but only notifies module observers after all
2192 ;; interfaces are added to the inports list.
2194 (define (module-use-interfaces! module interfaces)
2195 (let* ((cur (module-uses module))
2196 (new (let lp ((in interfaces) (out '()))
2200 (let ((iface (car in)))
2201 (if (or (memq iface cur) (memq iface out))
2203 (cons iface out))))))))
2204 (set-module-uses! module (append cur new))
2205 (hash-clear! (module-import-obarray module))
2206 (module-modified module)))
2210 ;;; {Recursive Namespaces}
2212 ;;; A hierarchical namespace emerges if we consider some module to be
2213 ;;; root, and submodules of that module to be nested namespaces.
2215 ;;; The routines here manage variable names in hierarchical namespace.
2216 ;;; Each variable name is a list of elements, looked up in successively nested
2219 ;;; (nested-ref some-root-module '(foo bar baz))
2220 ;;; => <value of a variable named baz in the submodule bar of
2221 ;;; the submodule foo of some-root-module>
2226 ;;; ;; a-root is a module
2227 ;;; ;; name is a list of symbols
2229 ;;; nested-ref a-root name
2230 ;;; nested-set! a-root name val
2231 ;;; nested-define! a-root name val
2232 ;;; nested-remove! a-root name
2234 ;;; These functions manipulate values in namespaces. For referencing the
2235 ;;; namespaces themselves, use the following:
2237 ;;; nested-ref-module a-root name
2238 ;;; nested-define-module! a-root name mod
2240 ;;; (current-module) is a natural choice for a root so for convenience there are
2243 ;;; local-ref name == nested-ref (current-module) name
2244 ;;; local-set! name val == nested-set! (current-module) name val
2245 ;;; local-define name val == nested-define! (current-module) name val
2246 ;;; local-remove name == nested-remove! (current-module) name
2247 ;;; local-ref-module name == nested-ref-module (current-module) name
2248 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2252 (define (nested-ref root names)
2255 (let loop ((cur root)
2259 (module-ref cur head #f)
2260 (let ((cur (module-ref-submodule cur head)))
2262 (loop cur (car tail) (cdr tail))))))))
2264 (define (nested-set! root names val)
2265 (let loop ((cur root)
2269 (module-set! cur head val)
2270 (let ((cur (module-ref-submodule cur head)))
2272 (error "failed to resolve module" names)
2273 (loop cur (car tail) (cdr tail)))))))
2275 (define (nested-define! root names val)
2276 (let loop ((cur root)
2280 (module-define! cur head val)
2281 (let ((cur (module-ref-submodule cur head)))
2283 (error "failed to resolve module" names)
2284 (loop cur (car tail) (cdr tail)))))))
2286 (define (nested-remove! root names)
2287 (let loop ((cur root)
2291 (module-remove! cur head)
2292 (let ((cur (module-ref-submodule cur head)))
2294 (error "failed to resolve module" names)
2295 (loop cur (car tail) (cdr tail)))))))
2298 (define (nested-ref-module root names)
2299 (let loop ((cur root)
2303 (let ((cur (module-ref-submodule cur (car names))))
2305 (loop cur (cdr names)))))))
2307 (define (nested-define-module! root names module)
2309 (error "can't redefine root module" root module)
2310 (let loop ((cur root)
2314 (module-define-submodule! cur head module)
2315 (let ((cur (or (module-ref-submodule cur head)
2316 (let ((m (make-module 31)))
2317 (set-module-kind! m 'directory)
2318 (set-module-name! m (append (module-name cur)
2320 (module-define-submodule! cur head m)
2322 (loop cur (car tail) (cdr tail)))))))
2325 (define (local-ref names)
2326 (nested-ref (current-module) names))
2328 (define (local-set! names val)
2329 (nested-set! (current-module) names val))
2331 (define (local-define names val)
2332 (nested-define! (current-module) names val))
2334 (define (local-remove names)
2335 (nested-remove! (current-module) names))
2337 (define (local-ref-module names)
2338 (nested-ref-module (current-module) names))
2340 (define (local-define-module names mod)
2341 (nested-define-module! (current-module) names mod))
2347 ;;; {The (guile) module}
2349 ;;; The standard module, which has the core Guile bindings. Also called the
2350 ;;; "root module", as it is imported by many other modules, but it is not
2351 ;;; necessarily the root of anything; and indeed, the module named '() might be
2352 ;;; better thought of as a root.
2355 (define (set-system-module! m s)
2356 (set-procedure-property! (module-eval-closure m) 'system-module s))
2358 ;; The root module uses the pre-modules-obarray as its obarray. This
2359 ;; special obarray accumulates all bindings that have been established
2360 ;; before the module system is fully booted.
2362 ;; (The obarray continues to be used by code that has been closed over
2363 ;; before the module system has been booted.)
2365 (define the-root-module
2366 (let ((m (make-module 0)))
2367 (set-module-obarray! m (%get-pre-modules-obarray))
2368 (set-module-name! m '(guile))
2369 (set-system-module! m #t)
2372 ;; The root interface is a module that uses the same obarray as the
2373 ;; root module. It does not allow new definitions, tho.
2375 (define the-scm-module
2376 (let ((m (make-module 0)))
2377 (set-module-obarray! m (%get-pre-modules-obarray))
2378 (set-module-eval-closure! m (standard-interface-eval-closure m))
2379 (set-module-name! m '(guile))
2380 (set-module-kind! m 'interface)
2381 (set-system-module! m #t)
2383 ;; In Guile 1.8 and earlier M was its own public interface.
2384 (set-module-public-interface! m m)
2388 (set-module-public-interface! the-root-module the-scm-module)
2392 ;; Now that we have a root module, even though modules aren't fully booted,
2393 ;; expand the definition of resolve-module.
2395 (define (resolve-module name . args)
2396 (if (equal? name '(guile))
2398 (error "unexpected module to resolve during module boot" name)))
2400 ;; Cheat. These bindings are needed by modules.c, but we don't want
2401 ;; to move their real definition here because that would be unnatural.
2403 (define define-module* #f)
2404 (define process-use-modules #f)
2405 (define module-export! #f)
2406 (define default-duplicate-binding-procedures #f)
2408 ;; This boots the module system. All bindings needed by modules.c
2409 ;; must have been defined by now.
2411 (set-current-module the-root-module)
2416 ;; Now that modules are booted, give module-name its final definition.
2419 (let ((accessor (record-accessor module-type 'name)))
2422 (let ((name (list (gensym))))
2423 ;; Name MOD and bind it in the module root so that it's visible to
2424 ;; `resolve-module'. This is important as `psyntax' stores module
2425 ;; names and relies on being able to `resolve-module' them.
2426 (set-module-name! mod name)
2427 (nested-define-module! (resolve-module '() #f) name mod)
2430 (define (make-modules-in module name)
2431 (or (nested-ref-module module name)
2432 (let ((m (make-module 31)))
2433 (set-module-kind! m 'directory)
2434 (set-module-name! m (append (module-name module) name))
2435 (nested-define-module! module name m)
2438 (define (beautify-user-module! module)
2439 (let ((interface (module-public-interface module)))
2440 (if (or (not interface)
2441 (eq? interface module))
2442 (let ((interface (make-module 31)))
2443 (set-module-name! interface (module-name module))
2444 (set-module-version! interface (module-version module))
2445 (set-module-kind! interface 'interface)
2446 (set-module-public-interface! module interface))))
2447 (if (and (not (memq the-scm-module (module-uses module)))
2448 (not (eq? module the-root-module)))
2449 ;; Import the default set of bindings (from the SCM module) in MODULE.
2450 (module-use! module the-scm-module)))
2452 (define (version-matches? version-ref target)
2453 (define (sub-versions-match? v-refs t)
2454 (define (sub-version-matches? v-ref t)
2455 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2457 ((number? v-ref) (eqv? v-ref t))
2460 ((>=) (>= t (cadr v-ref)))
2461 ((<=) (<= t (cadr v-ref)))
2462 ((and) (and-map matches? (cdr v-ref)))
2463 ((or) (or-map matches? (cdr v-ref)))
2464 ((not) (not (matches? (cadr v-ref))))
2465 (else (error "Invalid sub-version reference" v-ref))))
2466 (else (error "Invalid sub-version reference" v-ref)))))
2468 (and (not (null? t))
2469 (sub-version-matches? (car v-refs) (car t))
2470 (sub-versions-match? (cdr v-refs) (cdr t)))))
2472 (let ((matches? (lambda (v) (version-matches? v target))))
2473 (or (null? version-ref)
2474 (case (car version-ref)
2475 ((and) (and-map matches? (cdr version-ref)))
2476 ((or) (or-map matches? (cdr version-ref)))
2477 ((not) (not (matches? (cadr version-ref))))
2478 (else (sub-versions-match? version-ref target))))))
2480 (define (make-fresh-user-module)
2481 (let ((m (make-module)))
2482 (beautify-user-module! m)
2485 ;; NOTE: This binding is used in libguile/modules.c.
2487 (define resolve-module
2488 (let ((root (make-module)))
2489 (set-module-name! root '())
2490 ;; Define the-root-module as '(guile).
2491 (module-define-submodule! root 'guile the-root-module)
2493 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2494 (let ((already (nested-ref-module root name)))
2497 (or (not autoload) (module-public-interface already)))
2498 ;; A hit, a palpable hit.
2500 (not (version-matches? version (module-version already))))
2501 (error "incompatible module version already loaded" name))
2504 ;; Try to autoload the module, and recurse.
2505 (try-load-module name version)
2506 (resolve-module name #f #:ensure ensure))
2508 ;; No module found (or if one was, it had no public interface), and
2509 ;; we're not autoloading. Make an empty module if #:ensure is true.
2512 (make-modules-in root name)))))))))
2515 (define (try-load-module name version)
2516 (try-module-autoload name version))
2518 (define (reload-module m)
2519 "Revisit the source file corresponding to the module @var{m}."
2520 (let ((f (module-filename m)))
2522 (save-module-excursion
2524 ;; Re-set the initial environment, as in try-module-autoload.
2525 (set-current-module (make-fresh-user-module))
2526 (primitive-load-path f)
2528 ;; Though we could guess, we *should* know it.
2529 (error "unknown file name for module" m))))
2531 (define (purify-module! module)
2532 "Removes bindings in MODULE which are inherited from the (guile) module."
2533 (let ((use-list (module-uses module)))
2534 (if (and (pair? use-list)
2535 (eq? (car (last-pair use-list)) the-scm-module))
2536 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2538 ;; Return a module that is an interface to the module designated by
2541 ;; `resolve-interface' takes four keyword arguments:
2543 ;; #:select SELECTION
2545 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2546 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2547 ;; is the name in the used module and SEEN is the name in the using
2548 ;; module. Note that SEEN is also passed through RENAMER, below. The
2549 ;; default is to select all bindings. If you specify no selection but
2550 ;; a renamer, only the bindings that already exist in the used module
2551 ;; are made available in the interface. Bindings that are added later
2552 ;; are not picked up.
2556 ;; BINDINGS is a list of bindings which should not be imported.
2560 ;; PREFIX is a symbol that will be appended to each exported name.
2561 ;; The default is to not perform any renaming.
2563 ;; #:renamer RENAMER
2565 ;; RENAMER is a procedure that takes a symbol and returns its new
2566 ;; name. The default is not perform any renaming.
2568 ;; Signal "no code for module" error if module name is not resolvable
2569 ;; or its public interface is not available. Signal "no binding"
2570 ;; error if selected binding does not exist in the used module.
2572 (define* (resolve-interface name #:key
2577 (symbol-prefix-proc prefix)
2580 (let* ((module (resolve-module name #t version #:ensure #f))
2581 (public-i (and module (module-public-interface module))))
2582 (and (or (not module) (not public-i))
2583 (error "no code for module" name))
2584 (if (and (not select) (null? hide) (eq? renamer identity))
2586 (let ((selection (or select (module-map (lambda (sym var) sym)
2588 (custom-i (make-module 31)))
2589 (set-module-kind! custom-i 'custom-interface)
2590 (set-module-name! custom-i name)
2591 ;; XXX - should use a lazy binder so that changes to the
2592 ;; used module are picked up automatically.
2593 (for-each (lambda (bspec)
2594 (let* ((direct? (symbol? bspec))
2595 (orig (if direct? bspec (car bspec)))
2596 (seen (if direct? bspec (cdr bspec)))
2597 (var (or (module-local-variable public-i orig)
2598 (module-local-variable module orig)
2600 ;; fixme: format manually for now
2602 #f "no binding `~A' in module ~A"
2604 (if (memq orig hide)
2605 (set! hide (delq! orig hide))
2606 (module-add! custom-i
2610 ;; Check that we are not hiding bindings which don't exist
2611 (for-each (lambda (binding)
2612 (if (not (module-local-variable public-i binding))
2615 #f "no binding `~A' to hide in module ~A"
2620 (define (symbol-prefix-proc prefix)
2622 (symbol-append prefix symbol)))
2624 ;; This function is called from "modules.c". If you change it, be
2625 ;; sure to update "modules.c" as well.
2627 (define* (define-module* name
2628 #:key filename pure version (duplicates '())
2629 (imports '()) (exports '()) (replacements '())
2630 (re-exports '()) (autoloads '()) transformer)
2631 (define (list-of pred l)
2633 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2634 (define (valid-export? x)
2635 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2636 (define (valid-autoload? x)
2637 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
2639 (define (resolve-imports imports)
2640 (define (resolve-import import-spec)
2641 (if (list? import-spec)
2642 (apply resolve-interface import-spec)
2643 (error "unexpected use-module specification" import-spec)))
2644 (let lp ((imports imports) (out '()))
2646 ((null? imports) (reverse! out))
2649 (cons (resolve-import (car imports)) out)))
2650 (else (error "unexpected tail of imports list" imports)))))
2652 ;; We could add a #:no-check arg, set by the define-module macro, if
2653 ;; these checks are taking too much time.
2655 (let ((module (resolve-module name #f)))
2656 (beautify-user-module! module)
2658 (set-module-filename! module filename))
2660 (purify-module! module))
2663 (if (not (list-of integer? version))
2664 (error "expected list of integers for version"))
2665 (set-module-version! module version)
2666 (set-module-version! (module-public-interface module) version)))
2667 (let ((imports (resolve-imports imports)))
2668 (call-with-deferred-observers
2671 (module-use-interfaces! module imports))
2672 (if (list-of valid-export? exports)
2674 (module-export! module exports))
2675 (error "expected exports to be a list of symbols or symbol pairs"))
2676 (if (list-of valid-export? replacements)
2677 (if (pair? replacements)
2678 (module-replace! module replacements))
2679 (error "expected replacements to be a list of symbols or symbol pairs"))
2680 (if (list-of valid-export? re-exports)
2681 (if (pair? re-exports)
2682 (module-re-export! module re-exports))
2683 (error "expected re-exports to be a list of symbols or symbol pairs"))
2685 (if (not (null? autoloads))
2686 (apply module-autoload! module autoloads))
2687 ;; Wait until modules have been loaded to resolve duplicates
2689 (if (pair? duplicates)
2690 (let ((handlers (lookup-duplicates-handlers duplicates)))
2691 (set-module-duplicates-handlers! module handlers))))))
2694 (if (and (pair? transformer) (list-of symbol? transformer))
2695 (let ((iface (resolve-interface transformer))
2696 (sym (car (last-pair transformer))))
2697 (set-module-transformer! module (module-ref iface sym)))
2698 (error "expected transformer to be a module name" transformer)))
2700 (run-hook module-defined-hook module)
2703 ;; `module-defined-hook' is a hook that is run whenever a new module
2704 ;; is defined. Its members are called with one argument, the new
2706 (define module-defined-hook (make-hook 1))
2713 (define (make-autoload-interface module name bindings)
2714 (let ((b (lambda (a sym definep)
2715 (and (memq sym bindings)
2716 (let ((i (module-public-interface (resolve-module name))))
2718 (error "missing interface for module" name))
2719 (let ((autoload (memq a (module-uses module))))
2720 ;; Replace autoload-interface with actual interface if
2721 ;; that has not happened yet.
2722 (if (pair? autoload)
2723 (set-car! autoload i)))
2724 (module-local-variable i sym))))))
2725 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2726 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2727 (make-hash-table 0) #f #f #f)))
2729 (define (module-autoload! module . args)
2730 "Have @var{module} automatically load the module named @var{name} when one
2731 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2732 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2733 module '(ice-9 q) '(make-q q-length))}."
2734 (let loop ((args args))
2738 (error "invalid name+binding autoload list" args))
2740 (let ((name (car args))
2741 (bindings (cadr args)))
2742 (module-use! module (make-autoload-interface module
2744 (loop (cddr args)))))))
2749 ;;; {Autoloading modules}
2752 (define autoloads-in-progress '())
2754 ;; This function is called from "modules.c". If you change it, be
2755 ;; sure to update "modules.c" as well.
2757 (define* (try-module-autoload module-name #:optional version)
2758 (let* ((reverse-name (reverse module-name))
2759 (name (symbol->string (car reverse-name)))
2760 (dir-hint-module-name (reverse (cdr reverse-name)))
2761 (dir-hint (apply string-append
2763 (string-append (symbol->string elt) "/"))
2764 dir-hint-module-name))))
2765 (resolve-module dir-hint-module-name #f)
2766 (and (not (autoload-done-or-in-progress? dir-hint name))
2769 (lambda () (autoload-in-progress! dir-hint name))
2771 (with-fluids ((current-reader #f))
2772 (save-module-excursion
2774 ;; The initial environment when loading a module is a fresh
2776 (set-current-module (make-fresh-user-module))
2777 ;; Here we could allow some other search strategy (other than
2778 ;; primitive-load-path), for example using versions encoded
2779 ;; into the file system -- but then we would have to figure
2780 ;; out how to locate the compiled file, do auto-compilation,
2781 ;; etc. Punt for now, and don't use versions when locating
2783 (primitive-load-path (in-vicinity dir-hint name) #f)
2785 (lambda () (set-autoloaded! dir-hint name didit)))
2790 ;;; {Dynamic linking of modules}
2793 (define autoloads-done '((guile . guile)))
2795 (define (autoload-done-or-in-progress? p m)
2796 (let ((n (cons p m)))
2797 (->bool (or (member n autoloads-done)
2798 (member n autoloads-in-progress)))))
2800 (define (autoload-done! p m)
2801 (let ((n (cons p m)))
2802 (set! autoloads-in-progress
2803 (delete! n autoloads-in-progress))
2804 (or (member n autoloads-done)
2805 (set! autoloads-done (cons n autoloads-done)))))
2807 (define (autoload-in-progress! p m)
2808 (let ((n (cons p m)))
2809 (set! autoloads-done
2810 (delete! n autoloads-done))
2811 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2813 (define (set-autoloaded! p m done?)
2815 (autoload-done! p m)
2816 (let ((n (cons p m)))
2817 (set! autoloads-done (delete! n autoloads-done))
2818 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2822 ;;; {Run-time options}
2825 (define-syntax define-option-interface
2827 ((_ (interface (options enable disable) (option-set!)))
2834 (begin (interface arg) (interface))
2837 (apply (lambda (name value documentation)
2839 (if (< (string-length (symbol->string name)) 8)
2844 (display documentation)
2848 (define (enable . flags)
2849 (interface (append flags (interface)))
2851 (define (disable . flags)
2852 (let ((options (interface)))
2853 (for-each (lambda (flag) (set! options (delq! flag options)))
2857 (define-syntax-rule (option-set! opt val)
2858 (eval-when (eval load compile expand)
2859 (options (append (options) (list 'opt val)))))))))
2861 (define-option-interface
2862 (debug-options-interface
2863 (debug-options debug-enable debug-disable)
2866 (define-option-interface
2867 (read-options-interface
2868 (read-options read-enable read-disable)
2871 (define-option-interface
2872 (print-options-interface
2873 (print-options print-enable print-disable)
2878 ;;; {The Unspecified Value}
2880 ;;; Currently Guile represents unspecified values via one particular value,
2881 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2882 ;;; future if we could replace this with a return of 0 values, though.
2885 (define-syntax *unspecified*
2886 (identifier-syntax (if #f #f)))
2888 (define (unspecified? v) (eq? v *unspecified*))
2897 ;; Three fields: the procedure itself, the fluid, and the converter.
2898 (make-struct <applicable-struct-vtable> 0 'pwprpr))
2899 (set-struct-vtable-name! <parameter> '<parameter>)
2901 (define* (make-parameter init #:optional (conv (lambda (x) x)))
2902 (let ((fluid (make-fluid (conv init))))
2903 (make-struct <parameter> 0
2905 (() (fluid-ref fluid))
2906 ((x) (let ((prev (fluid-ref fluid)))
2907 (fluid-set! fluid (conv x))
2911 (define (parameter? x)
2912 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
2914 (define (parameter-fluid p)
2917 (scm-error 'wrong-type-arg "parameter-fluid"
2918 "Not a parameter: ~S" (list p) #f)))
2920 (define (parameter-converter p)
2923 (scm-error 'wrong-type-arg "parameter-fluid"
2924 "Not a parameter: ~S" (list p) #f)))
2926 (define-syntax parameterize
2929 ((_ ((param value) ...) body body* ...)
2930 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
2931 #'(let ((p param) ...)
2932 (if (not (parameter? p))
2933 (scm-error 'wrong-type-arg "parameterize"
2934 "Not a parameter: ~S" (list p) #f))
2936 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
2938 body body* ...)))))))
2942 ;;; Current ports as parameters.
2945 (let ((fluid->parameter
2946 (lambda (fluid conv)
2947 (make-struct <parameter> 0
2949 (() (fluid-ref fluid))
2950 ((x) (let ((prev (fluid-ref fluid)))
2951 (fluid-set! fluid (conv x))
2954 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
2956 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
2960 (module-remove! (current-module) 'fluid)))
2962 (port-parameterize! current-input-port %current-input-port-fluid
2963 input-port? "expected an input port")
2964 (port-parameterize! current-output-port %current-output-port-fluid
2965 output-port? "expected an output port")
2966 (port-parameterize! current-error-port %current-error-port-fluid
2967 output-port? "expected an output port"))
2975 (define current-warning-port
2976 (make-parameter (current-error-port)
2978 (if (output-port? x)
2980 (error "expected an output port" x)))))
2988 (define *repl-stack* (make-fluid '()))
2990 ;; Programs can call `batch-mode?' to see if they are running as part of a
2991 ;; script or if they are running interactively. REPL implementations ensure that
2992 ;; `batch-mode?' returns #f during their extent.
2994 (define (batch-mode?)
2995 (null? (fluid-ref *repl-stack*)))
2997 ;; Programs can re-enter batch mode, for example after a fork, by calling
2998 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
2999 ;; to abort to the outermost prompt, and call a thunk there.
3001 (define (ensure-batch-mode!)
3002 (set! batch-mode? (lambda () #t)))
3004 (define (quit . args)
3005 (apply throw 'quit args))
3009 (define (gc-run-time)
3010 (cdr (assq 'gc-time-taken (gc-stats))))
3012 (define abort-hook (make-hook))
3013 (define before-error-hook (make-hook))
3014 (define after-error-hook (make-hook))
3015 (define before-backtrace-hook (make-hook))
3016 (define after-backtrace-hook (make-hook))
3018 (define before-read-hook (make-hook))
3019 (define after-read-hook (make-hook))
3020 (define before-eval-hook (make-hook 1))
3021 (define after-eval-hook (make-hook 1))
3022 (define before-print-hook (make-hook 1))
3023 (define after-print-hook (make-hook 1))
3025 ;;; This hook is run at the very end of an interactive session.
3027 (define exit-hook (make-hook))
3029 ;;; The default repl-reader function. We may override this if we've
3030 ;;; the readline library.
3032 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3033 (if (not (char-ready?))
3035 (display (if (string? prompt) prompt (prompt)))
3036 ;; An interesting situation. The printer resets the column to
3037 ;; 0 by printing a newline, but we then advance it by printing
3038 ;; the prompt. However the port-column of the output port
3039 ;; does not typically correspond with the actual column on the
3040 ;; screen, because the input is echoed back! Since the
3041 ;; input is line-buffered and thus ends with a newline, the
3042 ;; output will really start on column zero. So, here we zero
3043 ;; it out. See bug 9664.
3045 ;; Note that for similar reasons, the output-line will not
3046 ;; reflect the actual line on the screen. But given the
3047 ;; possibility of multiline input, the fix is not as
3048 ;; straightforward, so we don't bother.
3050 ;; Also note that the readline implementation papers over
3051 ;; these concerns, because it's readline itself printing the
3052 ;; prompt, and not Guile.
3053 (set-port-column! (current-output-port) 0)))
3055 (run-hook before-read-hook)
3056 ((or reader read) (current-input-port))))
3061 ;;; {IOTA functions: generating lists of numbers}
3065 (let loop ((count (1- n)) (result '()))
3066 (if (< count 0) result
3067 (loop (1- count) (cons count result)))))
3073 ;;; with `continue' and `break'.
3076 ;; The inliner will remove the prompts at compile-time if it finds that
3077 ;; `continue' or `break' are not used.
3079 (define-syntax while
3082 ((while cond body ...)
3083 #`(let ((break-tag (make-prompt-tag "break"))
3084 (continue-tag (make-prompt-tag "continue")))
3088 (define-syntax #,(datum->syntax #'while 'break)
3092 #'(abort-to-prompt break-tag arg (... ...)))
3095 (apply abort-to-prompt break-tag args))))))
3100 (define-syntax #,(datum->syntax #'while 'continue)
3104 #'(abort-to-prompt continue-tag))
3106 (syntax-violation 'continue "too many arguments" x))
3109 (abort-to-prompt continue-tag))))))
3110 (do () ((not cond) #f) body ...))
3111 (lambda (k) (lp)))))
3115 (apply values args)))))))))
3120 ;;; {Module System Macros}
3123 ;; Return a list of expressions that evaluate to the appropriate
3124 ;; arguments for resolve-interface according to SPEC.
3126 (eval-when (compile)
3127 (if (memq 'prefix (read-options))
3128 (error "boot-9 must be compiled with #:kw, not :kw")))
3130 (define (keyword-like-symbol->keyword sym)
3131 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3133 (define-syntax define-module
3135 (define (keyword-like? stx)
3136 (let ((dat (syntax->datum stx)))
3138 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3139 (define (->keyword sym)
3140 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3142 (define (parse-iface args)
3143 (let loop ((in args) (out '()))
3146 ;; The user wanted #:foo, but wrote :foo. Fix it.
3147 ((sym . in) (keyword-like? #'sym)
3148 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3149 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3150 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3151 ((#:renamer renamer . in)
3152 (loop #'in (cons* #',renamer #:renamer out)))
3154 (loop #'in (cons* #'val #'kw out))))))
3156 (define (parse args imp exp rex rep aut)
3157 ;; Just quote everything except #:use-module and #:use-syntax. We
3158 ;; need to know about all arguments regardless since we want to turn
3159 ;; symbols that look like keywords into real keywords, and the
3160 ;; keyword args in a define-module form are not regular
3161 ;; (i.e. no-backtrace doesn't take a value).
3162 (syntax-case args ()
3164 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3165 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3166 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3167 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3168 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3169 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3170 ;; The user wanted #:foo, but wrote :foo. Fix it.
3171 ((sym . args) (keyword-like? #'sym)
3172 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3173 imp exp rex rep aut))
3174 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3175 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3176 ((#:no-backtrace . args)
3178 (parse #'args imp exp rex rep aut))
3180 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3182 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3183 ((#:version (v ...) . args)
3184 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3185 ((#:duplicates (d ...) . args)
3186 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3187 ((#:filename f . args)
3188 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3189 ((#:use-module (name name* ...) . args)
3190 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3191 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
3192 ((#:use-syntax (name name* ...) . args)
3193 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3194 #`(#:transformer '(name name* ...)
3195 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
3196 ((#:use-module ((name name* ...) arg ...) . args)
3197 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3199 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
3201 ((#:export (ex ...) . args)
3202 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3203 ((#:export-syntax (ex ...) . args)
3204 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3205 ((#:re-export (re ...) . args)
3206 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3207 ((#:re-export-syntax (re ...) . args)
3208 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3209 ((#:replace (r ...) . args)
3210 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3211 ((#:replace-syntax (r ...) . args)
3212 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3213 ((#:autoload name bindings . args)
3214 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3216 (syntax-violation 'define-module "unknown keyword or bad argument"
3220 ((_ (name name* ...) arg ...)
3221 (and-map symbol? (syntax->datum #'(name name* ...)))
3222 (with-syntax (((quoted-arg ...)
3223 (parse #'(arg ...) '() '() '() '() '()))
3224 ;; Ideally the filename is either a string or #f;
3225 ;; this hack is to work around a case in which
3226 ;; port-filename returns a symbol (`socket') for
3228 (filename (let ((f (assq-ref (or (syntax-source x) '())
3230 (and (string? f) f))))
3231 #'(eval-when (eval load compile expand)
3232 (let ((m (define-module* '(name name* ...)
3233 #:filename filename quoted-arg ...)))
3234 (set-current-module m)
3237 ;; The guts of the use-modules macro. Add the interfaces of the named
3238 ;; modules to the use-list of the current module, in order.
3240 ;; This function is called by "modules.c". If you change it, be sure
3241 ;; to change scm_c_use_module as well.
3243 (define (process-use-modules module-interface-args)
3244 (let ((interfaces (map (lambda (mif-args)
3245 (or (apply resolve-interface mif-args)
3246 (error "no such module" mif-args)))
3247 module-interface-args)))
3248 (call-with-deferred-observers
3250 (module-use-interfaces! (current-module) interfaces)))))
3252 (define-syntax use-modules
3254 (define (keyword-like? stx)
3255 (let ((dat (syntax->datum stx)))
3257 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3258 (define (->keyword sym)
3259 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3261 (define (quotify-iface args)
3262 (let loop ((in args) (out '()))
3265 ;; The user wanted #:foo, but wrote :foo. Fix it.
3266 ((sym . in) (keyword-like? #'sym)
3267 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3268 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3269 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3270 ((#:renamer renamer . in)
3271 (loop #'in (cons* #'renamer #:renamer out)))
3273 (loop #'in (cons* #''val #'kw out))))))
3275 (define (quotify specs)
3276 (let lp ((in specs) (out '()))
3279 (((name name* ...) . in)
3280 (and-map symbol? (syntax->datum #'(name name* ...)))
3281 (lp #'in (cons #''((name name* ...)) out)))
3282 ((((name name* ...) arg ...) . in)
3283 (and-map symbol? (syntax->datum #'(name name* ...)))
3284 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3285 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3290 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3291 #'(eval-when (eval load compile expand)
3292 (process-use-modules (list quoted-args ...))
3295 (define-syntax-rule (use-syntax spec ...)
3297 (eval-when (eval load compile expand)
3298 (issue-deprecation-warning
3299 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3300 (use-modules spec ...)))
3302 (include-from-path "ice-9/r6rs-libraries")
3304 (define-syntax-rule (define-private foo bar)
3307 (define-syntax define-public
3309 ((_ (name . args) . body)
3310 (define-public name (lambda args . body)))
3316 (define-syntax-rule (defmacro-public name args body ...)
3318 (defmacro name args body ...)
3319 (export-syntax name)))
3321 ;; And now for the most important macro.
3322 (define-syntax-rule (λ formals body ...)
3323 (lambda formals body ...))
3326 ;; Export a local variable
3328 ;; This function is called from "modules.c". If you change it, be
3329 ;; sure to update "modules.c" as well.
3331 (define (module-export! m names)
3332 (let ((public-i (module-public-interface m)))
3333 (for-each (lambda (name)
3334 (let* ((internal-name (if (pair? name) (car name) name))
3335 (external-name (if (pair? name) (cdr name) name))
3336 (var (module-ensure-local-variable! m internal-name)))
3337 (module-add! public-i external-name var)))
3340 (define (module-replace! m names)
3341 (let ((public-i (module-public-interface m)))
3342 (for-each (lambda (name)
3343 (let* ((internal-name (if (pair? name) (car name) name))
3344 (external-name (if (pair? name) (cdr name) name))
3345 (var (module-ensure-local-variable! m internal-name)))
3346 ;; FIXME: use a bit on variables instead of object
3348 (set-object-property! var 'replace #t)
3349 (module-add! public-i external-name var)))
3352 ;; Export all local variables from a module
3354 (define (module-export-all! mod)
3355 (define (fresh-interface!)
3356 (let ((iface (make-module)))
3357 (set-module-name! iface (module-name mod))
3358 (set-module-version! iface (module-version mod))
3359 (set-module-kind! iface 'interface)
3360 (set-module-public-interface! mod iface)
3362 (let ((iface (or (module-public-interface mod)
3363 (fresh-interface!))))
3364 (set-module-obarray! iface (module-obarray mod))))
3366 ;; Re-export a imported variable
3368 (define (module-re-export! m names)
3369 (let ((public-i (module-public-interface m)))
3370 (for-each (lambda (name)
3371 (let* ((internal-name (if (pair? name) (car name) name))
3372 (external-name (if (pair? name) (cdr name) name))
3373 (var (module-variable m internal-name)))
3375 (error "Undefined variable:" internal-name))
3376 ((eq? var (module-local-variable m internal-name))
3377 (error "re-exporting local variable:" internal-name))
3379 (module-add! public-i external-name var)))))
3382 (define-syntax-rule (export name ...)
3383 (eval-when (eval load compile expand)
3384 (call-with-deferred-observers
3386 (module-export! (current-module) '(name ...))))))
3388 (define-syntax-rule (re-export name ...)
3389 (eval-when (eval load compile expand)
3390 (call-with-deferred-observers
3392 (module-re-export! (current-module) '(name ...))))))
3394 (define-syntax-rule (export! name ...)
3395 (eval-when (eval load compile expand)
3396 (call-with-deferred-observers
3398 (module-replace! (current-module) '(name ...))))))
3400 (define-syntax-rule (export-syntax name ...)
3403 (define-syntax-rule (re-export-syntax name ...)
3404 (re-export name ...))
3411 (define* (make-mutable-parameter init #:optional (converter identity))
3412 (let ((fluid (make-fluid (converter init))))
3414 (() (fluid-ref fluid))
3415 ((val) (fluid-set! fluid (converter val))))))
3420 ;;; {Handling of duplicate imported bindings}
3423 ;; Duplicate handlers take the following arguments:
3425 ;; module importing module
3426 ;; name conflicting name
3427 ;; int1 old interface where name occurs
3428 ;; val1 value of binding in old interface
3429 ;; int2 new interface where name occurs
3430 ;; val2 value of binding in new interface
3431 ;; var previous resolution or #f
3432 ;; val value of previous resolution
3434 ;; A duplicate handler can take three alternative actions:
3436 ;; 1. return #f => leave responsibility to next handler
3437 ;; 2. exit with an error
3438 ;; 3. return a variable resolving the conflict
3441 (define duplicate-handlers
3442 (let ((m (make-module 7)))
3444 (define (check module name int1 val1 int2 val2 var val)
3445 (scm-error 'misc-error
3447 "~A: `~A' imported from both ~A and ~A"
3448 (list (module-name module)
3454 (define (warn module name int1 val1 int2 val2 var val)
3455 (format (current-warning-port)
3456 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3457 (module-name module)
3463 (define (replace module name int1 val1 int2 val2 var val)
3464 (let ((old (or (and var (object-property var 'replace) var)
3465 (module-variable int1 name)))
3466 (new (module-variable int2 name)))
3467 (if (object-property old 'replace)
3468 (and (or (eq? old new)
3469 (not (object-property new 'replace)))
3471 (and (object-property new 'replace)
3474 (define (warn-override-core module name int1 val1 int2 val2 var val)
3475 (and (eq? int1 the-scm-module)
3477 (format (current-warning-port)
3478 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3479 (module-name module)
3482 (module-local-variable int2 name))))
3484 (define (first module name int1 val1 int2 val2 var val)
3485 (or var (module-local-variable int1 name)))
3487 (define (last module name int1 val1 int2 val2 var val)
3488 (module-local-variable int2 name))
3490 (define (noop module name int1 val1 int2 val2 var val)
3493 (set-module-name! m 'duplicate-handlers)
3494 (set-module-kind! m 'interface)
3495 (module-define! m 'check check)
3496 (module-define! m 'warn warn)
3497 (module-define! m 'replace replace)
3498 (module-define! m 'warn-override-core warn-override-core)
3499 (module-define! m 'first first)
3500 (module-define! m 'last last)
3501 (module-define! m 'merge-generics noop)
3502 (module-define! m 'merge-accessors noop)
3505 (define (lookup-duplicates-handlers handler-names)
3507 (map (lambda (handler-name)
3508 (or (module-symbol-local-binding
3509 duplicate-handlers handler-name #f)
3510 (error "invalid duplicate handler name:"
3512 (if (list? handler-names)
3514 (list handler-names)))))
3516 (define default-duplicate-binding-procedures
3517 (make-mutable-parameter #f))
3519 (define default-duplicate-binding-handler
3520 (make-mutable-parameter '(replace warn-override-core warn last)
3521 (lambda (handler-names)
3522 (default-duplicate-binding-procedures
3523 (lookup-duplicates-handlers handler-names))
3530 ;;; Load is tricky when combined with relative paths, compilation, and
3531 ;;; the file system. If a path is relative, what is it relative to? The
3532 ;;; path of the source file at the time it was compiled? The path of
3533 ;;; the compiled file? What if both or either were installed? And how
3534 ;;; do you get that information? Tricky, I say.
3536 ;;; To get around all of this, we're going to do something nasty, and
3537 ;;; turn `load' into a macro. That way it can know the path of the
3538 ;;; source file with respect to which it was invoked, so it can resolve
3539 ;;; relative paths with respect to the original source path.
3541 ;;; There is an exception, and that is that if the source file was in
3542 ;;; the load path when it was compiled, instead of looking up against
3543 ;;; the absolute source location, we load-from-path against the relative
3544 ;;; source location.
3547 (define %auto-compilation-options
3548 ;; Default `compile-file' option when auto-compiling.
3549 '(#:warnings (unbound-variable arity-mismatch format)))
3551 (define* (load-in-vicinity dir path #:optional reader)
3552 (define (canonical->suffix canon)
3554 ((string-prefix? "/" canon) canon)
3555 ((and (> (string-length canon) 2)
3556 (eqv? (string-ref canon 1) #\:))
3557 ;; Paths like C:... transform to /C...
3558 (string-append "/" (substring canon 0 1) (substring canon 2)))
3561 ;; Returns the .go file corresponding to `name'. Does not search load
3562 ;; paths, only the fallback path. If the .go file is missing or out of
3563 ;; date, and auto-compilation is enabled, will try auto-compilation, just
3564 ;; as primitive-load-path does internally. primitive-load is
3565 ;; unaffected. Returns #f if auto-compilation failed or was disabled.
3567 ;; NB: Unless we need to compile the file, this function should not cause
3568 ;; (system base compile) to be loaded up. For that reason compiled-file-name
3569 ;; partially duplicates functionality from (system base compile).
3571 (define (compiled-file-name canon-path)
3572 ;; FIXME: would probably be better just to append SHA1(canon-path)
3573 ;; to the %compile-fallback-path, to avoid deep directory stats.
3574 (and %compile-fallback-path
3576 %compile-fallback-path
3577 (canonical->suffix canon-path)
3578 (cond ((or (null? %load-compiled-extensions)
3579 (string-null? (car %load-compiled-extensions)))
3580 (warn "invalid %load-compiled-extensions"
3581 %load-compiled-extensions)
3583 (else (car %load-compiled-extensions))))))
3585 (define (fresh-compiled-file-name name go-path)
3588 (let* ((scmstat (stat name))
3589 (gostat (and (not %fresh-auto-compile)
3590 (stat go-path #f))))
3592 (or (> (stat:mtime gostat) (stat:mtime scmstat))
3593 (and (= (stat:mtime gostat) (stat:mtime scmstat))
3594 (>= (stat:mtimensec gostat)
3595 (stat:mtimensec scmstat)))))
3599 (format (current-warning-port)
3600 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
3603 (%load-should-auto-compile
3604 (%warn-auto-compilation-enabled)
3605 (format (current-warning-port) ";;; compiling ~a\n" name)
3608 (resolve-interface '(system base compile))
3611 #:opts %auto-compilation-options
3612 #:env (current-module))))
3613 (format (current-warning-port) ";;; compiled ~a\n" cfn)
3617 (format (current-warning-port)
3618 ";;; WARNING: compilation of ~a failed:\n" name)
3619 (for-each (lambda (s)
3620 (if (not (string-null? s))
3621 (format (current-warning-port) ";;; ~a\n" s)))
3623 (call-with-output-string
3624 (lambda (port) (print-exception port #f k args)))
3628 (define (absolute-path? path)
3629 (string-prefix? "/" path))
3631 (define (load-absolute abs-path)
3632 (let ((cfn (let ((canon (false-if-exception (canonicalize-path abs-path))))
3634 (let ((go-path (compiled-file-name canon)))
3636 (fresh-compiled-file-name abs-path go-path)))))))
3640 (%load-hook abs-path))
3641 (load-compiled cfn))
3642 (start-stack 'load-stack
3643 (primitive-load abs-path)))))
3645 (save-module-excursion
3647 (with-fluids ((current-reader reader)
3648 (%file-port-name-canonicalization 'relative))
3650 ((or (absolute-path? path))
3651 (load-absolute path))
3652 ((absolute-path? dir)
3653 (load-absolute (in-vicinity dir path)))
3655 (load-from-path (in-vicinity dir path))))))))
3658 (make-variable-transformer
3660 (let* ((src (syntax-source x))
3661 (file (and src (assq-ref src 'filename)))
3662 (dir (and (string? file) (dirname file))))
3665 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
3669 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
3673 ;;; {`cond-expand' for SRFI-0 support.}
3675 ;;; This syntactic form expands into different commands or
3676 ;;; definitions, depending on the features provided by the Scheme
3682 ;;; --> (cond-expand <cond-expand-clause>+)
3683 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3684 ;;; <cond-expand-clause>
3685 ;;; --> (<feature-requirement> <command-or-definition>*)
3686 ;;; <feature-requirement>
3687 ;;; --> <feature-identifier>
3688 ;;; | (and <feature-requirement>*)
3689 ;;; | (or <feature-requirement>*)
3690 ;;; | (not <feature-requirement>)
3691 ;;; <feature-identifier>
3692 ;;; --> <a symbol which is the name or alias of a SRFI>
3694 ;;; Additionally, this implementation provides the
3695 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3696 ;;; determine the implementation type and the supported standard.
3698 ;;; Currently, the following feature identifiers are supported:
3700 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3702 ;;; Remember to update the features list when adding more SRFIs.
3705 (define %cond-expand-features
3706 ;; Adjust the above comment when changing this.
3710 srfi-0 ;; cond-expand itself
3711 srfi-4 ;; homogenous numeric vectors
3712 srfi-6 ;; open-input-string etc, in the guile core
3713 srfi-13 ;; string library
3714 srfi-14 ;; character sets
3715 srfi-23 ;; `error` procedure
3716 srfi-39 ;; parameterize
3717 srfi-55 ;; require-extension
3718 srfi-61 ;; general cond clause
3721 ;; This table maps module public interfaces to the list of features.
3723 (define %cond-expand-table (make-hash-table 31))
3725 ;; Add one or more features to the `cond-expand' feature list of the
3728 (define (cond-expand-provide module features)
3729 (let ((mod (module-public-interface module)))
3731 (hashq-set! %cond-expand-table mod
3732 (append (hashq-ref %cond-expand-table mod '())
3735 (define-syntax cond-expand
3737 (define (module-has-feature? mod sym)
3738 (or-map (lambda (mod)
3739 (memq sym (hashq-ref %cond-expand-table mod '())))
3742 (define (condition-matches? condition)
3743 (syntax-case condition (and or not)
3745 (and-map condition-matches? #'(c ...)))
3747 (or-map condition-matches? #'(c ...)))
3749 (if (condition-matches? #'c) #f #t))
3752 (let ((sym (syntax->datum #'c)))
3753 (if (memq sym %cond-expand-features)
3755 (module-has-feature? (current-module) sym))))))
3757 (define (match clauses alternate)
3758 (syntax-case clauses ()
3759 (((condition form ...) . rest)
3760 (if (condition-matches? #'condition)
3762 (match #'rest alternate)))
3765 (syntax-case x (else)
3766 ((_ clause ... (else form ...))
3767 (match #'(clause ...)
3769 #'(begin form ...))))
3771 (match #'(clause ...)
3773 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
3775 ;; This procedure gets called from the startup code with a list of
3776 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3778 (define (use-srfis srfis)
3779 (process-use-modules
3781 (list (list 'srfi (string->symbol
3782 (string-append "srfi-" (number->string num))))))
3787 ;;; srfi-55: require-extension
3790 (define-syntax require-extension
3792 (syntax-case x (srfi)
3794 (and-map integer? (syntax->datum #'(n ...)))
3798 (datum->syntax x (symbol-append 'srfi- n)))
3800 (map number->string (syntax->datum #'(n ...)))))))
3801 #'(use-modules (srfi srfi-n) ...)))
3803 (identifier? #'type)
3804 (syntax-violation 'require-extension "Not a recognized extension type"
3808 ;;; Defining transparently inlinable procedures
3811 (define-syntax define-inlinable
3812 ;; Define a macro and a procedure such that direct calls are inlined, via
3813 ;; the macro expansion, whereas references in non-call contexts refer to
3814 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
3816 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
3818 (define prefix (string->symbol "% "))
3819 (define (make-procedure-name name)
3821 (symbol-append prefix (syntax->datum name)
3825 ((_ (name formals ...) body ...)
3826 (identifier? #'name)
3827 (with-syntax ((proc-name (make-procedure-name #'name))
3828 ((args ...) (generate-temporaries #'(formals ...))))
3830 (define (proc-name formals ...)
3831 (syntax-parameterize ((name (identifier-syntax proc-name)))
3833 (define-syntax-parameter name
3837 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
3838 (lambda (formals ...)
3843 #'proc-name))))))))))
3847 (define using-readline?
3848 (let ((using-readline? (make-fluid)))
3849 (make-procedure-with-setter
3850 (lambda () (fluid-ref using-readline?))
3851 (lambda (v) (fluid-set! using-readline? v)))))
3855 ;;; {Deprecated stuff}
3859 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3863 ;;; SRFI-4 in the default environment. FIXME: we should figure out how
3864 ;;; to deprecate this.
3868 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3872 ;;; A few identifiers that need to be defined in this file are really
3873 ;;; internal implementation details. We shove them off into internal
3874 ;;; modules, removing them from the (guile) module.
3877 (define-module (system syntax))
3880 (define (steal-bindings! from to ids)
3883 (let ((v (module-local-variable from sym)))
3884 (module-remove! from sym)
3885 (module-add! to sym v)))
3887 (module-export! to ids))
3889 (steal-bindings! the-root-module (resolve-module '(system syntax))
3890 '(syntax-local-binding
3892 syntax-locally-bound-identifiers
3893 syntax-session-id)))
3898 ;;; Place the user in the guile-user module.
3901 ;; Set filename to #f to prevent reload.
3902 (define-module (guile-user)
3903 #:autoload (system base compile) (compile compile-file)
3906 ;; Remain in the `(guile)' module at compilation-time so that the
3907 ;; `-Wunused-toplevel' warning works as expected.
3908 (eval-when (compile) (set-current-module the-root-module))
3910 ;;; boot-9.scm ends here